
if(!window.HW){
    window.HW = {};
}
if(!window.HW.ui){
    window.HW.ui = {};
}
window.HW.ui.twitterUtil = {
        
        initCommonFn:function(target){
            target.createTw = function(item){
	            var Util = window.HW.ui.twitterUtil;
	            item.noPic = this.noPic;
	            item.content = Util.handleFaces(item.content);
	            item.dateStr = Util.Date.toString(item.createTime);
	            item._mediaHtml = window.HW.ui.showMedia.formatMediaList(item.media);
	            if(item.userV == '1'){
	                item._vIconHtml = '<span class="i-auth i-auth-v"></span>';
	            }
	            item._userLink = Util.getUserLink(item);
	            if(item.shareCount == 0){
	                item.shareCount = '';
	            }
	            if(item.replyCount === 0){
	                item.replyCount = '';
	            }
	            if(item.root && item.root.userId){
	                var root = item.root;
	                if(root.userId === -1){
	                    //TODO  the twitter has been deleted.
	                    item._shareHtml = HW_CodeTips['weibo.tweet.selectTweet.TWEETDELECTED'];
	                }else{
	                    root.content = Util.handleFaces(root.content);
	                    if(root.userV == '1'){
	                        root._vIconHtml = '<span class="i-auth i-auth-v"></span>';
	                    }
	                    root._userLink = Util.getUserLink(root);
	                    
	                    if(root.shareCount == 0){
	                        root.shareCount = '';
	                    }
	                    if(root.replyCount === 0){
	                        root.replyCount = '';
	                    }
	                    root._mediaHtml = window.HW.ui.showMedia.formatMediaList(root.media);
	                    root._shareActionHtml = Util.applyTpl(this.shareActionTpl,root);
	                    item._shareHtml = Util.applyTpl(this.shareTwitterTpl,root);
	                    
	                    delete root._mediaHtml;
	                    delete root._shareActionHtml;
	                }
	            }else{
	                item.noCite = 'no_cite';
	            }
	            if(this.loginUid == item.userId){
	                item._deleteHtml = '<a href="#" class="delete" action="delete" >'
	                         + HW_LanguageUtil.plugins.TwitterList.Delete
	                         + '</a>';
	            }
	            return Util.applyTpl(this.twitterTpl,item);
	        };
            target.showMask = function(cfg){
	            new TY.ui.pop({
	                headTxt: HW_LanguageUtil.plugins.TwitterList.Warn,
	                body: cfg.body,
	                type:cfg.type || "confirm",
	                isMod:(cfg.isMod === false)? false:true,
	                yesHandler:function(){
	                    if(cfg.confirmFn){
	                        cfg.confirmFn.call(cfg.scope);
	                    }
	                },
                    yesTxt:HW_LanguageUtil.plugins['follow_cancel']['yes'],
                    cancelTxt:HW_LanguageUtil.plugins['follow_cancel']['cancel']
	            });
	        };
        },
        initCommonTpl:function(target){
            var from = HW_LanguageUtil.plugins.TwitterList.From,
                forward1 = HW_LanguageUtil.plugins.TwitterList.Forward1,
                comment1 = HW_LanguageUtil.plugins.TwitterList.Comment1,
                comment3 = HW_LanguageUtil.plugins.TwitterList.Comment3;
            var browser = this.browser();
            var _wrapT = '',
                _wrapB = '',
                css3 = 'radius_css';
            if(browser.isIE && browser.ver < 9){
                _wrapT = '<div class="radius_top"><div class="r1"></div><div class="r2"></div><div class="r3"></div><div class="r4"></div></div>';
                _wrapB = '<div class="radius_bottom"><div class="r4"></div><div class="r3"></div><div class="r2"></div><div class="r1"></div></div>';
                css3 = '';
            }
            
            target.twitterTpl = [
                '<li class="twitter_list {noPic}" _key="{_key}" _id="{id}">',
                    '<div class="head_pic fl">',
                        '<a href="{_userLink}" target="_blank" title="{userNickName}"><img alt="{userNickName}" src="http://photo.nublogs.com/logo/m/{userId}"/></a>',
                    '</div>',
                    '<div class="fn_doc">',
                        '<div class="information">',
                            '<h3 class="fl"><a href="{_userLink}" target="_blank">{userNickName}</a>{_vIconHtml}:</h3>',
                            '<div class="source fr"><a href="/{userId}/{id}" target="_blank">{dateStr}</a><a href="{sourceLink}" class="sourceName">'+from+' {sourceName}</a></div>',
                        '</div>',
                        '<div class="tw_text">',
                            '<p>{content}</p>',
                        '</div>',
                        '{_mediaHtml}',
                        '<div class="cite {noCite}">',
                            '<div class="share_triangle_box"><div class="triangle"></div></div>',
                             _wrapT,
                                '<div class="item_content '+css3+'">',
                                    '{_shareHtml}',
                                '</div>',
                             _wrapB,
                        '</div>',
                         '<div class="actions_box clearfix">',
                             '<div class="actions fr">',
                                '{_deleteHtml}',
                                '<a href="#" hidefocus class="forward" action="forward">'+forward1+' {shareCount}</a>',
                                '<a href="#" hidefocus class="comment" action="comment">'+comment1+' {replyCount}</a>',
                            '</div>',
                        '</div>',
                    '</div>',
                '</li>'
            ].join('');
            
            target.shareTwitterTpl = [
                    '<p><a href="{_userLink}" title="{userNickName}" target="_blank">@{userNickName}</a>{_vIconHtml}: {content}</p>',
                    '{_mediaHtml}',
                    '{_shareActionHtml}'
            ].join('');

            target.shareActionTpl = [
                '<div class="actions_box">',
                    '<div class="actions fr">',
                        '<a target="_blank" href="/{userId}/{id}#action=forward" class="forward">'+forward1+' {shareCount}</a>',
                        '<a target="_blank" href="/{userId}/{id}" class="comment">'+comment1+' {replyCount}</a>',
                    '</div>',
                '</div>'
            ].join('');
            
            target.twCommentTpl = [
                '<li class="comment_box_item clearfix {borderT} {noBorder}" _key="{_key}" _id="{id}">',
                    '<div class="comment_text">',
                        '<a href="{_userLink}" class="pic"><img src="http://photo.nublogs.com/logo/{userId}" /></a>',
                        '<div class="comment_content">',
                            '<a href="{_userLink}" class="uname">{userName}{_vIconHtml}</a>{content}<span class="c_date">{dateStr}</span>',
                            '<div class="actions_box clearfix">',
	                            '<a href="#" class="c_action fr" action="commentTo">'+comment3+'</a>',
	                            '{_deleteHtml}',
                            '</div>',
                        '</div>',
                     '</div>',
                 '</li>'
            ].join('');
            
            var actionBox = [
                '<div class="comment_triangle_box"><div class="triangle"></div></div>',
                _wrapT,
                '<div class="item_content '+css3+'">',
                    '<div class="twitter_box" id="{id}"></div>',
                '</div>',
                _wrapB
            ].join('');
            target.commentBox = 
                '<div class="fn_comment_box comment_box">' + actionBox + '</div>';
            
            target.forwardBox = 
                '<div class="fn_forward_box comment_box">' + actionBox + '</div>';
        },
     	API_URL:{
            selectTweet:'/api/tw?method=weibo.tweet.selectTweet',
            selectTweetByGroup:'/api/tw?method=weibo.tweet.selectTweetByGroup',
            selectAtMe:'/api/tw?method=weibo.tweet.selectAtMeTweets',
            selectTweetByUser: '/api/tw?method=weibo.tweet.selectTweetByUser',
            getNewTweetCount:'/api/tw?method=weibo.tweet.selectNewTweetCount',
            
            selectHotShareTweet:'/api/tw?method=weibo.tweet.selectHotShareTweet',
            selectHotReplyTweet:'/api/tw?method=weibo.tweet.selectHotReplyTweet',
            
            selectTweetById:'/api/tw?method=weibo.tweet.selectTweetById',
            selectTweetByTopic: '/api/tw?method=weibo.tweet.selectTweetsByTopic',
            delTw:'/api/tw?method=weibo.tweet.delete',
            delComment:'/api/tw?method=weibo.retweet.delete',
            getTwComments:'/api/tw?method=weibo.retweet.selectByTweet',
            
            selectMyRcvReply:'/api/tw?method=weibo.retweet.selectMyRcvReply',
            selectMyReply:'/api/tw?method=weibo.retweet.selectMyReply'
        },
        
        /**
         * get the user name link.
         * @param {Object} data
         * {
         *   userDomain:'abc',
         *   userNickName:'shawn',
         *   id:12345
         * }
         */
        getUserLink:function(data){
            var u = '';
            if(data.userDomain){
                u = '/'+data.userDomain;
            }else if(data.userNickName){
                u = '/n/'+data.userNickName;
            }else if(data.userName){
                u = '/n/'+data.userName;
            }else if(data.id){
                u = '/u/'+data.id;
            }
            return u
        },
        /**
         * @param type {Integer} 1:forward;2:comment. 
         * @param bAdd {Boolean} true:increase;false:decrease.
         */
        changeLinksNumbers : function(container, type, bAdd){
            var clsName = '',clsText='';
            function updateNum(clsName,clsText){
                var aShare = container.find(clsName).text().match(/(\d+)/);
                var nShare = 0;
                if(aShare){
                    nShare = +aShare[1];
                }
                if(bAdd){
                    nShare++;
                }else{
                    nShare--;
                }
                container.find(clsName).text(clsText+(nShare<1?'':' '+nShare));
            }
            
            switch(type){
                case 1 : 
                    clsName = '.forward';
                    clsText = HW_LanguageUtil.plugins.TwitterList.Forward1;
                    updateNum(clsName,clsText);
                    break;
                case 2 : 
                    clsName = '.comment';
                    clsText = HW_LanguageUtil.plugins.TwitterList.Comment1;
                    updateNum(clsName,clsText);
                    break;
            }
        },
        browser:function(){
            var b = {};
            var ua = navigator.userAgent;
            var rs = /MSIE ([^;]+)/.test(ua);
            if(rs){
                b.isIE = true;
                b.ver = parseInt(RegExp['$1']);
            }
            return b;
        },
        handleFaces:function(str){
            var copyStr = str,
                key=null,keyReg=null,val=null,tmp=null;
            var reg = arguments.callee.reg,
                faceTpl = arguments.callee.faceTpl;
            if(!reg){
                reg = arguments.callee.reg =/\[.+?\]/g;
                faceTpl = arguments.callee.faceTpl = '<img class="emotion" src="/images/emotion/e/{val}.png" />';
            }
            var rs = reg.exec(str);
            while(rs){
                tmp = rs[0];
                keyReg = key = tmp.substring(1,tmp.length-1);
                key = key.replace(/&nbsp;/,' ');
                val = HW_Emotion_en[key] || HW_Emotion_es[key];
                if(val){
                    copyStr = copyStr.replace(new RegExp('\\['+keyReg+'\\]'),this.applyTpl(faceTpl,{"val":val,"key":key}));
                }
                rs = reg.exec(str);
            }
            return copyStr;
            
        },
        applyTpl: function(tpl,data){
            if(typeof data == 'undefined'){
                data = '';
            }
            var reg = arguments.callee.reg,
            replaceFn = arguments.callee.replaceFn;
    
            if(!reg){
                reg = arguments.callee.reg = new RegExp("\\{(.+?)\\}","g");
                replaceFn = arguments.callee.replaceFn = function(data,words,tpl){
                    var value = data;
                    for(var i=0;i<words.length;i++){
                        if(typeof value[words[i]] != 'undefined'){
                            value = value[words[i]];
                        }else{
                            value = '';
                            break;
                        }
                    }
                    var keyReg = "\\{" + words.join("\\.")+"\\}";
                    return tpl.replace(new RegExp(keyReg),value);
                }
            }
            var rs2 = tpl.match(reg);
            for(var i=0;i<rs2.length;i++){
                 var key = rs2[i].substring(1,rs2[i].length-1);
                 tpl = replaceFn(data,key.split("."),tpl);     
            }
            return tpl || '';
       },
        Date : {
                /*
                 * format date to string
                 * @method window.HW.ui.twitterList.Util.Date.toString(time)
                 * @param time {num || string}
                 * @return time {string}
                 */
                toString : function(time){
                    time = +time;
                    if(isNaN(time)){
                        return "";
                    }
                    var d = new Date(time),
                        dToday = new Date(),
                        nToday = new Date(dToday.getFullYear(), dToday.getMonth(), dToday.getDate()).getTime(),
                        noff = nToday - time,
                        nOneDay = 24*60*60*1000,
                        sResult,
                        sTime = (d.getHours()<10?'0' + d.getHours() : d.getHours()) + ':'+
                            (d.getMinutes()<10?'0'+ d.getMinutes() : d.getMinutes());
                        
                    if(noff <= 0){
                        sResult = HW_LanguageUtil.plugins.TwitterList.Today;
                    }else if(noff < nOneDay){
                        sResult = HW_LanguageUtil.plugins.TwitterList.Yesterday;
                    }else{
                        return dateFormat(new Date(time),"dd-mmmm-yyyy HH:MM:ss");
                    }
                    sResult += '&nbsp;' + sTime;
                    return sResult;
                }
            },
        
        getScrollTop:function(){
            var scrollTop=0;
            if(document.documentElement&&document.documentElement.scrollTop){
                scrollTop=document.documentElement.scrollTop;
            }else if(document.body){
                scrollTop=document.body.scrollTop;
            }
            return scrollTop;
        },
        
        getViewHeight: function(){
            var viewHeight=0;
            if(document.body.clientHeight&&document.documentElement.clientHeight){
                viewHeight = (document.body.clientHeight<document.documentElement.clientHeight)?
                            document.body.clientHeight:document.documentElement.clientHeight;       
            }else{
                viewHeight = (document.body.clientHeight>document.documentElement.clientHeight)?
                        document.body.clientHeight:document.documentElement.clientHeight;   
            }
            return viewHeight;
        },
        
        getDocHeight: function(){
                return Math.max(document.body.scrollHeight,document.documentElement.scrollHeight);
        },
        
        /**
         * set focus to textarea
         * @param {HTMLElement} elem textarea 
         * @param {Boolean} bBegin:set the cursor at the begining of textarea
         */
        focusTextarea : function(elem, bBegin) {
            var start =0,end = 0;
            if (bBegin) {
                start =end = 0;
            } else {
                start =end = elem.value.length;
            }
			if (document.all) {//IE
				var range = elem.createTextRange();
				range.moveStart("character", end);
				range.collapse(true);
				range.select();
			} else {
				elem.setSelectionRange(start, end);
				elem.focus();
			}
		},
        /**
		 * send ajax request.
		 * 
		 * @param cfg
		 *            {Object} usage example: { url:'', success:fn, scope: the
		 *            context of success fn and error fn. error:fn, params:{} ||
		 *            '', //params data }
		 */
        ajax: function(cfg){
            var params = "&";
            if(typeof cfg.params == 'string'){
                params += cfg.params;
            }else{
                var obj = cfg.params;
                for(var p in obj){
                    if(typeof obj[p] != 'undefined'){
                        params += "params." + p + "=" + encodeURIComponent(obj[p]);
                        params += "&";
                    }   
                }
            }
            params += '_r=' + Math.random();
            jQuery.ajax({
                type:cfg.type || 'POST',
                dataType:cfg.dataType || 'json',
                url: cfg.url+params,
                success:function(rnt){
                    var scope = cfg.scope || window;
                    if(cfg.success){
                        cfg.success.call(scope,rnt);
                    }
                },
                error:function(rnt){
                    var scope = cfg.scope || window;
                    if(cfg.error){
                        cfg.error.call(scope,rnt); 
                    }
                }
            });
        }
};


