乐活广场页的相关逻辑

/**
 * @fileoverview blog-list-plaza
 * @desc 博文广场瀑布流展示模式,
 * @author baohe.oyt<[email protected]>
 * @date 20120922
 * @version 1.0
 * @depends kissy, widgets/ImageCtrl/ImageCtrl,widgets/UserOperate/UserOperate,widgets/Waterfall/Waterfall,widgets/Pagination/Pagination,menubutton,template,widgets/Store/Store
 */
KISSY.app('LEHUO');
LEHUO.namespace('blogListPlaza');
LEHUO.blogListPlaza = (function () {
    var S = KISSY, 
        D = S.DOM, 
        E = S.Event,
        _A = S.all,
        _O = S.one,
        
        defaultWidth = 235,//图片默认宽度,修改的话,需要同步改模板
        imageMaxHeight = 480,//图片最大高度
        marginTop = 10,//瀑布流item的垂直间距
        BREAK_MARK = '||',//多个热门标签的分隔符
        isNormalListDefault = false,//列表浏览模式默认值(瀑布流)
        isFirstTimeGetData = true,
        listTypeLocalName = 'plazaListType',
        maxNum = 99999,//阅读评论收集数最大值
        maxNumStr = '99999+',//达到最大值时的替代string
        minHeight = 90,//瀑布流文字块最低高度
        waterfallPerPage = 50,
        normalListPerPage = 50,
        
        tagmap = {//热门标签对应表
            jujia        :   "居家",
            diy          :   "手工DIY",
            jiaju        :   "家居",
            xiaohuxing   :   "小户型",
            jujiaqiaomen :   "居家窍门",
            zhuangxiu    :   "装修",
            yijia       : "宜家",
            dapei       : "搭配",
            shaiwu      : "晒物",
            fushi       : "服饰",
            shishang    : "时尚",
            jiepai      : "街拍",
            peishi      : "配饰",
            zherou      : "遮肉",
            xianshou    : "显瘦",
            mingxing    : "明星",
            meishi      : "美食",
            tianpin     : "甜品",
            xiaochi     : "小吃",
            liangtang   : "靓汤",
            lanrencaipu   : "懒人菜谱",
            shoushenshipu : "瘦身食谱",
            meibaican   : "美白餐",
            yingyangcan : "营养餐",
            huazhuang   : "化妆",
            zatoufa     : "扎头发",
            bianfa      : "编发",
            huayanxian  : "画眼线"
        },
        
        waterfallTemplate = '<div class="waterfall-item">\
                                <div class="item-con">\
                                    <h3 class="title">\
                                        <a href="/article_detail.htm?article_id={{articleId}}" target="_blank" title="{{articletitle}}">\
                                         {{#if recommend != 0}}\
                                        <span class="Jcss_jian">[荐]</span>\
                                        {{/if}}\
                                        {{#if original == 1}}\
                                        <span class="Jcss_jian">[原创]</span>\
                                        {{/if}}\
                                        {{articletitle}}\
                                        </a>\
                                    </h3>\
                                    <span class="author">作者:\
                                    <a target="_blank" href="{{nameurl}}" title="{{username}}">{{username}}\
                                        {{#if role == "2"}}\
                                            <s class="vip-ico"></s>\
                                        {{/if}}\
                                        {{#if role == "5"}}\
                                            <s class="vip-ico"></s>\
                                        {{/if}}\
                                    </a>\
                                    </span>\
                                    {{#if summarizeimg != ""}}\
                                        <div class="img-box">\
                                            <a class="big-img" target="_blank" href="/article_detail.htm?article_id={{articleId}}">\
                                                <img class="oneimg" style="width:235px" src="{{summarizeimg}}"/>\
                                            </a>\
                                        </div>\
                                        <s class="mask"></s>\
                                    {{/if}}\
                                    <p class="para">{{summarize}}<a class="lookMore" target="_blank" href="/article_detail.htm?article_id={{articleId}}">阅读全文</a></p>\
                                    <ul class="operation clearfix">\
                                        <li class="read-li">\
                                            <a target="_blank" class="read icon" href="/article_detail.htm?article_id={{articleId}}" title="阅读">{{read}}</a>\
                                        </li>\
                                        <li class="collect-li J_operate" data-articleid="{{articleId}}" data-title="{{articletitle}}" data-userid="{{userid}}">\
                                            {{#if isCollect}}\
                                            <a class="collect icon cancelcollectbtn" href="javascript:void(0);" title="取消收集">{{collect}}</a>\
                                            {{/if}}\
                                            {{#if !isCollect}}\
                                            <a class="collect icon collectbtn" href="javascript:void(0);" title="收集">{{collect}}</a>\
                                            {{/if}}\
                                        </li>\
                                        <li class="comment-li" data-articleid="{{articleId}}" data-title="{{articletitle}}" data-userid="{{userid}}">\
                                            <a class="comment icon" target="_blank" href="/article_detail.htm?article_id={{articleId}}" title="评论">\
                                                {{#if commentcount != 0}}\
                                                   {{commentcount}}\
                                                {{/if}}\
                                            </a>\
                                        </li>\
                                    </ul>\
                                </div>\
                                <div class="boxshadow"></div>\
                            </div>',
        
        listTemplate = '<div>\
            <div class="blog-list-item clearfix">\
                <div class="list-item-left">\
                    <a href="{{nameurl}}" target="_blank" class="portrait">\
                    {{#if portrait == ""}}\
                    <img src="http://a.tbcdn.cn/app/sns/img/default/avatar-120.png" alt="" />\
                    {{/if}}\
                    <img src="{{portrait}}" alt="" />\
                    {{#if role == "2"}}\
                    <s class="vip-ico"></s></a>\
                    {{/if}}\
                    {{#if role == "5"}}\
                    <s class="vip-ico"></s></a>\
                    {{/if}}\
                    <a href="{{nameurl}}" target="_blank" class="article-author">{{username}}</a>\
                </div>\
                <div class="list-item-right">\
                    <div class="item-right-center clearfix">\
                        <div class="center-describe">\
                            <a href="/article_detail.htm?article_id={{articleId}}" target="_blank" class="article-name">\
                             {{#if recommend != 0}}\
                            <span class="Jcss_jian">[荐]</span>\
                            {{/if}}\
                            {{#if original == 1}}\
                            <span class="Jcss_jian">[原创]</span>\
                            {{/if}}\
                            {{articletitle}}\
                            </a>\
                        </div>\
                        <div class="article-content clearfix">\
                            {{#if summarizeimg != ""}}\
                            <div class="img-wrap"><a href="/article_detail.htm?article_id={{articleId}}" target="_blank"><img class="oneimg" src="{{summarizeimg}}" alt="" /></a></div>\
                            {{/if}}\
                            <div class="article-text">{{summarize}}<a href="/article_detail.htm?article_id={{articleId}}" target="_blank" class="lookMore">阅读全文</a></div>\
                            <div class="article-tags">\
                                <span class="{{#if summarizeimg != ""}}tags-wrap-small{{#elseif summarizeimg == ""}}tags-wrap{{/if}}">\
                                {{#each tags}}\
                                    <a target="_blank" href="/article_plaza.htm?per_page=30&pageNum=1&key={{encodeURIComponent(_ks_value)}}&newArticle=false&count=false">{{_ks_value}}</a>\
                                {{/each}}\
                                </span>\
                            </div>\
                        </div>\
                        {{#if sourceUrl != ""}}\
                        <div class="source">来源<div class="divpop hidden"><b></b><a href="{{sourceUrl}}" target="_blank">{{from}}</a></div></div>\
                        {{/if}}\
                        <ul class="operation clearfix">\
                            <li class="comment-li" data-articleid="{{articleId}}" data-title="{{articletitle}}" data-userid="{{userid}}">\
                                <a class="comment icon" target="_blank" href="/article_detail.htm?article_id={{articleId}}" title="评论">\
                                    {{#if commentcount != 0}}\
                                       {{commentcount}}\
                                    {{/if}}\
                                </a>\
                            </li>\
                            <li class="collect-li J_operate" data-articleid="{{articleId}}" data-title="{{articletitle}}" data-userid="{{userid}}">\
                            {{#if isCollect}}\
                            <a class="collect icon cancelcollectbtn" href="javascript:void(0);" title="取消收集">{{collect}}</a>\
                            {{/if}}\
                            {{#if !isCollect}}\
                            <a class="collect icon collectbtn" href="javascript:void(0);" title="收集">{{collect}}</a>\
                            {{/if}}\
                            </li>\
                            <li class="read-li">\
                                <a target="_blank" class="read icon" href="/article_detail.htm?article_id={{articleId}}" title="阅读">{{read}}</a>\
                            </li>\
                        </ul>\
                    </div>\
                    <div class="list-decorate"></div>\
                    <b class="list-c"></b>\
                    <div class="list-boxshadow"></div>\
                </div>\
            </div>\
            </div>',
        
        paginationHTML = '{{#! 显示首页 }}'+
                        '{{#if currentPage === startPage }}'+
                        '<a class="pg-prev pg-first pg-disabled">首页</a>'+
                        '{{#else}}'+
                        '<a class="pg-prev pg-first" href="#contents" data-page="{{ startPage }}">首页</a>'+
                        '{{/if}}'+
                        ''+
                        '{{#! 显示上一页 }}'+
                        '{{#if currentPage === startPage }}'+
                        '<a class="pg-prev pg-disabled">上一页</a>'+
                        '{{#else}}'+
                        '<a class="pg-prev" href="#contents" data-page="{{ currentPage - 1 }}">上一页</a>'+
                        '{{/if}}'+
                        ''+
                        '{{#if showPageNum }}'+
                        '{{#! 左边固定显示几页, 如固定显示 1 和 2 }}'+
                        '{{#if currentPage > startPage + alwaysDisplayCount - 1}}'+
                        '{{#for var i = 0; i < alwaysDisplayCount; i++ }}'+
                        '{{#! 避免后面重复显示 }}'+
                        '{{#if i + startPage < startIndex }}'+
                        '<a class="pg-page pg-item" href="#contents" data-page="{{ i + startPage }}">{{ i + startPage }}</a>'+
                        '{{/if}}'+
                        '{{/for}}'+
                        '{{/if}}'+
                        ''+
                        '{{#! 是否显示省略号 }}'+
                        '{{#if ellipseText && startIndex > startPage + alwaysDisplayCount }}'+
                        '<span class="pg-item">…</span>'+
                        '{{/if}}'+
                        ''+
                        '{{#! 显示页数 }}'+
                        '{{#for var i = startIndex; i <= endIndex; i++ }}'+
                        '{{#if currentPage !== i }}'+
                        '<a class="pg-page pg-item" href="#contents" data-page="{{ i }}">{{ i }}</a>'+
                        '{{#else}}'+
                        '<span class="pg-current pg-item">{{ i }}</span>'+
                        '{{/if}}'+
                        '{{/for}}'+
                        ''+
                        '{{#! 是否显示省略号 }}'+
                        '{{#if ellipseText && endIndex < endPage - alwaysDisplayCount }}'+
                        '<span class="pg-item">…</span>'+
                        '{{/if}}'+
                        ''+
                        '{{#! 右边固定显示几页 }}'+
                        '{{#if currentPage < endPage - alwaysDisplayCount + 1 }}'+
                        '{{#for var i = endPage - alwaysDisplayCount + 1; i <= endPage; i++ }}'+
                        '{{#if i > endIndex }}'+
                        '<a class="pg-page pg-item" href="#contents" data-page="{{ i }}">{{ i }}</a>'+
                        '{{/if}}'+
                        '{{/for}}'+
                        '{{/if}}'+
                        '{{/if}}'+
                        ''+
                        '{{#! 显示下一页 }}'+
                        '{{#if currentPage === endPage }}'+
                        '<a class="pg-next pg-disabled">下一页</a>'+
                        '{{#else}}'+
                        '<a class="pg-next" href="#contents" data-page="{{ currentPage + 1 }}">下一页</a>'+
                        '{{/if}}'+
                        ''+
                        '{{#! 显示末页 }}'+
                        '{{#if currentPage === endPage }}'+
                        '<a class="pg-next pg-last pg-disabled" href="#contents">末页</a>'+
                        '{{#else}}'+
                        '<a class="pg-next pg-last" href="#contents" data-page="{{ endPage }}">末页</a>'+
                        '{{/if}}'+
                        ''+
                        '{{#! 显示当前页和总页数}}'+
                        '<span class="pg-skip">'+
                        '共{{ endPage - startPage + 1 }}页 到第'+
                        '<!--<form method="get" action="/search?q=mp3&amp;tab=all" >-->'+
                        '<input type="text" id="J_jumpTo" size="2" class="pg-jump" value="{{ currentPage }}"/>页'+
                        '<button type="submit" class="J_jumpToBtn pg-next">确定</button>'+
                        '<!--</form>-->'+
                        '</span>'+
                        '<select name="decorateSelect" id="decorateSelect">'+
                        '<option value="10">10</option>'+
                        '<option value="20">20</option>'+
                        '<option value="30">30</option>'+
                        '<option value="40">40</option>'+
                        '<option value="50">50</option>'+
                        '</select>',
        //loading
        loading = D.create('<img src="http://img01.taobaocdn.com/tps/i1/T1kKy9XnNcXXXXXXXX-42-42.gif" class="loading" />');
        loading.hide = function() {
            var self = this;
            
            D.remove(self);
        };
        loading.show = function() {
            var self = this,
            	con = D.get('#page-content-5');
            
            if(D.contains(con, self) || D.get('.loading', con))return;//检测容器中是否已经存在该元素
            D.prepend(self, con);
        };
        
        /**
         * this的常用属性如下:
         * 
         * content  容器
         * leftMessage 待加载数据集合
         * pagesize 一页信息个数???
         * message 所有请求来的的信息
         * isNormalList 是不是常规列表(注意!为了有记忆功能,不要直接赋值,要用工具set_isNormalList赋值)
         * isNewArticle 是不是最新浏览
         * store 本地存储的实例化对象
         * toTopBtn 回到顶部按钮
         * isCreateNormalListStructure 普通模式,每页第一次为false,scroll触发信息插入为true,每次翻页重新置false
         * isCreateWaterFallStructure  瀑布流模式,同上
         * widgets 相关组件
         * 
         */
        
        
        return {
            config: {
                getPageUrl : "",
                getListUrl : "",//废弃
                param:{},
                collectajax:'/ajax/article_collect.htm',
                cancelcollect:'/ajax/article_collect.htm?p=delete',
                //获取已有专辑列表
                getAlbumsAjax : '/ajax/album_title_list.htm',
                //创建专辑
                createNewAjax : '/ajax/album_create.htm'
            },
            
            init: function() {
                var self = this,
                    widgetStr = 'widgets/ImageCtrl/ImageCtrl,widgets/UserOperate/UserOperate,widgets/Waterfall/Waterfall,widgets/Pagination/Pagination,menubutton,template,widgets/Store/Store'; 
                
                S.use(widgetStr, function(S, IC, UO, Waterfall, Pagination, MenuButton, Template, Store) {
                    self.widgets = {
                        //操作给常规list设置图片的组件
                        'IC': IC,
                        //用户操作组件(收集和取消收集等)
                        'UO': UO,
                        'Waterfall': Waterfall,
                        'Pagination': Pagination,
                        'MenuButton': MenuButton,
                        'Template': Template,
                        'Store': Store
                    };
                        
                    S.ready(function() {
                        self._initParam();
                        // 优先从url上抓取key,填充至当前标签
                        self.renderHotLabel(function() {
                            //初始化热门标签筛选
                             self.bindMoreLabelEvent();
                        });
                        //初始化“回到顶部功能”
                        self._backTop();
                        //初始化控制板展示
                        self.setRankAndMode();
                        //监听热门文章和最新文章的切换按钮,再渲染页码,回调函数中请求数据
                        self._sortType();
                        //列表模式切换监听
                        self._modeType();
                        //渲染信息
                        self._renderData();
                    });
                });
            },
            /**
             * 初始设置参数
             */
            _initParam: function() {
                var self = this,
                    listType,//从本地存储取出值
                	rankType = self.getArguments("newArticle"),//取是按照“热门”还是“最新”排列
                    modeType = self.getArguments("normalList");//取是按照“常规”还是“瀑布流”排列

                self.store = new self.widgets.Store({type:'local'});//本地存储的实例化对象
                listType = self.store.get(listTypeLocalName);
            	self.isNewArticle = (rankType === 'false' || rankType === 'undefined')? false : true;
                
                //链接里有明确的normalList = true或者false的优先,本地存储的次之,最后再默认的                
                if(modeType === 'true' || modeType === 'false'){
                    (modeType === 'true')? self.set_isNormalList(true) : self.set_isNormalList(false);
                }else{
                    listType? self.set_isNormalList(listType) : self.set_isNormalList(isNormalListDefault);
                }
                
         		self.content = D.get('#page-content-5');
                self.isCreateNormalListStructure = false;//是否已经绑创建通浏览模式的结构,事件监听;
                self.isCreateWaterFallStructure = false;//是否已经创建好瀑布流的结构;
                self.waterRenderNum = 10;//瀑布流一次渲染10个;
            },
            /**
             * 重新加载数据(1.初次打开,2. 浏览模式切换)
             */
            _renderData: function() {
            	var self = this;
            	
            	//请求页面总页数
                self._requestAllData(function(idx) {
                    //idx是当前数据的页码,翻页的时候用,这里不用
                    self._createPagination();
                });
            },
            /**
             * 热门标签部分的初始化
             */
            bindMoreLabelEvent: function() {
                var self = this,
                    labelBox = S.one('.inner'),
                    labelUlHeight = S.one('.labelList').height(),
                    moreLabel = S.one('.tips-bar .morelabel');

                if(labelUlHeight <= 30)return;
                moreLabel.show();
                moreLabel.on('click', function(e) {
                    if(labelBox.hasClass('lock')){
                        labelBox.removeClass('lock');
                        moreLabel.html('收起');
                        moreLabel.addClass('open');
                        return;
                    }
                    labelBox.addClass('lock');
                    moreLabel.html('更多');
                    moreLabel.removeClass('open');
                });
            },
            /**
             * 通过
             * isNormalList 是不是常规列表
        	 * isNewArticle 是不是最新浏览
        	 * 来重新设置展示(操作面板、回顶按钮)
             */
            setRankAndMode: function() {
            	var self = this,
            		rankBtn = D.get('#J_check_rank'),
                    modeBtn = D.get('#J_check_mode'),
            		rankClassName = self.isNewArticle? 'new' : 'hot',
            		currentRank = D.get('.'+ rankClassName, rankBtn);

            	D.addClass(currentRank, 'current');
            	D.prepend(currentRank, rankBtn);
				D.removeClass(D.next(currentRank), 'current');
            	
            	if(self.isNormalList) {//常规list
            		D.addClass(modeBtn, 'first');
            	} else {//瀑布流
            		D.removeClass(modeBtn, 'first');
            	}
            	//重置回到顶部按钮的水平位置
                self.toTopBtn.resetMarginRight();
            },
            /**
             * 面包屑的展示
             */
            renderHotLabel: function(callback) {
                var self = this,
                    newCrumbs = '',//最新的面包屑
                    crumbs = D.get('.current-tips'),//面包屑容器
                    currentTag = D.get("#J_tagInfo"),//可能不需要了
                    tagName = self.getArguments("key"),//取参数key
                    hottag = self.getArguments("hottag"),//取热门标签
                    //hotBtn = D.get("#hot-type"),
                    //newBtn = D.get("#new-type"),
                    labelListBox = D.get('.labelList'),//筛选标签容器
                    labelListHtml = '',
                    labelList,
                    len,
                    tags,//把key参数值断开的集合
                    hottagname = tagmap[hottag];//获得热门标签参数的对应中文
                
                //赋值给这里的命名空间,给发请求的时候使用
                self.key = (!tagName || tagName === 'undefined')? '' : tagName ;
                
                //热门标签请求并且渲染
                S.ajax({
                    url: self.config.siftUrl,
                    dataType: 'json',
                    data: {
                        key: encodeURIComponent(self.key)
                    },
                    success: function(data) {
                        if(!data.success)return;
                        //返回空的数组,没有相关标签
                        if(data.labelList.length === 0)return;
                        S.one('.tips-bar').one('.inner').show();
                        labelList = data.labelList;
                        len = labelList.length
                        for(var i=0; i<len; i++){
                            labelListHtml += '<li><a href="'+ labelList[i].link +'">'+ labelList[i].name +'</a></li>';
                        }
                        D.html(labelListBox, labelListHtml);
                        callback();
                    }
                });
            	
                //hottag存在
                if(hottagname != '' && hottagname != undefined) {
                    newCrumbs = D.html(crumbs) + '<span class="point">&gt;</span><a href="#" id="J_tagInfo">'+ hottagname +'</a>';
                    D.html(crumbs, newCrumbs);
                    document.title = hottagname+' — 淘宝乐活+';
                    return;
                }
                if(self.key == '') {
                    document.title = '全部标签'+' — 淘宝乐活+';
                    return;
                }
                var tags = decodeURIComponent(tagName).split(BREAK_MARK),
                    len = tags.length;
                
                document.title = tags[len-1]+' — 淘宝乐活+';
                for(var i=0; i<len; i++) {
                    if(i == len - 1){
                        newCrumbs += '<span class="point">&gt;</span><a href="javascript:void(0);" id="J_tagInfo">'+ tags[i] +'</a>';
                        continue;
                    }
                    newCrumbs += '<span class="point">&gt;</span><a href="/article_plaza.htm?per_page=30&pageNum=1&key='+ encodeURIComponent(tags[i]) +'" id="J_tagInfo">'+ tags[i] +'</a>';
                }
                D.html(crumbs, D.html(crumbs) + newCrumbs);
            },
            /**
             * 重新设置渲染条件
             * 1.页面翻页的时候用
             */
            resetPageParam: function() {
                var self = this,
                    brooks,
                    paganation;
                
                loading.show();
                //创建新瀑布流实例前,销毁之前的瀑布流实例
                self.waterfall = self.waterfall || {};
                if(self.waterfall.waterfallCase){
                	self.waterfall.waterfallCase.end();
                }
                /**
                 * 给普通list,清理事件
                 */
                self._stopNormalList();
                
                //普通模式
                //{{
                if(self.isNormalList) {
                    self.isCreateNormalListStructure = false;//翻页的后,结构需要重新来
                    D.html(self.content, '');
                    paganation = D.get('.dr-blog-list-plaza #page5');
                    if(!paganation){
                        D.append(D.get('#page5'), D.get('.dr-blog-list-plaza'));
                    }
                    return;
                }
                //}}
                
                //瀑布流模式
                //{{
                
                if(D.get('#page-content-5 .leftCon')) {
                    var brooks = D.query('.J_plaza_brook'),
                        len = brooks.length;

                    for(var i=0; i<len; i++) {
                        D.html(brooks[i], '');
                    }
                    self.isCreateWaterFallStructure = true;//表示已经创建瀑布流结构
                } else {
                    self.isCreateWaterFallStructure = false;//表示未创建瀑布流结构
                }
                //把页码挪到大容下中
                paganation = D.get('.dr-blog-list-plaza #page5');
                if(paganation){
                    D.insertAfter(paganation, D.get('#contents'));
                }
                //}}
            },
            /**
             * 当前页信息渲染结束后的操作
             * 1.展示页码
             */
            _currentPageRenderOver: function() {
                var self = this;
                //普通模式
                if(self.isNormalList) {
                    D.css("#page5", 'display' , 'block');
                    E.remove(window, 'resize scroll', self._eventBlogList.renderFn);
                    return;
                }
                //瀑布流模式
                D.css("#page5", 'display' , 'block');
            },
            /**
             * 渲染方式选择器
             */
            _rendering: function(){
                var self = this;
                //普通列表
                if(self.isNormalList){
                    //给普通的列表绑定渲染信息的事件监听,只在第一次绑定!
                    if(!self.isCreateNormalListStructure){
                        self._createNormalListStructure();
                    }
                    self._createList();
                    return;
                }
                
                //瀑布流
                //给瀑布流绑定渲染信息的事件监听,只在第一次绑定!
                if(!self.isCreateWaterFallStructure){
                    self._createWaterFallStructure();
                }
                self._createWaterFall();
            },
            /**
             * 热门排序和最新文章切换
             */
            _sortType: function() {
                var self = this,
                	rankBtn = D.get('#J_check_rank');
                	
                E.on(rankBtn, 'mouseenter', function(e) {
                	D.removeClass(rankBtn, 'lock');
                });
                E.on(rankBtn, 'mouseleave', function(e) {
                	D.addClass(rankBtn, 'lock');
                });
                
                E.on(D.get('.hot', rankBtn), 'click', function(e) {
                	e.halt();
                	//D.addClass(rankBtn, 'lock');
                	if(D.hasClass(e.currentTarget, 'current'))return;
                	
                	D.addClass(rankBtn, 'lock');
                	self.isNewArticle = false;
                	self.setRankAndMode();
                	//hot和new切换,页码数据是一样的
                	self._createPagination();
                });
                E.on(D.get('.new', rankBtn), 'click', function(e) {
                	e.halt();
                	//D.addClass(rankBtn, 'lock');
                	if(D.hasClass(e.currentTarget, 'current'))return;
                	
                	D.addClass(rankBtn, 'lock');
                	self.isNewArticle = true;
                	self.setRankAndMode();
                	//同hot
                	self._createPagination();
                });
            },
            /**
             * 列表模式切换(常规和瀑布流)
             */
            _modeType: function() {
            	var self = this,
            		modeBtn = D.get('#J_check_mode');
            	
            	E.on(D.get('.list', modeBtn), 'click', function(e) {
            		e.halt();
            		if(D.hasClass(modeBtn, 'first'))return;

            		self.set_isNormalList(true);
            		self.setRankAndMode();
            		
            		self._createNormalListStructure();
            		loading.show();
            		//模式改变,页码会变,不能直接_createPagination
                	self._renderData();
            	});
            	
            	E.on(D.get('.big-img', modeBtn), 'click', function(e) {
            		e.halt();
            		if(!D.hasClass(modeBtn, 'first'))return;

            		self.set_isNormalList(false);
            		self.setRankAndMode();
            		
            		self._createWaterFallStructure();
            		loading.show();
            		//模式改变,页码会变,不能直接_createPagination
                	self._renderData();
            	});
            },
            /**
             * 用于设置和获取self.isNormalList的值
             */
            set_isNormalList: function(b) {
                var self = this;
                
                if(typeof b == 'boolean'){
                    self.store.set(listTypeLocalName, b)
                    self.isNormalList = b;
                }
                return self.isNormalList;
            },
            /**
             * 获取url参数的值
             */
            getArguments: function(name) {
                var reg = new RegExp("(^|\\?|&|#)"+ name +"=([^&]*)", "g"), 
                    cs;
                
                window.location.href.replace(reg, function($1,$2,$3){cs = !$3 ? '' : $3; });
                return decodeURIComponent(cs);
            },
            /**
             * 判断图片是否超高
             * 最大高度为 imageMaxHeight
             * 宽度固定为 defaultWidth
             */
            isOverHeight: function(obj) {
                var self = this;
                if(imageMaxHeight/defaultWidth < obj.height/obj.width){//确定超高
                    return true;
                }
                return false;
            },
            /**
             * 请求list所有信息
             */
            _requestAllData: function(callback, idx) {
                var self = this,
                    hottag = self.getArguments("hottag"),
                    pageAllNum = D.attr(D.get("#page5"), "data-page"),
                    topid = self.getArguments("topid"),
                    hottag = self.getArguments("hottag"),
                    dataArguments;
				
				//第一次请求现实loading,其他情况,在清理信息之后loading,体验更好
				if(isFirstTimeGetData){
					loading.show();
				}
                idx = (idx && (typeof idx == 'number' || typeof idx == 'string'))? idx : 1;
                topid = (topid !== 'undefined')? topid : '';
                dataArguments = {
                    //每页的信息个数
                    'pageSize'  : self.isNormalList? normalListPerPage : waterfallPerPage, 
                    'hottag'    : hottag,
                    'key'       : encodeURIComponent(self.key),
                    'newArticle': self.isNewArticle,
                    'count'     : !self.isNewArticle,
                    'topid'     : topid,
                    'page'      : idx,
                    '_t'        : S.now()
                };
                if(topid!='undefined') {
                    dataArguments.topid = topid;
                }
                
                S.ajax({
                    url: self.config.getListUrl,
                    dataType: 'json',
                    data: dataArguments,
                    success: function(data) {
                    	//检测和处理异常数据,返回数据,是正常的true还是异常false
                    	var isOk = self._checkSolveRequestDataAbnormal(data);
                    	if(!isOk)return;
                    	
                        self.changePageNum = data.totalPage;//翻页配置设置为返回的总页数
                        self.message = data;//给_statusSwitch备用
                        callback(idx);
                    }
                });
            },
            /**
             * 对请求数据的状态分析(status的值),再启动渲染
             */
            _statusSwitch: function(idx, ready) {
                var self = this,
                    // newtype = D.prop(D.get("#new-type"), "checked"),
                    // hottype = D.prop(D.get("#hot-type"), "checked"),
                    //hottag = self.getArguments("hottag"),
                    newSelect,
                    rs = self.message;
                        
                //返回顶部,从第一条开始看
                scroll(0,0);
                    //防止相应时间过长出现翻页
                D.css("#page5", 'display', 'none');
                if (rs.status === 200) {
                    loading.hide();
                    //创建list
                    self.leftMessage = rs;//把所有信息都放到全局的剩余信息里(里面会越来越少)
                    //首次加载数据
                    self._rendering();
                    // 加载完内容后, 通知下分页器更新加载状态
                    ready(idx);
                }else if(rs.status === 1) {//最后一页
                    var pgNextBtn = D.get('a.pg-next');
                    //remove小菊花
                    D.html(self.content, '');
                    //创建list
                    //self._createList(rs);
                    self.leftMessage = rs;//把所有信息都放到全局的剩余信息里(里面会越来越少)
                    //首次加载数据
                    self._rendering();
                    
                    //显示分页、移除翻页按钮功能
                    D.css('#page5', 'display' , 'block');
                    D.addClass(pgNextBtn, 'pg-disabled');
                    E.on(pgNextBtn, 'click', function(e){
                       e.halt();
                    });
                } else {//请求的数据异常
                	self._checkSolveRequestDataAbnormal(rs);
                }
                
                /*老代码,不知道用处是什么,先留着
                var pgSkip = pgFirst = D.get("a.pg-first"), 
                    pgLast = D.get("a.pg-last");
                
                D.remove([pgFirst, pgLast]);
                cacheIdx = idx;
                */
            },
            /**
             * 处理请求有误信息
             * 有异常返回true,否则false
             */
            _checkSolveRequestDataAbnormal: function(rs) {
            	var self = this;
            	if(rs.status === 0) {//博文广场无数据
                	var urlKey = encodeURIComponent(self.getArguments("key"));
                    D.html(self.content, '<div class="noData">很抱歉,暂时还没有关于' + decodeURIComponent(urlKey).split(BREAK_MARK).join('、') + '的博文哦,去 <a href="/article_plaza.htm">广场</a> 逛逛吧!</div>')
                	return false;
                }else if(rs.status === 400) {//个人中心无数据
                    D.html(self.content, '<div class="noData">您暂时还没有任何博文动态哦,去 <a href="/article_plaza.htm">广场</a> 逛逛吧!</div>')
                	return false;
                }
                return true;
            },
            /**
             * 分页
             * //tag -> 标签 newtype -> 最新排序  hottype -> 热门排序  选择排序radio是获取最新状态
             */
            _createPagination: function() {
                var self = this,
                    pagination,
                    newSelect;
                
                //self.pagesize = self.isNormalList? 30 : 50;
                if(self.pagination){
                	self.pagination.reset();
                }
                
                self.pagination = new self.widgets.Pagination({
                    container: '#page5',
                    totalPage: self.changePageNum,
                    template: paginationHTML,
                    callback: function(idx, pg, ready) {
                        self.resetPageParam();
                         /**
                         *  从init过来的已经有数据,从按页码来的要重新请求数据
                         */
                        if(isFirstTimeGetData) {
                            isFirstTimeGetData = false;
                            self._statusSwitch(idx, ready);//请求信息
                            return;
                        }
                        
                        self._requestAllData(function(idx) {
                            self._statusSwitch(idx, ready);//请求信息
                        }, idx);
                        
                        ready(idx);
                    },
                    events: {
                        'J_jumpToBtn': {
                            click: function(e) {
                                var pg = this,
                                    val = pg.get('container').one('#J_jumpTo').val();
                                    // 对用户指定翻页数做限制(输入负数则跳到第一页,输入数大于总页数则到最后一页)
                                    if(val<1)
                                    {
                                        val=1;
                                    }else if(val > self.changePageNum)
                                    {
                                        val = self.changePageNum;
                                    }
                                pg.page(val);
                            }
                        }
                    }
                });
                pagination = self.pagination;
                newSelect = function() {
                    var select = self.widgets.MenuButton.Select.decorate('#decorateSelect', {
                        prefixCls:"c2c-",
                        menuAlign:{
                            offset:[0,-1]
                        },
                        menuCfg:{
                            width:82,
                            height:150,
                            elStyle:{
                                overflow:"auto",
                                overflowX:"hidden"
                            }
                        }
                    });
                    select.on("click", function(e) {
                        self.pagesize = select.get("value");
                        // 更新页码后, 重新获取数据;
                        pagination.page(pagination.get('currentPage'));
                    });
                    select.set("value", self.pagesize);
                    return select;
                };
                select = newSelect();
                
                pagination.on('beforePageChange', function(v) {
                    v.halt();
                    // 更新分页器前, 销毁其他组件
                    select && select.destroy();
                });
                pagination.on('afterPageChange', function(v) {
                    v.halt();
                    // 重新初始化 select
                    select = newSelect();
                });
                pagination.reset = function() {
                	var self = this;
                		container = self.get('container');
                	
                	var newPage = D.create('<div style="display:none" id="page5" class="pagination"></div>');
                	D.insertAfter(newPage, container[0]);
                	container.remove();
                };
            },
            /**
             * 瀑布流的列表模式
             */
            _createWaterFall: function(){
                var self = this;

                self.waterfall.waterfallCase = new self.widgets.Waterfall('#contents', {
                    brooks: D.query('.J_plaza_brook'),
                    //给每纵列的基本高度,是顶部不齐的,能尽量底部对齐
                    basicHeight: [0, 0, 0, 410],
                    //图片的class,用于在插入元素之前操作元素
                    imageClass: 'oneimg',
                    /**
                     * requestSuccess 参数为瀑布流代码块
                     * end 结束瀑布流
                     * context 瀑布流组件的上下文
                     */
                    load: function(requestSuccess, end, context) {
                        self._packageMessage(requestSuccess, end, context);
                    },
                    //单个item插入之前
                    //此时图片已经算好高度了
                    insertBefore: function(imgData) {
                    	var _self = this;//该item
                    		
                    	if(!imgData.isHasImg)return;//没有图片的item
                    	if(self.isOverHeight(imgData)) {
                    		var img = D.get('.big-img', _self);
                            D.css(img, 'height', imageMaxHeight);
                            D.css(D.get('.mask', D.parent(img, '.waterfall-item')), 'display', 'block');
                        }
                    },
                    //单个item插入之后
                    insertAfter: function(imgData) {
                    	var _self = this,//该元素
                    		para,
                    		height;
                    	if(imgData.isHasImg) return;//item存在大图片时不进行限高操作
                    	para = D.get('.para', _self),
                    	height = D.height(para);
                    	if(height < minHeight){
                    		D.css(para, 'height', minHeight+'px');
                    	}
                    },
                    //单个item显示完整(渐隐)
                    itemComplete: false
                });
            },
            /**
             * 限制几项数据的最大值
             */
            _limiteMaxNum: function(currentItem) {
            	var self = this;
            	currentItem.collect = (currentItem.collect <= maxNum)? currentItem.collect : maxNumStr;
                currentItem.read = (currentItem.read <= maxNum)? currentItem.read : maxNumStr;
                currentItem.commentcount = (currentItem.commentcount <= maxNum)? currentItem.commentcount : maxNumStr;
                return currentItem;
            },
            /**
             * 组装用于渲染瀑布流的信息块集合
             *
             */
            _packageMessage: function(requestSuccess, end, context) {
                var self = this,
                    leftItems = self.leftMessage.items,
                    len = self.waterRenderNum,
                    items = [],
                    currentItem,
                    isLastTime = false;

                for(var i=0; i<len; i++){
                    if(leftItems.length == 0){//若当次信息已经不足预定的每次渲染数量,则渲染完就跳出
                        isLastTime = true;
                        break;   
                    }
                    //给收集、阅读、评论增加最大限制
                    currentItem = self._limiteMaxNum(self.leftMessage.items[0]);
                    
                    var item = S.Template(waterfallTemplate).render(currentItem),
                        newItemDom = D.create(item),
                        o = S.clone(self.config);
                        
                    o.wrapclass = D.get('.J_operate', newItemDom);
                    
                    var uo = new self.widgets.UO(o);
                    uo.on('Plaza', function(e) {
                        var box = e.currentTarget.wraps;
                        if(!e.collect)return;
                        var str = D.html(D.get('.collect', box)),
                        box_a = D.get('.collect', box);
                        D.attr(box_a, 'title', '取消收集');
                        if(str.indexOf('+') == -1){
                            var newNum = parseInt(D.html(D.get('.collect', box)));
                            newNum = (newNum == maxNum)? '99999+' : newNum+1;
                            D.html(box_a, newNum);
                            D.addClass(box_a, 'hover');
                            D.removeClass(box_a, 'collectbtn');
                            D.addClass(box_a, 'cancelcollectbtn');
                        }
                    });
                    uo.on('Guang_Center', function(e) {
                        var box = e.currentTarget.wraps,
                            str = D.html(D.get('.collect', box)),
                            box_a = D.get('.collect', box);
                            D.attr(box_a, 'title', '收集');
                        if(str.indexOf('+') == -1){
                            var newNum = parseInt(D.html(D.get('.collect', box)));
                            newNum = newNum-1;
                            D.html(box_a, newNum);
                            D.removeClass(box_a, 'hover');
                            D.addClass(box_a, 'collectbtn');
                            D.removeClass(box_a, 'cancelcollectbtn');
                        }
                    });
                    items.push(newItemDom);
                    leftItems.shift();
                }
                requestSuccess.call(context, items);
                if(isLastTime){
                    end.apply(context);
                    self._currentPageRenderOver();
                }
            },
            /**
             * 创建瀑布流的基本结构
             * _createWaterFall之前执行
             */
            _createWaterFallStructure: function() {
                var self = this,
                    selfCon = D.get('#page-content-5'),
                    rightCon = D.get('.right-small-col-v2'),
                    leftColNum = 3,
                    marginValue = 14,//间隙
                    colWidth = 237,//没列宽
                    leftConStr = '',
                    waterFallStructureAlready = false,
                    rightConStr = '';
                //如果已经存在瀑布流结构,就不再创建该结构
                waterFallStructureAlready = D.get('.leftCon', self.content)? true : false;
                
                //瀑布流结构重新渲染
                if(!waterFallStructureAlready) {
	                self.isCreateWaterFallStructure = true;//表示瀑布流模式渲染已经开始
	                for(var i =0; i<leftColNum; i++){
	                    leftConStr += (i == leftColNum - 1)? '<div class="J_plaza_brook" style="float:left;width:'+ colWidth +'px;"></div>'
	                                                       : '<div class="J_plaza_brook" style="float:left;margin-right:'+ marginValue +'px;width:'+ colWidth +'px;"></div>';
	                }
	                leftConStr = '<div class="leftCon" style="width:741px;overflow:hidden">'+ leftConStr +'</div>';
	                rightConStr = '<div class="J_plaza_brook" style="float:left;margin-top:'+ marginTop +'px;width:'+ colWidth +'px;"></div>';
	                D.html(selfCon, leftConStr);//左边的内容需要清空
	                D.append(D.create(rightConStr), rightCon);//右边的内容,是加在其原有内容下方
                	return;
                }
                //清空原有瀑布流结构内容
                var brooks = D.query('.J_plaza_brook');
                for(var i=0; i<len; i++) {
	                D.html(brooks[i], '');
            	}
            },
            /**
             * 创建常规list模式的基本结构
             */
            _createNormalListStructure: function(){
                var self = this,
                    hooks = D.query('.J_plaza_brook');
                
                //表示常规list模式已经开始
                self.isCreateNormalListStructure = true;
                //清除瀑布流结构
                if(hooks.length > 0){
                    D.remove(hooks);
                    var leftCon = D.get('.dr-blog-list-plaza .leftCon');
                    if(leftCon){
                        D.remove(leftCon);
                    }
                }
                self._eventBlogList();
            },
            /**
             * 清除普通list模式的事件
             */
            _stopNormalList: function() {
            	var self = this;
            	
            	self._eventBlogList = self._eventBlogList || {};
            	if(!self._eventBlogList.renderFn)return;
            	E.remove(window, "resize scroll", self._eventBlogList.renderFn);
            },
            /**
             * 普通的列表模式
             */
            _createList: function() {
                var self = this;
                //没有剩余信息渲染了
                if(self.leftMessage.items.length === 0) {
                    self._currentPageRenderOver();
                    return;
                }
                //请求回数据填充首屏数据:当list包裹层 < 可视区 + scrollTop,则加载list数据
                if(D.innerHeight(self.content) < D.viewportHeight() + D.scrollTop()) {
                    var currentItem = self._limiteMaxNum(self.leftMessage.items[0]),
                    	domTemplate = S.Template(listTemplate).render(currentItem),
                    	domList = D.create(domTemplate);
                    
                    self.leftMessage.items.shift();
                    D.append(domList, self.content);
                    //self._sourcePop(domList);

                    var ic = new self.widgets.IC(domList, '.oneimg', [139,139]),
                   		o = S.clone(self.config);
                   		
                    o.wrapclass = D.get('.J_operate', domList);
                    
                    var uo = new self.widgets.UO(o);
                    uo.on('Plaza', function(e) {
                        var box = e.currentTarget.wraps;
                        if(!e.collect)return;
                        var str = D.html(D.get('.collect', box)),
                        box_a = D.get('.collect', box);
                        D.attr(box_a, 'title', '取消收集');
                        if(str.indexOf('+') == -1){
                            var newNum = parseInt(D.html(D.get('.collect', box)));
                            newNum = (newNum == maxNum)? '99999+' : newNum+1;
                            D.html(box_a, newNum);
                            D.addClass(box_a, 'hover');
                            D.removeClass(box_a, 'collectbtn');
                            D.addClass(box_a, 'cancelcollectbtn');
                        }
                    });
                    uo.on('Guang_Center', function(e) {
                        var box = e.currentTarget.wraps,
                            str = D.html(D.get('.collect', box)),
                            box_a = D.get('.collect', box);
                            D.attr(box_a, 'title', '收集');
                        if(str.indexOf('+') == -1){
                            var newNum = parseInt(D.html(D.get('.collect', box)));
                            newNum = newNum-1;
                            D.html(box_a, newNum);
                            D.removeClass(box_a, 'hover');
                            D.addClass(box_a, 'collectbtn');
                            D.removeClass(box_a, 'cancelcollectbtn');
                        }
                    });
                    self._rendering();
                }
            },
            /**
             * 普通列表模式的事件监听
             */
            _eventBlogList: function() {
                var self = this,
                    timer;
                
                self._eventBlogList.renderFn = function(){
                     if(timer){
                        clearTimeout(timer);
                    }
                    timer = setTimeout(function(){
                        clearTimeout(timer);
                        self._rendering();
                    }); 
                };
                E.on(window, "resize scroll", self._eventBlogList.renderFn);
            },
            /**
             * 来源
             */
            /*
            _sourcePop: function(dom) {
                var self = this,
                    timer,
                    source = D.get('.source', dom);
                
                if(!source)return;
                E.on(source, 'mouseenter', function(e) {
                    timer && clearTimeout(timer);
                    var pp = D.get('.divpop', this);
                    
                    D.removeClass(pp, 'hidden');
                    E.on(pp, 'mouseenter', function() {
                        timer && clearTimeout(timer);
                        E.remove(pp, 'mouseenter');
                    });
                    E.on(pp, 'mouseleave', function() {
                        E.remove(pp, 'mouseleave');
                        D.addClass(pp, 'hidden')
                    });
                    
                });
                E.on(source, 'mouseleave', function(e) {
                    var _this = this;
                    timer = setTimeout(function() {
                        var pp = D.get('.divpop', _this);
                        D.addClass(pp, 'hidden');
                    }, 1000);
                });
            },*/
            /**
             * 浮动回到顶部
             */
            _backTop: function() {
                var self = this,
                    winheight = D.viewportHeight(), 
                    isShow = false,
                    normalListMargin = -294,
                    waterfallMargin = -531,
                    //marginRight = self.isNormalList? normalListMargin : waterfallMargin,
                    newClassName = self.isNormalList? 'back-to-top-normalList' : 'back-to-top-waterfall',
                    //backbtn = D.create('<a href="javascript:;" target="_self" class="back-to-top '+ newClassName +'" style="display:none;margin-right:'+ marginRight +'px;"></a>'),
                    backbtn = D.create('<a href="javascript:;" target="_self" class="back-to-top '+ newClassName +'" style="display:none;"></a>'),
                    btn = D.get(backbtn),
                    timer;
                    
                self.toTopBtn = btn;
                self.toTopBtn.resetMarginRight = function(){
                    //var marginRight = self.isNormalList? normalListMargin : waterfallMargin;
                    var newClassName = self.isNormalList? 'back-to-top-normalList' : 'back-to-top-waterfall',
                        oldClassName = self.isNormalList? 'back-to-top-waterfall' : 'back-to-top-normalList';
                    //alert(marginRight);
                    D.removeClass(self.toTopBtn, oldClassName);
                    D.addClass(self.toTopBtn, newClassName);
                    //D.css(self.toTopBtn, 'marginRight', marginRight);
                };
                D.append(backbtn, D.get(".left-large-col-v2"));
                E.on(btn, "click", function() {
                    isShow=false;
                    scroll(0,0);
                    D.hide(backbtn);
                    D.css(btn,{
                        opacity: '0'
                    });
                });
                
                E.on(window, "scroll", function() {
                    //winheight = D.viewportHeight();
                    winheight = 700;
                    if(D.scrollTop() > winheight) {
                        var st = D.scrollTop();
                        D.show(backbtn);
                        !isShow && S.Anim(btn, {
                            opacity: 1
                        }, 0.3).run();
                        isShow = true;
                        if(S.UA.ie == 6) {
                            timer && clearTimeout(timer);
                            timer = setTimeout(function() {
                                S.Anim(backbtn, {'top':winheight-398+st+"px"}, 0.3, 'easeOut').run();
                            }, 400);
                        }
                    } else {
                        isShow = false;
                        D.hide(backbtn);
                        D.css(btn, {
                            opacity: '0'
                        });
                    }
                });
            }
        };
})();
 

你可能感兴趣的:(逻辑)