if(!window.HW.io){
    window.HW.io = {};
}
if(!window.HW.io.Record){
    /**
    *@params rnt {Object} 
     format:{
                    "success":1,
                    "code":"1",
                    "message":"query success",
                    "data":{
                        total:150,
                        items:[
                            {twitter data},
                            {twitter data}
                        ]
                    }
                }

    */
    window.HW.io.Record = function(rnt,cfg){
        if(cfg){
            jQuery.extend(this,cfg);
        }

        this.init(rnt);
    }
}
(function(packager){
    jQuery.extend(packager.prototype,{
        
        itemProperty:'items',
        
        init:function(rnt){
	        this.rntData = rnt;
	        this.total = 0;
	        this.items = [];
            if(this.rntData && this.rntData.success == 1 && this.rntData.data){
                this.items = this.rntData.data[this.itemProperty];
                if(this.items instanceof Array === false){
                    this.items = [];
                }
                this.total = this.rntData.data.total || 0;
            }
        },
        /** @params i {integer} . zero based.*/
        getByIndex: function(i){
            return this.items[i];
        },
        getById: function(id){
            for(var i=0,len = this.getSize();i<len;i++){
                if(this.items[i].id == id){
                    return this.items[i];
                }
            }
            return null;
        },
        getTotal:function(){
            return this.total;
        },
        getSize:function(){
            return this.items.length;
        },
        /**
            @params rnt {Object} 
            format:{
                    "success":1
                    "code":"1", 
                    "message":"forward success",
                    "data":{ a data item}
                }
        */
        addData: function(rnt){
            if(rnt && rnt.success == 1 && rnt.data){
                this.items.push(rnt.data);
                this.total++;
            }
        }
    })
})(window.HW.io.Record);


if(!window.HW.io.RecordManager){
    window.HW.io.RecordManager = function(rnt){
        this.records = [];
        this.newRecord = new window.HW.io.Record();
        if(rnt){
            this.pushRecord(rnt);
        }
    };
}
(function(packager){
    jQuery.extend(packager.prototype,{
        
        /**
         * @param rnt {Object} 
         *      record data
         * @param clear {boolean} 
         *      true to clear all old data.Default to be false;
         */
        pushRecord:function(rnt,clear){
            if(clear === true){
                this.reset();
            }
            this.records.push(new window.HW.io.Record(rnt));
        },

        /** 
         * @params key {String} 
         *   format: {cursor_index}. Both cursor and index start from 0.
         *   example:0_1, 1_15, 2_1, etc.
         * @params id {String} optional
         *    id of the  data  
         */
        getRecordData:function(key,id){
            var tmp = null;
            if(key && /^\d+_\d+$/.test(key)){
                tmp = key.split("_");
                return this.records[parseInt(tmp[0])].getByIndex(parseInt(tmp[1]));
            }else if(id){
                tmp = this.newRecord.getById(id);
                if(tmp != null){
                    return tmp;
                }
            }
            return null;
        },
        
        /**
         * @description 
         *   increase additional record data
         */
        addRecord:function(rnt){
            this.newRecord.addData(rnt);
        },
        
        /**
         * get the length of records of this manager.
         * the return value will be part of the key which used to index the record.
         * @see getRecordData() 
         */
        getCursor:function(){
            return this.records.length-1;
        },
        getRecord:function(i){
            var len = i || this.records.length-1;
            return this.records[len];
        },
        reset:function(){
            this.records = [];
            this.newRecords = new window.HW.io.Record();
        },
        getTotal:function(){
            return this.records[0].getTotal();
        },
        getRecSize:function(){
            return this.records[this.records.length-1].getSize();
        }
    });
})(window.HW.io.RecordManager);
