/**
 * @fileoverview 该文件是 xweibo web端UI。
 *
 * @requires jquery 1.4.2
 * @version 0.1
 */
(function($){

    var 
		UNDEFINED,
		
		NULL = null,
		
		TRUE = true,
		
		FALSE = false,
		
		slice = Array.prototype.slice,
		
		toString = Object.prototype.toString,
		
		toInt = parseInt,
		
		xwb = window.XWB,
		
		eventMgr = xwb.eventMgr,
		
		buildModulePath = xwb.url,
		
		htmlEscape = xwb.escape,
		
		alertMsg = xwb.alert,
		
		confirmBox = xwb.confirm,
		
		apiCall = xwb.apiCall,
		
		isArray = $.isArray,
		
		FileUploader = xwb.FileUploader,
		
		isFn = $.isFunction;
    
    var    //转发
    event_type_forward = 1,    //收藏 
    event_type_fav = 2,    //评论
    event_type_comment = 3,    //缩略图
    event_type_thumbpic = 4,    //收起图片
    event_type_hidepic = 5,    //图片向左转
    event_type_trunleft = 6,    //图片向右转
    event_type_trunright = 7,    //发表评论
    event_type_sendComment = 8,    //转发里的图片
    event_type_pic_forward = 12,    //隐藏图片
    button_hidepic = 9,    //图片左转
    button_trunleft = 10,    //图片右转
    button_trunright = 11,    //看视频
    event_type_video = 13,    //收起视频
    event_type_video_hide = 14,
    event_type_forward_video_hide = 15,    //删除微博
    event_type_delete = 16,    //播放音乐
    event_type_play_music = 17,    //删除图片
    event_type_photo_del = 18,    //发布微博
    event_type_publish = 19,    //取消收藏
    event_type_fav_del = 20;
    
    
    var music_type_189 = 1, music_type_sina = 2;
	
	//按键禁用样式
	var disable_class = 'disable';
    
    var emotionPath = 'http://timg.sjs.sinajs.cn/miniblog2style/images/common/face/basic/';
    
    /**
     * 注册特定的事件对应处理的函数
     * @param {Object} type
     * @param {Object} fn
     */
    function regEvent(type, fn){
        eventMgr.add(type, fn);
    }
    
    function getImageSrc(tid, type){
        var data = XWEIBO && XWEIBO.data;
        var ele = data[tid];
        
        var propertyName;
        
        if (type == 1) {
            propertyName = 'tp';
        }
        else 
            if (type == 2) {
                propertyName = 'mp';
            }
            else 
                if (type == 3) {
                    propertyName = 'op';
                }
        
        return propertyName && data && ele && (ele[propertyName] || (ele.rt && ele.rt[propertyName]));
    }
    
    /**
     * 向上找标签元素
     * @param {Object} tagName
     * @param {Object} $parent
     */
    function findParentElement(tagName, $ele){
        $parent = $ele.parent();
        
        if (!$parent.length) {
            return NULL;
        }
        
        if ($parent.get(0).tagName == tagName) {
            return $parent;
        }
        else {
            return findParentElement(tagName, $parent);
        }
    }

    var sinaurls = (function(){
        /**
         * URL属性缓存
         */
        var urlInfos = {};
        
        function getSinaUrlInfo(ids, callback){
            var total = ids.length;
            var dataFromCache = {};
            var caches = 0;
            
            $.each(ids, function(i, url_id){
                if (urlInfos[url_id]) {
                    dataFromCache[url_id] = urlInfos[url_id];
                    caches++;
                }
            });
            
            if (caches < total) {
                apiCall('sinaurl', {
                    data: {
                        id: ids.join(',')
                    },
                    success: function(ret){
                        if (ret.code != '-1' && ret.data) {
                            var data = ret.data;
                            $.extend(urlInfos, data);
                            var mergeData = $.extend(dataFromCache, data);
                            callback && callback(mergeData);
                        }
                    }
                });
            }
            else {
                callback(dataFromCache);
            }
        }
        
        return {
            get: function(url_id){
                return urlInfos[url_id];
            },
            
            query: getSinaUrlInfo
        }
    })();
    
    //每条消息对应的组件映射
    var weiboMapping = {};
    
    /*
     * 消息对象映射管理
     */
    function mapWeibo(id, type, ele){
        if (!weiboMapping[id]) {
            weiboMapping[id] = {};
        }
        
        if (ele === UNDEFINED) {
            return weiboMapping[id][type];
        }
        
        weiboMapping[id][type] = ele;
    }
    
    var uniqueId = 0;
    
    var map_weibo = uniqueId++, map_pic_thumb = uniqueId++, map_video_thumb = uniqueId++;
    
    function createMiddlePic(tid){
        return $('<div class="show-img hidden"><p><a href="#" rel=' + button_hidepic + '>收起</a><a href="' + getImageSrc(tid, 3) + '" target="_blank">查看原图</a><a href="#" rel=' + button_trunleft + '>向左转</a><a href="#" rel=' + button_trunright + '>向右转</a></p><div><img src="' + getImageSrc(tid, 2) + '" rel=' + button_hidepic + ' alt="" /></div></div>');
    }
    
    function createVideoThumb(thumb){
		//<div rel=' + event_type_video + ' class="video-view all-bg"></div>
        return $('<div class="feed-img"><img  alt="" src="' + thumb + '" width="120px"><div rel=' + event_type_video + ' class="video-view all-bg"></div></div>');
    }
    
    
    /**
     * 根据ID返回对应的LI元素
     * @param {Object} tid
     */
    function getWeibo(tid){
        return $('#i' + tid);
    }
    
    /**
     * 获取元素对应的微博的ID
     * @param {Object} $element jQuery对象
     */
    function getWeiboID($element, $li){
		var element = $element.get(0);
		
        if (!element) 
            return FALSE;
        
        if (element.tid === UNDEFINED) {
            $li || ($li = findParentElement('LI', $element));
            
            var ele_id = $li && $li.attr('id');
            
            var tid;
            
            if (ele_id) {
                tid = ele_id.substr(1);
                mapWeibo(tid, map_weibo, $li);
            }
            
            element.tid = tid ? tid : NULL;
        }
        
        return element.tid;
    }

    function showItem($obj){
        $obj.removeClass('hidden');
    }
    
    function hideItem($obj){
        if (!$obj.hasClass('hidden')) {
            $obj.addClass('hidden');
        }
    }
    
    var picId = 0;
	
	var errorMsgs = {
        '0': '发布失败。',
		'5': '超过字数了！',
		'1': '图片正在上传，请稍候。',
		'2': '正在发布,请稍候。。',
		'3': '请先输入内容。',
		'4': '请写上你要说的话题。',
		'20014': '你已经发过同样的内容了，请不要重复。',
		'20015': '已经提交，请耐心等待管理员审核，谢谢！',
        '20011': '评论字数超过限制',
		
		//图片相关
		'20020':'上传图片为空',
		'20021':'上传图片大小超过限制',
		'20022':'上传图片类型不符合要求',
		'20023':'上传图片失败',
		'20024':'非法的上传图片'
	};
	
	function getError(errno) {
		return errno in errorMsgs ? errorMsgs[errno]: '未知错误';
	}
    
    function getNextPicId(){
        return 'pic_' + picId++;
    }
    
    var show_box_classname = 'showbox', show_box_classname_forward = 'showbox-f';
    
    function getShowBox($li, is_forward){
        if (is_forward) {
            return $('div.' + show_box_classname_forward, $li);
        }
        else {
            var $box = $('div.' + show_box_classname, $li);
            
            if (!$box.length) {
            
                //$box = $('<div class="box-style hidden"></div>');
                $box = $(['<div class="box-style hidden ' + show_box_classname + '">', '<div class="box-t skin-bg"><span class="skin-bg"></span></div>', '<div class="box-b skin-bg"><span class="skin-bg"></span></div>', '<span class="box-arrow skin-bg"></span>', '</div>'].join(''));
                
                $('p.feed-main', $li).after($box);
            }
            return $box;
        }
    }
	
	xwb.showInit = function($content, tid, isForward) {
		//短链接处理
		var url = findSinaurl();
		if (url) {
			var map = url.map;
			var urls = url.urls;

			sinaurls.query(urls, function(ret){
				var isVideo = 0;
				for (var p in ret) {
					if (ret[p].type == 'video') {
						addVideoPreview(p, ret[p], $content, map[p][0][1]);
						isVideo = 1;
					}
				}
				
				//绑定看视频的事件
				isVideo && $('div.video-view', $content).click(function(){
					var video_id = $(this).attr('video_id');
					
					showVideo($content, ret[video_id], isForward);
				})
			});
		}
		
		
		//图片点击事件
		var $img = $('div.feed-img>img', $content);
		
		if ($img.length) {
			var pic_id;
			
			$img.click(function(){
				if (!pic_id) {
					var $box = getShowBox($content, isForward);
					pictures.init(tid, $box, $img, isForward);
					pic_id = $img.attr('id');
				}
				else {
					pictures.show(pic_id)
				}
			})
		}
	}
    
    var pictures = {
        cache: {},
        
        init: function(tid, $box, $thumb, is_forward){
            var cache = this.cache;
            
            var img_panel_id = 'middle_pic_' + getNextPicId();
            
            //var $img = createMiddlePic(tid);
            if (is_forward) {
                var $img = $('<div class="show-img cutline hidden"><p><a href="#" class="piup-icon icon-bg" rel=' + button_hidepic + '>收起</a><a href="' + getImageSrc(tid, 3) + '" target="_blank" class="src-icon icon-bg">查看原图</a><a href="#" class="trunleft-icon icon-bg" rel=' + button_trunleft + '>向左转</a><a href="#" class="trunright-icon icon-bg" rel=' + button_trunright + '>向右转</a></p><div id="' + img_panel_id + '"></div></div>');
                $box.append($img);
            }
            else {
                var $img = $('<div class="show-img  box-content hidden"><p><a href="#" rel=' + button_hidepic + ' class="piup-icon icon-bg">收起</a><a href="' + getImageSrc(tid, 3) + '" target="_blank" class="src-icon icon-bg">查看原图</a><a href="#" rel=' + button_trunleft + ' class="trunleft-icon icon-bg">向左转</a><a href="#" rel=' + button_trunright + ' class="trunright-icon icon-bg">向右转</a></p><div id="' + img_panel_id + '"></div></div>');
                $box.find('div.box-t').after($img);
            }
            
            //<img src="' + getImageSrc(tid, 2)+ '" rel=' + button_hidepic +' alt="" />
            
            
            var pic_id = getNextPicId();
            
            $thumb.attr('id', pic_id);
            
            this.bindEvent(is_forward ? $img : $box, pic_id);
            
			var $loading = $('<div class="loading-img"></div>').insertAfter($thumb);
			
            cache[pic_id] = {
                box: $box,
                preview: $thumb.parent().parent(),
                forward: is_forward,
                img: $img
            }
            
            //this.show(pic_id);
            
            var img = new Image();
            img.rel = button_hidepic;
            
            img.onload = function(){                
				$(this).appendTo('#' + img_panel_id).addClass('narrow-move');
				
                if (this.width > 440) {
                    this.width = 440;
                }
                
                pictures.show(pic_id);
                
				$loading.remove();
				
                this.onload = NULL;
            }
            
            img.src = getImageSrc(tid, 2);
            /*
             $('img', $img).bind('load', function(){
             if (this.width > 440) {
             this.width = 440;
             }
             pictures.show(pic_id);
             });
             */
        },
        
        bindEvent: function($box, pic_id){
        
            $box.click(function(e){
                var $target = $(e.target);
                
                var cache = pictures.cache[pic_id];
                
                var rel = toInt($target.attr('rel'));
                
                switch (TRUE) {
                    case button_hidepic == rel:
                    case $target.attr('tagName') == 'CANVAS':
                    
                        if($target.height() > $(window).height()) {
                            var $li = findParentElement('LI', $target);
                            if($li && $li[0]) {
                                $li.moveToView(1);
                            } 
                        }
                    
                        pictures.hide(pic_id);
                        break;
                        
                    case button_trunleft == rel:
                        $('img', cache.img).imgRotate('left');
                        break;
                        
                    case button_trunright == rel:
                        $('img', cache.img).imgRotate('right');
                        break;
                }
				rel && e.preventDefault();
            })
        },
        
        show: function(pic_id){
            var cache = this.cache[pic_id];
            
            if (cache.forward) {
                showItem($('div.show-img', cache.box));
                //hideItem($('div.feed-img', cache.box));
            }
            else {
                showItem(cache.box.add('div.show-img', cache.box));
            }
            hideItem(cache.preview);
        },
        
        hide: function(pic_id){
            var cache = this.cache[pic_id];
            
            if (cache.forward) {
                hideItem($('div.show-img', cache.box));
            }
            else {
                hideItem(cache.box);
            }
            showItem(cache.preview);
        }
    }
    
    /**
     *  查看中图
     * @param {Object} $source 源缩略图
     */
    function viewMiddlePic($source, type){
        var $li = findParentElement('LI', $source);
        
        var tid = getWeiboID($source, $li);
        
        if (!tid) {
            return FALSE;
        }
        
        var pic_id = $source.attr('id');
        
        if (!pic_id) {
            var is_forward = type == event_type_pic_forward ? TRUE : FALSE;
            
            var $box = getShowBox($li, is_forward);
            
            pictures.init(tid, $box, $source, is_forward);
        }
        else {
            pictures.show(pic_id);
        }
    }
	
	/**
	 * 增加文字计数,如：转发(1),调用后：转发(2)
	 * @param {Object} text
	 * @param {Object} $forwards
	 */
	function increaseText(text, $forwards) {
		var str = $forwards.text();
        var hasNum = 0;
        var newstr = str.replace(/(\d+)/gi, function(num){
            hasNum++;
            return parseInt(num) + 1;
        });
		
        if (hasNum) {
            $forwards.text(newstr);
        }
        else {
            $forwards.text(text + '(1)');
        }
	}
	
	
	xwb.showForward = showForward;
	xwb.increaseText = increaseText;
	
	/**
	 * 显示转发的面板
	 * @param {Object} tid
	 * @param {Object} data
	 * @param {Object} uid
	 * @param {Object} callback
	 */
	function showForward(tid, data, uid, callback) {
		var text, inputText, comments = [];
		
		if (uid != data.u.id) 
            comments.push({
                uid: tid,
                nick: data.u.sn
            });
        
        var rt = data.rt;
        
        if (rt) {
            text = rt.tx;
            
            inputText = '//@' + data.u.sn + ':' + data.tx;
            
            if (rt.u.id != uid) 
                comments.push({
                    uid: rt.id,
                    nick: rt.u.sn
                });
        }
        else {
            text = data.tx;
            inputText = '';
        }
        
        //'<label><input type="checkbox" />同时作为新浪乐库的评论发布</label>',
        var html = ['<div class="pop-window forward-window fixed-window">', '<div class="pop-t"></div>', '<div class="pop-content">', '<h4 class="pop-title x-bg"><a class="close-btn icon-bg" href="#" rel="close" title="关闭"></a>转发到我的微博</h4>', '<div class="forward-box">', '<p>' + htmlEscape(text) + '</p>', '<div class="forward-tool"><span></span><a class="choose-emotion all-bg" href="#" rel="face"></a></div>', '<textarea>' + inputText + '</textarea>', (function(){
            var str = '';
            for (var i = 0, l = comments.length; i < l; i++) 
                str += '<label><input type="checkbox" value="' + comments[i].uid + '"/>同时作为' + comments[i].nick + '的评论发布</label>';
            return str;
        })(), '<div class="btn-area">', '<a class="general-btn highlight" href="#" rel="forward"><span rel="forward">转发</span></a>', '<a class="general-btn" href="#" rel="close"><span rel="close">取消</span></a>', '</div>', '</div>', '</div>', '<div class="pop-b"></div>', '<div class="pop-tl all-bg"></div>', '<div class="pop-tr all-bg"></div>', '<div class="pop-bl all-bg"></div>', '<div class="pop-br all-bg"></div>', '</div>'].join('');
        
        var $html = $(html);
        
        $html.appendTo('body');
        
        var win = $html.toXwin();
        
        var $input = $('textarea', $html);
        
        function close(){
            win.remove();
            $html.remove();
        }
        
        $input.focus();
		$input.focusEnd(0);
        
        var rids = [];
        
        var $tips = $('div.forward-tool span', $html);
        
        $input.keyup(function(){
            var len = $input.checkText();
            if (len >= 0) {
                $tips.text('还可以输入' + len + '字').removeClass('out140');
            }
            else {
                $tips.text('已超出' + Math.abs(len) + '字').addClass('out140');
            }
        })
        
        $html.click(function($e){
            var target = $e.target;
            var rel = $(target).attr('rel');
            
            if (rel) {
                switch (rel) {
                    case 'close':
                        close();
                        break;
                        
                    case 'forward':
						var errMsg;
						
						if ($input.checkText() < 0) {
							errMsg = '字数超过了！';
						}
					
						if (errMsg) {
							alertMsg({
								msg: errMsg,
								timeout: 2,
								callback: function(){$input.focus()}
							});
						}
						else {
							$('input[type="checkbox"]', $html).each(function(i, ele){
								if (ele.checked) {
									rids.push(ele.value);
								}
							});
							
							var text = $input.val();
							
							if (!text) {
								text = '转发微博';
							}
							
							apiCall('repost', {
								data: {
									id: tid,
									text: text,
									rtids: rids.join(',')
								},
								success: function(ret){
									close();
									
									if (ret.errno == '0') {
										alertMsg({
											msg: '转发成功。',
											timeout: 2
										});
										
										callback && callback(ret.rst);
									}
									else {
										alertMsg({
											msg: getError(ret.errno),
											timeout: 3
										});
									}
								}
							})
						}
                        break;
                        
                    case 'face':
                        wbSubjoin.showEmotion(target, $input, 0, 30);
                        return FALSE;
                        break;
                }
                
                $e.preventDefault();
            }
        });
        
        win.show();
        $input.keyup();
	}
    
    /**
     * 转发微博
     */
    function weiboForward($target){
        var $li = findParentElement('LI', $target);
        
        var tid = getWeiboID($target, $li);
        
		var data = XWEIBO.data[tid];
        
        var uid = XWEIBO && XWEIBO.uid;

		showForward(tid, data, uid, function(rst){                                    
            publisher.insert(rst.data.id, rst.data, rst.html);
            
            //转发数加1
            var $forwards = $('p>a[rel=1]', $li);
            increaseText('转发', $forwards);
		});
        
    }
    
	xwb.weiboForward = weiboForward;
	xwb.addFavorite = addFavorite;
	xwb.delFavorite = delFavorite;
	
	function addFavorite(tid, callback) {
		apiCall('createFavorite', {
            data: {
                id: tid
            },
            success: function(ret){
                if (ret.errno == '0') {
                    alertMsg({
                        title: "提示",
                        msg: "收藏成功",
                        callback: callback,
                        timeout: 2
                    });
                }
                else {
                    alertMsg({
                        title: "提示",
                        msg: "收藏失败",
                        timeout: 2
                    });
                }
            }
        });
	}
	
    /**
     * 添加收藏
     * @param {Object} $target
     */
    function addWeiboFavorite($target){
        var tid = getWeiboID($target);
        
        addFavorite(tid, function() {
            $target.replaceWith('<span>已收藏</span>');
        });
        
    }
	
	function delFavorite(tid, callback) {
		confirmBox({
			title: '提示：',
            msg: '确定要删除该收藏？'
        }, function(){
            apiCall('deleteFavorite', {
                data: {
                    id: tid
                },
                success: function(ret){
                    if (ret.errno == '0') {
                        callback && callback(ret);
                    }
                    else {
                        alertMsg({
                            msg: '发生错误: ' + htmlEscape(ret.err),
                            timeout: 2
                        })
                    }
                }
            })
        })
	}
    
    /**
     * 取消收藏
     * @param {Object} $taget
     */
    function delWeiboFavorite($taget){
        var $li = findParentElement('LI', $taget);
        var tid = getWeiboID($taget, $li);
        
        delFavorite(tid, function(){
			$li.slideUp('normal', function(){
                $li.remove();
            });            
		});
    }
    
    function deleteWeiboConfirm($target){
		var $li = findParentElement('LI', $target);
        var tid = getWeiboID($target, $li);
		
        confirmBox({
            title: '提示',
            msg: '确定删除这条微博吗？'
        }, function(){
            weiboDelete(tid, function(){
				$li.slideUp('normal', function(){
                    $li.remove();
                    
                    var $text = $('#user-weibo-count');
                    var num = $text.text().match(/\d+/g);
                    
                    $text.text(num-1);
                });
			});
        })
    }
	
	xwb.del = function(tid){
		confirmBox({
			msg: '确定要删除这条微博？'
		}, function(){
			weiboDelete(tid, function(){
				window.location = buildModulePath('index','profile');
			});
		});
	}
    
    /**
     * 删除微博
     */
    function weiboDelete(tid, callback){
        
        apiCall('destroy', {
            data: {
                id: tid
            },
            success: function(ret){
                if (ret.errno == '0') {
                    callback && callback();
                }
                else {
                    alertMsg({
                        msg: '删除失败: ' + htmlEscape(ret.err),
						type: 'error',
                        timeout: 2
                    });
                }
            }
        });
    }
    
	function showListVideo($source, type) {
		var video = sinaurls.get($source.attr('video_id'));
		if (video && video.type == 'video') {
			
			    var isForward = toInt($source.attr('is_forward'));
            	var $li = findParentElement('LI', $source);
				
				showVideo($li, video, isForward);
		}
	}
    
    /**
     * 看视频
     */
    function showVideo($li, video, isForward){
        var $box = getShowBox($li, isForward);
        
        if($box.find('div.show-video')[0]) {return ;}
        
        var flash = xwb.flash({
            src: video.flash,
            width: 440,
            height: 360,
            w3c: 1,
            id: 'sinaVideo_'+(+new Date()),
            quality: 'high',
            allowScriptAccess: 'always',
            wmode: 'transparent',
            allowFullscreen: 'true',
            flashvars: 'playMovie=true'
        });
        
        var html = '<div class="cutline show-video' + (isForward ? '' : ' box-content') + '"><p><a class="piup-icon icon-bg" href="#" rel="' + event_type_video_hide + '">收起</a><span>|</span><a href="' + video.url + '" target="_blank" title="' + video.title + '">' + video.title + '</a></p><div>' + flash + '</div></div>'
        
        var $video = $(html);
        
        $video.click(function(e){
            var rel = $(e.target).attr('rel');
            
            switch (TRUE) {
                case rel == event_type_video_hide:
                    showItem(getPreviewBox($li, isForward));
                    hideItem(isForward ? $video : $box);
                    $video.remove();
					e.preventDefault();
                    break;
            }
        })
        
        isForward ? $box.append($video) : $box.find('div.box-t').after($video);
        
        hideItem(getPreviewBox($li, isForward));
        hideItem($('div.show-img', $box));
        showItem(isForward ? $video : $box);
		
    }
/**
* 微博辅助阅读
*/
var wbReader = (function(){
    
    function eventBind(){
        $(document).keydown(function(e) {
            var 
                reader = wbReader,
                _target = e.target;
            
            if(!_target || (_target.tagName != 'INPUT' && _target.tagName != 'TEXTAREA')) {
                if(!reader._timeout) {
                    reader._timeout = setTimeout(function() {
                        if(e.keyCode == 74 || e.keyCode == 38) {
                            reader.move('up');
                        }else if(e.keyCode == 75 || e.keyCode == 40) {
                            reader.move('down');
                        }
                        
                        reader._timeout = NULL;
                        delete reader._timeout;
                        
                    }, 200);
                }
                
                if(e.keyCode == 40 || e.keyCode == 38 && !reader.firstIsInVeiw()) {
                    e.preventDefault();
                }
            }
        });
    
        $(window).scroll(function() {
            wbReader.checkUnread();
            
            var firstIsInVeiw = wbReader.firstIsInVeiw();
            
            if(!wbAutoInsert.isStop && !firstIsInVeiw) {
                wbAutoInsert.stop();
            }else if(wbAutoInsert.isStop && firstIsInVeiw && XWEIBO.autoshow==='1') {
                wbAutoInsert.insert();
            }
        });
    }
    
    return {
        ctn: NULL,
        first: NULL,
        last: NULL,
        lastTop: 0,
        curList: NULL,
        
        init: function(ctn) {
            this.ctn = ctn;
            this.lastTop = $(document).scrollTop() || 0;
            this.first = this.getFirstInVeiw();
            this.last = this.getLastInVeiw();
            
            eventBind.call(this);
        },
        
        move: function(dir) {
            var _$tarEl, _$first, _osTop = 80;
            
            this.curList = this.getFirstInVeiw();
            
            if(this.curList) {
                this.curList = $(this.curList).next().get(0);
            }else {
                _$first = $(this.ctn).children().first();
                
                if(_$first.offset().top - _osTop <= $(document).scrollTop()) {
                    this.curList = _$first.get(0);
                }
            }

            if(dir === 'up') {
               _$tarEl = $(this.curList).prev();
            }else if(dir === 'down') {
                if(this.curList) {
                    _$tarEl = $(this.curList).next();
                }else {
                    _$tarEl = _$first;
                }
            }

            
            if(_$tarEl[0]) {
                _$tarEl.moveToView(_osTop);
                this.curList = _$tarEl[0];
            }

            _$tarEl = _osTop = _$first = NULL;

        },

        firstIsInVeiw: function() {
            var _top = $(this.ctn).children().first().offset().top;
            return _top >= $(document).scrollTop();
        },

        getChildsInVeiw: function() {
            var _top = $(document).scrollTop();
            var els = [];
            
            $.each($(this.ctn).children(), function(i, child) {
                var 
                    _offsetTop = $(child).offset().top,
                    _height = $(window).height();
                
                if(_offsetTop > _top) {
                    if(_height+_top-_offsetTop <= $(child).height()) {
                        _offsetTop = _height = NULL;              
                        return false;
                    }else {
                        els.push(child);
                    }
                }
                
            });
            
            _top = NULL;
            
            return els;
        },
        
        getFirstInVeiw: function() {
            var _top = $(document).scrollTop();
            var first = NULL;
            
            $.each($(this.ctn).children(), function(i, child) {
                var _offsetTop = $(child).offset().top;
                if(_offsetTop > _top) {
                    
                    if(i == 0) {
                        first = NULL;       
                    }else {
                        first = $(child).prev()[0];
                    }
                    
                    _offsetTop = NULL;
                    return false;
                }
            });
            
            _top = NULL;
            
            return first;
        },
        
        getLastInVeiw: function() {
            var 
                _top = $(document).scrollTop(),
                _height = $(window).height();
            var last = NULL;
            
            $.each($(this.ctn).children(), function(i, child) {
                var _offsetTop = $(child).offset().top;
                if(_height+_top-_offsetTop < $(child).height()) {
                    last = child;                
                    _offsetTop = _height = NULL;
                    return false;
                }            
            });
            
            _top = NULL;
            
            return last;
        },
        
        checkUnread: function() {
            var _top = $(document).scrollTop();        
            var _dir = this.lastTop > _top ? 'up' : 'down';
            this.lastTop = _top;
            
            var 
                $el,
                first = this.getFirstInVeiw(),
                last = this.getLastInVeiw(),
                rFirst = this.first,
                rLast = this.last;
/*
            if(first != rFirst) {
                if(_dir === 'down') {
                    $el = rFirst ? $(rFirst).next() : $(this.ctn).children().first();
                }else {
                    $el = $(rFirst);
                }

                if(first != last && $el) {
                    $el.removeClass('unread');
                }
                
                this.first = first;
            }
            
            if(last != rLast) {
                if(_dir === 'up') {
                    $el = rLast ? $(rLast).prev() : $(this.ctn).children().last();
                }else {
                    $el = $(rLast);
                }
                
                if(first != last && $el) {
                    $el.removeClass('unread');
                }
                
                this.last = last;
            }            
*/

            if(first != rFirst) {
                if(_dir === 'down') {
                    $el = $(rFirst);
                }

                if(first != last && $el) {
                    $el.removeClass('unread');
                }
                
                this.first = first;
            }
            if(last != rLast) {
                this.last = last;
            }      
        }
        
    }
    
})();
xwb.reader = wbReader;

/**
* 微博提示浮层
*/
var wbTipsLayer = function(opt) {
    this.el = NULL;
    this.type = opt.type;
    this.confirmCallback = opt.confirmCallback || NULL;
};

wbTipsLayer.prototype = {
    init: function() {
        switch(this.type) {
            case 'tips':
                this.create({
                    content: '<p>有新微博时，点击此处，微博信息就会在下方自动显示。</p><p>你也可以设置在网页右下角使用始终可见的气泡，提示新信息。</p>',
                    pEl: $('#header>.inner-header').first()
                });
                
                break;
            case 'weibo':
                // this.create({
                    // content: '<p>有新微博时，点击此处，微博信息就会在下方自动显示。</p><p>你也可以设置有新微博时直接显示，不需要进行点击。</p>',
                    // pEl: $('#container .post-box').first()
                // });

                // this.el.addClass('new-feed-tips');
                break;
        }
        
        return this;
    },
    create: function(opt) {
        var $el = $('<div></div>')
            .addClass('newtips-tips')
            .html('<div class="newtips-tips-c"></div><a class="iknow" href="javascript:;">我知道了</a><a class="nowset" href="'+buildModulePath('setting', '', 'tab=displaySet')+'">立即设置</a><div class="newtips-tips-bg"></div>');
        
        this.el = $el;
        
        opt.content && this.setContent(opt.content);
        var pEl = opt.pEl || document.body; 
        
        $el.find('a.iknow').bind('click', {tl: this}, function(e) {
            var tl = e.data.tl;
            
            if(tl.confirmCallback) {
                tl.confirmCallback();
            }
            
            tl.close();
            
            return false;
        });
        
        $(pEl).append($el);
        
        $el = NULL;
        
        return this;
    },
    
    show: function() {
        if(!this.el) {
            this.create();
        }
        
        this.el.show();
    },
    
    close: function() {
        this.el && this.el.hide();
    },
    
    setContent: function(content) {
        if(this.el) {
            this.el.find('.newtips-tips-c').html(content);
        }
    }
};
xwb.tipsLayer = wbTipsLayer;

   /**
     * 微博评论
     */
    var wbComment = (function(){
        //微博ID，评论区域容器，评论列表容器，更多评论容器
        var _wbid, _$cEl, _$ul, _$more;
        
        function eventBind(){
            _$ul.bind('click', wbComment, function(e){
                var $target = $(e.target), rel = $target.attr('rel'), wbc = e.data;
                if (rel) {
                    var $li = findParentElement('LI', $(e.target)), cid = $li.attr('id').slice(2);
                    
                    switch (rel) {
                        case 'del':
                            confirmBox({
                                title: '提示',
                                msg: '确定要删除这条评论吗'
                            }, function(){
                                wbc.delComment(cid);
                            });
                            break;
                        case 'reply':
                            wbc.replyComment(cid);
                            break;
                    }
                }
            });
        }
        
        return {
            /**
             * 定位至指定微博的评论列表
             * @param {Object|String} $srcEl 微博ID或者jq查询出来的评论按钮
             */
            get: function($srcEl){
                if (typeof $srcEl === 'string') {
                    _wbid = $srcEl;
                }
                else {
                    _wbid = getWeiboID($srcEl);
                }
                
                var $wb = $('#i' + _wbid + ' div.feed-content');
                
                if ($wb[0]) {
                    _$cEl = $wb.find('div.feed-comment');
                    if (!_$cEl[0]) {
                        var isNew = true;                        
                        _$cEl = this.createTextArea(true, _wbid).appendTo($wb);
                    }
                    
                    _$ul = _$cEl.find('ul');
                    _$more = _$cEl.find('div.more-comment');
                    
                    isNew && eventBind();
                }
                
                return this;
            },

            /**
             * 显示或隐藏某条微博的评论
             */
            toggle: function() {
                if (_$cEl[0].offsetWidth) {
                    this.hide();
                }
                else {
                    this.loadData();
                }
                return this;
            },
            
            show: function() {
                if (_$cEl && _$cEl[0]) {
                    _$cEl.show();
                }
                _$cEl.find('textarea.comment-textarea').focusEnd();
                return this;
            },
            
            hide: function() {
                if (_$cEl && _$cEl[0]) {
                    _$cEl.hide();
                }
                return this;
            },
            
            loading: function(isStop) {
                if(isStop) {
                    $('#xweibo-loading').remove();
                }else {
                    var $loading = $('<div></div>').attr('id', 'xweibo-loading').addClass('loading');
                    $('#i' + _wbid + ' div.feed-info').after($loading);
                }
            },
            
            /**
             * 加载某条微博的评论
             */
            isLoading: FALSE,
            loadData: function() {
                
                if(this.isLoading) {return;}
                
                var count = 10;
                this.loading();
                this.isLoading = TRUE;
                
                apiCall('getComments', {
                    data: 'id=' + _wbid + '&count=' + count,
                    success: function(msg){
                        if (msg.errno == 0) {
                            log('加载评论列表', msg);
                            wbComment.createList(msg.rst, msg.rst.total - count);
                            wbComment.show();
                        }
                        
                        wbComment.loading('stop');
                        wbComment.isLoading = FALSE;
                    }
                });
            },
            
            createTextArea: function(hasList, wbid) {
                var listStr = hasList ? 
                    '<ul><li></li></ul><div class="more-comment">后面还有<span></span>条评论，<a href="'+XWB.url('show', '', 'id='+wbid)+'">点击查看</a></div>': '';

                var $el = $('<div></div>')
                    .addClass('feed-comment box-style')
                    .html([
                        '<div class="box-t skin-bg"><span class="skin-bg"></span></div>', 
                        '<div class="box-content">', 
                            '<div class="post-comment">', 
                                '<div class="post-comment-main">', 
                                    '<a href="javascript:;" class="choose-emotion all-bg"></a>', 
                                    '<a class="general-btn" href="javascript:;" rel="8"><span rel="8">评论</span></a>', 
                                    '<div class="comment-keyin"><div><textarea class="comment-textarea"></textarea></div></div>', 
                                '</div>', 
                                '<div>',
                                    '<span class="keyin-tips">还可以输入<span>140</span>个字</span>',
                                    '<label><input type="checkbox" />同时发一条微博</label>',                                    
                                '</div>',
                            '</div>', 
                            listStr, 
                        '</div>', 
                        '<div class="box-b skin-bg"><span class="skin-bg"></span></div>', 
                        '<span class="box-arrow skin-bg"></span>'
                    ].join(''))
                    .hide();
                
                $el.find('a.choose-emotion').click(function(e) {
                    wbSubjoin.showEmotion(this, $el.find('textarea'), -20, 30);
                    return FALSE;                    
                });
                
                $el.find('textarea.comment-textarea').bind('keyup', function() {
                    var 
                        $area = $(this);
                        
                    while ($area.checkText() < 0) {
                        var val = $area.val();
                        $area.val(val.substring(0, val.length - 1));
                    }
                    $area.css('height', $area[0].scrollHeight);
                    
                    $el.find('.keyin-tips span').text($area.checkText());
                });
                
                return $el;
            },
            
            /**
             * 创建列表
             */
            createList: function(data, more) {
                if (_$ul && _$ul[0]) {
                    _$ul.empty();
                    
                    var frag = document.createDocumentFragment();
                    $.each(data, function(i, item){
                        if (isNaN(i)) {
                            return;
                        }
                        var $li = wbComment.createComment(item);
                        
                        frag.appendChild($li[0]);
                    });
                    
                    _$ul[0].appendChild(frag);
                }
                
                if (more && more > 0) {
                    _$more.show().find('span').html(more);
                }
                else {
                    _$more.hide();
                }
                
                return this;
            },
            
            createComment: function(item) {
                var 
                    delStr = '', 
                    sinaV = item.sina_v ? 'class="v-icon icon-bg"' : '',
                    wbUid = XWEIBO.data && XWEIBO.data[_wbid] && XWEIBO.data[_wbid].u.id,
                    url = XWB.url('ta', '', 'id='+item.uid);
                
                if (wbUid == XWEIBO.uid || item.uid == XWEIBO.uid) {
                    delStr = '<a href="javascript:;" rel="del">删除</a>|'
                }
                
                var picSize = 30;
                
                var $li = $('<li></li>').attr({
                    'id': 'c_' + item['id'],
                    'rel': item['nick']
                }).html([
                    '<div class="user-pic">', 
                        '<a href="' + url + '"><img src="' + item['profileImg'] + '" title="' + item['nick'] + '" alt="' + item['nick'] + '的头像" width="'+picSize+'" height="'+picSize+'" /></a>', 
                    '</div>',
                    '<div class="comment-content">', 
                        '<p><a href="' + url + '"'+sinaV+'>' + item['nick'] + '</a>：' + item['text'] + '<span>(' + item['create_at'] + ')</span></p>', 
                        '<div>' + delStr + '<a href="javascript:;" rel="reply">回复</a></div>', 
                    '</div>'
                ].join(''));
                
                return $li;
            },
            
            /**
             * 删除某条微博的评论
             */
            delComment: function(cid) {
                var $li = $('#c_' + cid), $wb = findParentElement('LI', $li), $commentNum = $wb.find('div.feed-info a[rel="3"]');
                
                apiCall('comment_destroy', {
                    data: 'id=' + cid,
                    success: function(msg){
                        if (msg.errno == 0) {
                            $li.remove();
                            if($commentNum[0]) {
                                var num = $commentNum.text().match(/\d+/);
                                if (num == 1) {
                                    $commentNum.text('评论');
                                }
                                else {
                                    $commentNum.text('评论(' + (--num) + ')');
                                }
                            }
                        }
                    }
                });
                
            },
            
            /**
             * 回复某条微博的评论
             */
            replyComment: function(cid) {
                var $li = $('#c_' + cid), $wb = findParentElement('LI', $li), $textarea = $wb.find('textarea.comment-textarea'), re = /^回复@.*?:/;
                
                $textarea.val('回复@' + $li.attr('rel') + ':' + $textarea.val().replace(re, ''));
                $textarea.attr('rel', cid);
                
                $textarea.focusEnd();
                
                $wb.find('.keyin-tips span').text($textarea.checkText());
            },
            
            /**
             * 发送评论
             * params.$li: 评论节点容器
             * params.needHTML: 是否需要插入微博节点， （同时发一条微博）
             * params.needCommentCount: 是否需要统计评论数
             * params.wbid: 微博ID
             * params.callback: 评论回调
             * params.$cb: 是否同时发一条微博checkbox
             * params.$area: 微博输入框
             * params.callback: 评论回调
             */
            sendComment: function(params) {
                
                var 
                    _data, _action, 
                    $li = params.$li,
                    $area = params.$area || $li.find('textarea.comment-textarea'), 
                    $commentNum = params.needCommentCount && $li.find('a[rel="3"]'), 
                    _cid = $area.attr('rel'), 
                    $cb = params.$cb || $li.find('div.post-comment input'),
                    wbid = params.wbid,
                    needHTML = params.needHTML,
                    needCommentCount = params.needCommentCount,
                    callback = params.callback,
                    photoType = params.type;
					
				if (!$.trim($area.val())) {
					$area.focus();
					return;
				}
                    
                if (_cid) {
                    _action = 'reply';
                    _data = {id: wbid, cid: _cid, text: $area.val()};
                }
                else {
                    _action = 'comment';
                    _data = {id: wbid, text: $area.val()};
                }
                
                if ($cb.attr('checked')) {
                    _data.forward = 1;
                }else {
                    _data.forward = 0;
                }
                
                _data.type = photoType || 1;
                
                log('发送评论----------', {
                    action: _action,
                    data: _data
                });
                
                //_data += '&needHTML=' + (needHTML ? 1 : 0);
                _data.needHTML = needHTML ? 1 : 0;
                
                apiCall(_action, {
                    data: _data,
                    success: function(msg){
                        log('发送评论返回----------', msg);

                        var data = msg.rst.comment;
                        var wbData = msg.rst.rel;
                        
                        if (msg.errno == 0 && data) {
                        
                            //如果有配置了回调函数，使用配置的函数
                            if(callback) {
                                callback(data);
                                return;
                            }
                            if(!_$ul) {
                                alertMsg({
                                    msg: '评论发送成功',
                                    timeout: 2
                                });
                            }else {
                                var $li = wbComment.createComment(data);                            
                                _$ul.prepend($li);
                            }  
                            
                            $area.val('').focusEnd();
                            
                            $area.tagUp('LI').find('.keyin-tips span').text(140);
                            
                            if(needCommentCount) {
                                var num = $commentNum.text().match(/\d+/);
                                if (num) {
                                    $commentNum.text('评论(' + (++num) + ')');
                                }
                                else {
                                    $commentNum.text('评论(1)');
                                }
                            }
                            //同时发一条微博
                            if (wbData && msg.rst.html) {
                                publisher.insert(wbData.data.id, wbData.data, msg.rst.html);
                            }
                            
                        }
                        else {                 
                            alertMsg({
                                msg: errorMsgs[msg.errno] || errorMsgs[0]
                            });
                        }
                    }
                });
            },
            
            init: function(returnHtml) {
                regEvent(event_type_comment, function($srcEl){
                    wbComment.get($srcEl).toggle();
                });
                regEvent(event_type_sendComment, function($srcEl){
                    wbComment.get($srcEl).sendComment({
                        wbid: _wbid,
                        $li: $('#i'+_wbid),
                        needHTML: returnHtml,
                        needCommentCount: TRUE
                    });
                });
            }
        };
        
    })();
    
    xwb.comment = wbComment;
    
    var wbSubjoin = (function(){
        var $ui = {
            // faceBtn
            // videoBtn
            // musicBtn
            // topicBtn
        };
        
        function eventBind(){
            $ui.faceBtn.bind('click', function(e){
                wbSubjoin.showEmotion(this, '#publish_text', 0, 30);
                return false;
            });
            
            $ui.videoBtn.bind('click', function(e){
                wbSubjoin.showVideo(this, -150, 30);
                return false;
            });
            
            $ui.musicBtn.bind('click', function(e){
                wbSubjoin.showMusic(this, -150, 30);
                return false;
            });
            
            $ui.topicBtn.bind('click', function(e){
                wbSubjoin.insertTopic();
            });
        }
        
        return {
            init: function(){
                //缓存DOM
                var $tem = $('#container div.add-area');
                $ui.textarea = $('#publish_text');
                $ui.faceBtn = $tem.find('a.face-icon');
                $ui.videoBtn = $tem.find('a.video-icon');
                $ui.musicBtn = $tem.find('a.music-icon');
                $ui.topicBtn = $tem.find('a.topic-icon');
                
                this.createEmotion();
                this.createLayer('video');
                this.createLayer('music');
                
                eventBind();
            },
            
            setUiCache: function(data){
                $.extend($ui, data);
            },
            
            insertTopic: function(){
                var start = 0, end = 0, input = $ui.textarea[0], text, defaultText = '请在这里输入自定义话题', hasCustomTopic = /#请在这里输入自定义话题#/.test(input.value);
                
                text = defaultText;
                input.focus();
                
                if (document.selection) {
                
                    var cr = document.selection.createRange();
                    //获取选中的文本
                    text = cr.text || defaultText;
                    
                    //内容有默认主题，且没选中文本
                    if (text == defaultText && hasCustomTopic) {
                        start = RegExp.leftContext.length + 1;
                        end = defaultText.length;
                    }
                    //内容没有默认主题，且没选中文本
                    else if(text == defaultText) {
                        cr.text = '#' + defaultText + '#';
                        
                        start = input.value.indexOf('#' + defaultText + '#') + 1;
                        end = defaultText.length;
                    }
                    //有选中文本
                    else {
                        cr.text = '#' + text + '#';
                    }
                    
                    if (text == defaultText) {
                        cr = input.createTextRange();
                        cr.collapse();
                        cr.moveStart('character', start);
                        cr.moveEnd('character', end);
                    }
                    
                    cr.select();
                    
                }
                else if (input.selectionStart || input.selectionStart == '0') {
                    start = input.selectionStart;
                    end = input.selectionEnd;
                    
                    //获取选中的文本
                    if (start != end) {
                        text = input.value.substring(start, end);
                    }
                    
                    //内容有默认主题，且没选中文本
                    if (hasCustomTopic && text == defaultText) {
                        start = RegExp.leftContext.length + 1;
                        end = start + text.length;
                    }
                    //内容没有默认主题，且没选中文本
                    else if (text == defaultText) {
                        input.value = input.value.substring(0, start) + '#' + text + '#' + input.value.substring(end, input.value.length);
                        start++;
                        end = start + text.length;
                    }
                    //有选中文本
                    else {
                        input.value = input.value.substring(0, start) + '#' + text + '#' + input.value.substring(end, input.value.length);
                        end = start = start + text.length + 2;
                    }
                    
                    //设置选中范围
                    input.selectionStart = start;
                    input.selectionEnd = end;
                }
                else {
                    input.value += '#' + text + '#';
                }
                
                $ui.textarea.keyup();
            },
            
            createEmotion: function(){
                var prefix = emotionPath;
                var content = '', eList = [];
                
                window.XWEIBO && $.each(window.XWEIBO.emotions, function(i, item){
                    content += '<a title="' + item[0] + '" href="javascript:;"><img src="' + prefix + item[1] + '" /></a>';
                    eList.push(item[0]);
                });
                
                var layer = XWB.layerMgr.addLayer({
                    layerid: 'xEmotion',
                    type: 'emotion',
                    config: {
                        eList: eList,
                        insertCallback: function(input){
                            $(input).keyup();
                        }
                    },
                    content: ['<div class="emotion-box">', content, '</div>'].join('')
                });
                
                layer.close();
                
                return layer;
            },
            
            createLayer: function(type){
                var layer;
                
                switch (type) {
                    case 'video':
                        layer = XWB.layerMgr.addLayer({
                            layerid: 'xVideo',
                            type: 'video',
                            content: ['<div class="insert-box">', '<p>请输入<a href="http://video.sina.com.cn/" target="_blank">新浪播客</a>、<a href="http://www.youku.com/" target="_blank">优酷网</a>、<a href="http://www.tudou.com/" target="_blank">土豆网</a>、<a href="http://www.ku6.com/"  target="_blank">酷6网</a>等视频网站的视频播放页链接</p>', '<input type="text" /><a class="general-btn" href="javascript:;"><span>确定</span></a>', '<p class="error-tips">你输入的链接地址无法识别<span><a href="javascript:;">取消操作</a>或者<a href="javascript:;">作为普通的链接</a>发布。</span></p>', '</div>'].join('')
                        });
                        break;
                    case 'music':
                        layer = XWB.layerMgr.addLayer({
                            layerid: 'xMusic',
                            type: 'music',
                            content: ['<div class="insert-box music-box">',                        //'<p><a class="insert-tab current" href="javascript:;">输入歌曲名</a><a class="insert-tab" href="javascript:;">输入歌曲链接</a></p>',
                            '<p>请输入<a href="http://music.sina.com.cn/yueku/" target="_blank">新浪乐库</a>等音乐站点的音乐播放页链接</p>', '<input type="text" /><a class="general-btn" href="javascript:;"><span>确定</span></a>', '<p class="error-tips">你输入的链接地址无法识别<span><a href="javascript:;">取消操作</a>或者<a href="javascript:;">作为普通的链接</a>发布。</span></p>', '</div>'].join('')
                        });
                        break;
                }
                
                var $err = $(layer.element).find('p.error-tips').hide();
                var $input = $(layer.element).find('input');
                
                $err.find('a').eq(0).bind('click', function(e){
                    layer.close();
                    e.preventDefault();
                });
                
                $err.find('a').eq(1).bind('click', function(e){
                    insertToArea();
                    e.preventDefault();
                });
                
                $(layer.element).find('a.general-btn').bind('click', function(e){
                    var url = $input.val();
                    
                    if (url == '' || url == 'http://') {
                        return;
                    }
                    
                    var check = type == 'video' ? wbSubjoin.checkVideoUrl : wbSubjoin.checkMusicUrl;
                    
                    if (check(url)) {
                        insertToArea();
                    }
                    else {
                        $err.show();
                    }
                    
                });
                
                // $input.mouseover(function(){
                    // this.focus();
                    // var cr;
                    
                    // if (document.selection) {
                        // cr = this.createTextRange();
                        // cr.collapse();
                        // cr.moveStart('character', 0);
                        // cr.moveEnd('character', this.value.length);
                        // cr.select();
                    // }
                    // else {
                        // this.selectionStart = 0;
                        // this.selectionEnd = this.value.length;
                    // }
                // });
                
                layer.close();
                
                function insertToArea(){
                    var $input = $(layer.element).find('input');
                    var url = $input.val();
                    
                    wbSubjoin.insertText(url);
                    $input.val('');
                    layer.close();
                }
                
                return layer;
            },
            
            selectAll: function(input) {
                input.focus();
                var cr;
                
                if (document.selection) {
                    cr = input.createTextRange();
                    cr.collapse();
                    cr.moveStart('character', 0);
                    cr.moveEnd('character', input.value.length);
                    cr.select();
                }
                else {
                    input.selectionStart = 0;
                    input.selectionEnd = input.value.length;
                }
            },
            
            showEmotion: function(rel, input, ox, oy){
                var emotion = XWB.layerMgr.get('xEmotion');
                
                if (!emotion) {
                    emotion = this.createEmotion();
                }
                
                if (rel instanceof $) 
                    rel = rel.get(0);
                
                emotion.config({
                    rel: rel,
                    input: input,
                    ox: ox || 0,
                    oy: oy || 0
                });
                
                XWB.layerMgr.showLayer('xEmotion', 'default');
            },
            
            showVideo: function(rel, ox, oy){
                var video = XWB.layerMgr.get('xVideo');
                if (!video) {
                    video = this.createLayer('video');
                }
                video.config({
                    rel: rel,
                    ox: ox || 0,
                    oy: oy || 0
                });
                XWB.layerMgr.showLayer('xVideo', 'default');
                
                $(video.element).find('p.error-tips').hide();
                $(video.element).find('input').val('http://');
                this.selectAll($(video.element).find('input')[0]);
            },
            
            showMusic: function(rel, ox, oy){
                var music = XWB.layerMgr.get('xMusic');
                if (!music) {
                    music = this.createLayer('music');
                }
                music.config({
                    rel: rel,
                    ox: ox || 0,
                    oy: oy || 0
                });
                XWB.layerMgr.showLayer('xMusic', 'default');
                
                $(music.element).find('p.error-tips').hide();
                $(music.element).find('input').val('http://');
                this.selectAll($(music.element).find('input')[0]);
            },
            
            insertText: function(text){
                $ui.textarea.insertText(text).focus();
                $ui.textarea.keyup();
            },
            
            checkMusicUrl: function(str){
                var match = FALSE, re = /(?:^http:\/\/club\.189\.cn\/favor\/music\/playCheckMusic\?mids=.\d+)|(?:^http:\/\/music\.sina\.com\.cn\/yueku\/i\/.\d+\.html)|(?:\.mp3$)/;
                
                match = re.test(str);
                
                return match;
            },
            
            checkVideoUrl: function(str){
            
                /*             var 
                 url = [
                 '(?:^http:\\/\\/2010\\.sina\.com\\.cn\\/video\\/.+)',
                 '(?:^http:\\/\\/video\\.sina\\.com\\.cn\\/.+)',
                 '(?:^http:\\/\\/v\\.ku6\\.com\\/special\\/.+)',
                 '(?:^http:\\/\\/www\\.tudou\\.com\\/playlist\\/playindex\\.do\\?lid.+)',
                 '(?:^http:\\/\\/v\\.youku\\.com\\/v_show/.+)'
                 ],
                 re = [], match = FALSE;
                 
                 $.each(url, function(i, item) {
                 re.push(item.replace(/\\/g,'\\\\'));
                 });
                 re = re.join('|');
                 
                 console.log(re);
                 
                 re = new RegExp(re),
                 
                 match = re.test(str);
                 
                 alert(match);
                 
                 return match; */
                var match = FALSE, re = /(?:^http:\/\/2010\.sina\.com\.cn\/video\/.+)|(?:^http:\/\/video\.sina\.com\.cn\/.+)|(?:^http:\/\/v\.ku6\.com\/special\/.+)|(?:^http:\/\/www\.tudou\.com\/playlist\/playindex\.do\?lid.+)|(?:^http:\/\/v\.youku\.com\/v_show\/.+)/;
                
                match = re.test(str);
                
                return match;
            }
        };
        
    })();
    xwb.subjoin = wbSubjoin;
    
    /**
     * 将冒泡的事件分发到对应的方法处理
     * @param {Object} e
     */
    function eventDispatch(e){
        var $target = $(e.target);
        var type = $target.attr('rel');
        
        if (type && type.toString().match(/\d+/ig)) {
            eventMgr.broadcast(type, $target, type);
            
            if ($target.attr('tagName') == 'A') {
                e.preventDefault();
            }
        }
    }
    
    
    $.extend($.fn, {
        flash: function(opts, conf){
            $(this).html(getFlashObject(opts, conf));
        }
    });
    
    function findSinaurl(data){
        var data = data || (XWEIBO && XWEIBO.data);
        
        var result = {
            urls: [],
            map: {}
        }, tmp, url_id;
        
        if (data) {
            var matchs, map = result.map, urls = result.urls;
            
            var reg = /http:\/\/sinaurl\.cn\/([0-9a-z]+)/gi;
            
            for (var i in data) {
                $.each([data[i], data[i].rt], function(idx, ele){
                    if (!ele) 
                        return;
                    var txt = ele.tx;
                    
                    while (reg.test(txt)) {
                        url_id = RegExp.$1;
                        
                        if (!map[url_id]) {
                            map[url_id] = [];
                        }
                        
                        urls.push(url_id);
                        map[url_id].push([i, idx]);
                    }
                });
            }
        }
        log(result);
        
        return result.urls.length ? result : NULL;
    }
    
    
    function getPreviewBox($li, is_forward){
        var $preview, $content;
        
        if (is_forward) {
            $content = $('div.forward', $li);
            $preview = $content.children('.preview-img');
        }
        else {
            $content = $('div.feed-content', $li);
            $preview = $('div.preview-img:first', $content);
        }
        
        if (!$preview.length) {
            $preview = $('<div class="preview-img"></div>');
            $('p:first', $content).after($preview);
        }
        
        return $preview;
    }
    
    /**
     * 添加视频预览图
     * @param {Object} url_id
     * @param {Object} video
     * @param {Object} $li
     */
    function addVideoPreview(url_id, video, $li, isforward){
        var $thumb = createVideoThumb(video.screen);
        
        var $box = getPreviewBox($li, isforward);
		
        $('div.video-view', $thumb).attr({
            is_forward: isforward,
            video_id: url_id
        });
        
		
		$('a[href$=' + url_id + ']', $li).each(function(i, ele){
			$(ele).addClass('video-url icon-bg');
		})
		.attr({
			rel: event_type_video,
            is_forward: isforward,
            video_id: url_id
        });
        //console.debug($box.html());
        $box.append($thumb);
    }
    
    /**
     * 音乐链接添加播放功能
     */
    function addMusic($li, url_id, linkInfo, music_type){
    	//禁用189
		if (music_type == music_type_189) {
			return;
		}
		
        $('a[href$=' + url_id + ']', $li).each(function(i, ele){
            $(ele).attr({
                rel: event_type_play_music,
                link_id: url_id,
                tid: getWeiboID($li),
                site: music_type
            }).addClass('music-url icon-bg');
        })
    }
    
    var sina_music_player = 'http://music.sina.com.cn/yueku/m.php';
    
    /**
     * 播放音乐
     */
    function playMusic($link){
        var link_id = $link.attr('link_id');
        var linkInfo = sinaurls.get(link_id);
        var tid = getWeiboID($link);
        
        var music_type = $link.attr('site');
        
        
        var playurl = '', size;
        
        if (music_type == music_type_sina) {
            size = 'width=629,height=595';
            
            var sinaurl = encodeURIComponent('http://sinaurl.cn/' + link_id);
            
            playurl = sina_music_player + '?ads=1&coFlag=200006&url=' + sinaurl + '&id=' + tid;
        }
        else 
            if (music_type == music_type_189) {
                playurl = linkInfo.url;
                size = 'width=490,height=550';
            }
        
        playurl && window.open(playurl, 'xweibo_player', size + ",top=" + (window.screen.height - 600) / 2 + ", left=" + (window.screen.width - 730) / 2 + ", toolbar=no, menubar=no, scrollbars=no,resizable=no,location=no, status=no");
    }
    
    /**
     * 刷新评论数和转发数
     */
    function counterAdd(data) {
        var ids = [];
        
        if(!data) {
            $.each(XWEIBO.data, function(i, item) {
                ids.push(i);
                if(item.rt && item.rt.id) {
                    ids.push(item.rt.id);
                }
            });
            
            ids = ids.join(',');
        }
    
        apiCall('getCounts', {
            data: data||{'ids':ids},
            success: function(ret) {
                log('查询评论数和转发数', ret);
                if(ret.errno === 0) {
                    ret.rst && $.each(ret.rst, function(i, item) {
                        if(item[0]) {
                            $('#i'+i).find('.feed-info a[rel=3]').text('评论('+item[0]+')');
                        }
                        if(item[1]) {
                            $('#i'+i).find('.feed-info a[rel=1]').text('转发('+item[1]+')');
                        }
                        
                        //转发微博里面的计数
                        $.each(XWEIBO.data, function(j, wbData) {
                            if(wbData.rt && wbData.rt.id == i) {
                                var $tarEl = $('#i'+j).find('.forward>p>span>a');
                                
                                if(item[0]) {
                                    $tarEl.eq(1).text('原文评论('+item[0]+')');
                                }
                                if(item[1]) {
                                    $tarEl.eq(0).text('原文转发('+item[1]+')');
                                }
                            }
                        });
                        
                    });
                }
            }
        });
    }
    
    
    /**
     * 查找sinaurl的信息，重新渲染
     */
    function linkRender(data){
        var url = findSinaurl(data);
        
        if (url) {
            //url ID 集合
            var urls = url.urls;
            
            //sinaurl ID  -> 微博ID映射
            var map = url.map;
            
            sinaurls.query(urls, function(data){
                for (var url_id in data) {
                    $.each(map[url_id], function(i, pos){
                        var tid = pos[0];
                        var isforward = pos[1];
                        
                        var $li = $('#i' + tid);
                        
                        var linkInfo = data[url_id];
                        
                        switch (linkInfo.type) {
                            case 'url':
                                // http://club.189.cn/favor/music/playCheckMusic?mids=2622458
                                if (linkInfo.url.indexOf('http://club.189.cn/favor/music/playCheckMusic?mids=') == 0) {
                                    addMusic($li, url_id, linkInfo, music_type_189);
                                }
                                break;
                                
                            case 'video':
                                addVideoPreview(url_id, linkInfo, $li, isforward);
                                break;
                                
                            case 'music':
                                addMusic($li, url_id, linkInfo, music_type_sina);
                                break;
                        }
                    });
                }
            });
        }
    }
	
	/**
	 * 截断超长名字
	 * @param {Object} name
	 */
	function getShortFileName(str, len) {
		if (str.indexOf('\\')) {
			var parts = str.split('\\');
			str = parts.pop();
		}
			
		if (str.length > len) {
			return str.substr(0, len-4) + '..' + str.substr(str.length-4);
		}
		else {
			return str;
		}
	}
    
    var publishBox = (function(){
        var $floatBox, $textarea;
		var box, defaultText;
		var uploader;
		var pic = '';
		var $uploading;
		var $filename;
		var $file;
		var $form;
		var $pic;
		var $publish;
		
        function getBox(){
            if (!$floatBox) {
                var html = ['<div class="pop-window post-window fixed-window">', 
				'<div class="pop-t"></div>', 
				'<div class="pop-content">', 
				'<h4 class="pop-title x-bg"><a href="#" rel="close" class="close-btn icon-bg"></a>有什么新鲜事想告诉大家？</h4>', 
				'<div class="post-box">', 
				'<div class="key-tips">您还可以输入<span>140</span>字</div>', 
				'<div class="post-textarea skin-bg"><textarea id="publish_text"></textarea></div>', 
				'<div class="add-area">', 
				'<a href="#" class="face-icon icon-bg">表情</a>',
				'<span style="display:none" class="pic_uploading">正在上传..</span>', 
				'<span style="display:none" class="pic_name"></span>', 
				'<a href="#" class="pic-icon icon-bg">图片</a>', 
				'<a href="#" class="video-icon icon-bg">视频</a>', 
				'<a href="#" class="music-icon icon-bg">音乐</a>', 
				'<a href="#" class="topic-icon icon-bg">话题</a>', 
				'</div>', 
				'<div class="share-btn skin-bg"></div>', 
				'<form target="upload_frame" action="?m=action.upload_pic" enctype="multipart/form-data" method="post" class="upload-pic"><input type="file" value="" name="pic"></form>', 
				'<div class="post-tips">请输入要发布的微博内容</div>', 
				'<div class="post-success all-bg" style="display:none"></div>', 
				'</div>', 
				'</div>', 
				'<div class="pop-b"></div>',
				 '<div class="pop-tl all-bg"></div>', 
				 '<div class="pop-tr all-bg"></div>', 
				 '<div class="pop-bl all-bg"></div>', 
				 '<div class="pop-br all-bg"></div>', 
				 '</div>'].join('');
                
                //添加到body
                $floatBox = $(html).appendTo('body');
                
                $textarea = $('textarea', $floatBox);
                
                //添加焦点样式
                $textarea.focus(function(){
                    $textarea.parent().addClass('onfocus');
                }).blur(function(){
                    $textarea.parent().removeClass('onfocus');
                });
                
                var $tip = $('.key-tips', $floatBox);
                
                var outclass = 'icon-bg out140';
                
                $textarea.keyup(function(){
                    var len = $textarea.checkText();
                    if (len >= 0) {
                        $tip.html('您还可以输入<span>' + len + '</span>字').removeClass(outclass);
                    }
                    else {
                        $tip.html('已超出<span>' + Math.abs(len) + '</span>字').addClass(outclass);
                    }
                });
				
				$pic = $('a.pic-icon', $floatBox);
				$form = $('form', $floatBox);
				$publish = $('div.share-btn', $floatBox);
				
				//图片上传
				$file = $('input[type=file]', $floatBox);
				uploader = new FileUploader($file.get(0));
				$uploading = $('span.pic_uploading', $floatBox);
				$filename = $('span.pic_name', $floatBox);
				
				$file.change(function(){
					if (!checkPicName(this.value)) {
						alertMsg({
			                msg: '只支持 jpg、png、gif 的图片。',
			                timeout: 2,
							callback: function(){
								$textarea.focus();
							}
			            });
						return;
					}
					
					$uploading.show();
					$form.hide();
					$pic.hide();
					
					$publish.addClass(disable_class);
					
					var filename  = this.value;
					
					uploader.upload(function(ret){
						$uploading.hide();
						
						var rst = ret.rst, errno = ret.errno;
						
						if (errno == '0') {
							pic = rst.msg;
							$filename.html(getShortFileName(filename, 10) + '<a href="#" rel="delPic" class="close-btn icon-bg"></a>').show();
							$form.hide();
							if ($textarea.val() == '') {
								$textarea.val('分享图片').focusEnd();
							}
						}
						else {
							alertMsg({
								type: 'error',
								msg: getError(errno),
								timeout: 2,
								callback: function(){
									$textarea.focus();
								}
							});
							$form.show();
							$pic.show();
						}
						$publish.removeClass(disable_class);
					});
				})
                
                //wbSubjoin.init();
                
                wbSubjoin.setUiCache({
                    textarea: $textarea
                });
				
				box = $floatBox.toXwin();
                
                //绑定事件
                $floatBox.click(function(e){
                    var $target = $(e.target);

                    var stopDefault = TRUE;
                    
                    switch (TRUE) {
						case $target.attr('rel') == 'delPic':
							pic = '';
							$form.show();
							$pic.show();
							$filename.hide();
						break;
						
                        case $target.hasClass('share-btn'): //发布
							
                        	//如果按键被禁用，直接返回
							if ($target.hasClass(disable_class)) {
								return;
							}
							
							//禁用发布按键
							$target.addClass(disable_class);
							
                        	var text = $textarea.val();
							
                        	var data = {
								text: text
							};
							
							if (pic)
								data.pic = pic;
							
							var err = publisher.checkInput($textarea);

							if (err) {								
								alertMsg({
									msg: getError(err),
									timeout: 2,
									callback: function(){
										$textarea.focus();
										$target.removeClass(disable_class);
									}
								});
							}
							else {
								apiCall('update', {
									data: data,
									success: function(ret){
										var errno = ret.errno;
										if (toInt(errno) == 0) { //成功发布
											var rst = ret.rst;
											
											var $success = $('div.post-success', $floatBox);
											$success.show();
											$success.fadeOut(2000, function(){
												box.close();
												
												//删除禁用样式
												$target.removeClass(disable_class);
											});
											
											$textarea.val('');
										}
										else { //失败
											alertMsg({
												msg: getError(errno),
												type: 'error',
												timeout: 2,
												callback: function(){
													//删除禁用样式
													$target.removeClass(disable_class);
													$textarea.focus();
												}
											});
										}
										
									}
								});
							}
                            break;
                            
                        case $target.attr('rel') == 'close': //关闭
                            //$floatBox.hide();
							box.close();
                            break;
                            
                            
                        case $target.hasClass('face-icon'): //表情
                            wbSubjoin.showEmotion($target, $textarea, 0, 30);
                            e.stopPropagation();
                            break;
                            
                        case $target.hasClass('video-icon'):
                            wbSubjoin.showVideo($target, -150, 30);
                            e.stopPropagation();
                            break;
                            
                        case $target.hasClass('music-icon'):
                            wbSubjoin.showMusic($target, -150, 30);
                            e.stopPropagation();
                            break;
                            
                        case $target.hasClass('topic-icon'):
                            wbSubjoin.insertTopic();
                            break;
                            
                        default:
                            stopDefault = FALSE;
                    }
                    
                    stopDefault && e.preventDefault();
                });
				
            }
			
			return box;
            
            //return $floatBox;
        }
        
        return {
            show: function(text){
                getBox().show();
				if (defaultText) {
					$textarea.val(defaultText);
					$textarea.focusEnd();
				}
				$textarea.keyup();
				$textarea.focus();
            },
			
			init: function($btn, text){
				defaultText = text;
				$btn.click(function(e){
					publishBox.show();
	            	e.preventDefault();
				})
			}
        }
    })();
    
	xwb.publishBox = publishBox;
	
	function checkPicName(filename) {
		var pieces = filename.split('.');
            
        if (!pieces.length || -1 == $.inArray(pieces.pop().toLowerCase(), ['jpg', 'png', 'gif'])) {            
            return FALSE;
        }
		
		return TRUE;
	}
    
    var publisher = (function(){
        var        //上传状态
        uploading = FALSE,        //发布状态
        publishing = FALSE,        //图片
        pic = '', $box,        //文字输入框 
        $input,        //发布按钮
        $submit,        //剩余文字提示
        $tips,        //微博列表
        $list,        //已上传的图片
        $btnPhoto,        //图片的实际按键<input[file] />
        $photo,
        $btnUpload,
		$uploading,
		$form,
		uploader;
		
		var insertToList = FALSE; 
        
        var $floatBox;
        
        function show(){
            var html = ['<div class="pop-window post-window fixed-window">', '<div class="pop-t"></div>', '<div class="pop-content">', '<h4 class="pop-title x-bg"><a href="#" class="close-btn icon-bg"></a>爱说就说吧</h4>', '<div class="post-box">', '<div class="key-tips out140 icon-bg">您还可以输入<span>140</span>字</div>', '<div class="post-textarea skin-bg"><textarea></textarea></div>', '<div class="add-area">', '<a href="javascript:;" class="face-icon icon-bg">表情</a>', '<span class="hidden">fdsafadsf.gif<a href="#" class="close-btn icon-bg"></a></span>', '<a href="javascript:;" class="pic-icon icon-bg">照片</a>', '<a href="javascript:;" class="video-icon icon-bg">视频</a>', '<a href="javascript:;" class="music-icon icon-bg">音乐</a>', '<a href="javascript:;" class="topic-icon icon-bg">话题</a>', '</div>', '<div class="share-btn skin-bg"></div>', '<form class="upload-pic"><input type="file" value=""></form>', '<div class="post-tips">请输入要发布的微博内容</div>', '<div class="post-success all-bg"></div>', '</div>', '</div>', '<div class="pop-b"></div>', '<div class="pop-tl all-bg"></div>', '<div class="pop-tr all-bg"></div>', '<div class="pop-bl all-bg"></div>', '<div class="pop-br all-bg"></div>', '</div>'].join('');
            
            $floatBox = $(html).appendTo('body');
        }
        
        function delImg(){
            pic = '';
			$btnPhoto.show();
			$form.show();
			$photo.hide();
        }
        
        function bindEvent($box){
            //输入框聚焦事件
            $input.focus(function(){
                $input.parent().addClass('onfocus');
            }).blur(function(){
                $input.parent().removeClass('onfocus');
            });
            
            //绑定字数检查事件
            $input.keyup(function(){
                var remain = $input.checkText();
                
                if (remain >= 0) {
                    $tips.html('您还可以输入<span>' + remain + '</span>字').removeClass('out140 icon-bg');
                }
                else {
                    $tips.html('已超出<span>' + Math.abs(remain) + '</span>字').addClass('out140 icon-bg');
                }
            });
            
            //上传图片
            $btnUpload.change(uploadImg);
            
            $box.click(function(e){
                var $target = $(e.target);
                var rel = toInt($target.attr('rel'));
                
                if (rel) {
                    switch (rel) {
                        case event_type_photo_del:
                            delImg();
                            break;
                            
                        case event_type_publish:
                            publish();
                            break;
                    }
                    
                    if ($target.attr('tagName') == 'A') {
                        e.preventDefault();
                    }
                }
            })
        }
        
        /**
         * 插入一条微博到列表中
         * @param id object 微博ID
         * @param data object 微博的信息
         * @param html string
         */
        function insert(id, data, html){
            try {
                XWEIBO.data[id] = data;
                $list && $(html).prependTo($list).hide().fadeIn(1000, function(){
					var envlope = {};
					envlope[id] = data;
					linkRender(envlope);
				});
            } 
            catch (e) {
				throw e;
            };
        }
		
		function checkInput($input) {
			var err = 0;
			
			var text = $input.val();
			
			if ($input.checkText() < 0) {
				err = 5;
			}
            if (!$.trim(text)) {
                err = 3;
            } 
			else if  (text == '#请在这里输入自定义话题#') {
				err = 4;	
			}
			
			return err;
		}
        
        function publish(){
			var text = $input.val();
			 
            var data = {
                text: text
            };
            
            var err = 0;

            if (uploading) {
                err = 1;
            }
            else if (publishing) {
                err = 2;
            }
			else {
				err = checkInput($input);
			}
            
            if (err) {
                alertMsg({
                    msg: getError(err),
                    timeout: 2,
					callback: function(){
						$input.focus();
					}
                });
                return;
            }
            
            if (pic) {
                data.pic = pic;
            }
            
            publishing = 1;
            $submit.addClass(disable_class);
            
            apiCall('update', {
                data: data,
                success: function(ret){
					var errno = ret.errno;
                    if (toInt(errno) == 0) { //成功发布
                        var rst = ret.rst;
                        
						if (insertToList) 
							insert(rst.data.id, rst.data, rst.html);
                        delImg();
                        
                        var $success = $('<div class="post-success all-bg"></div>');
                        $success.appendTo($box);
						$('#user-weibo-count').zoomText();
                        $success.fadeOut(2000, function(){
                            $success.remove();
							$input.focus();
                        });
                        
                        $input.val('');
                        
                        $('#publish_box .key-tips span').text(140);
                    }
                    else { //失败
                        alertMsg({
                            msg: getError(errno),
							type: 'error'
                        });
                    }
                    
                    publishing = 0;
                    $submit.removeClass(disable_class);
                }
            });
        }
        
        function uploadImg(){
            var $file = $(this);
            
            var filename = $file.val();
            
            if (!filename || !checkPicName(filename)) {
				alertMsg({
	                msg: '只支持 jpg、png、gif 的图片。',
	                timeout: 2,
					callback: function(){
						$input.focus();
					}
	            });
				return;
			}
			
			$uploading.show();
			$form.hide();
			$submit.addClass(disable_class);
			$btnPhoto.hide();
            
			uploader.upload(function(ret){
				var errno = ret.errno;
				
				if (errno == '0') {
					var rst = ret.rst;
					pic = rst.msg;
					$photo.html(getShortFileName($file.val(), 10) + '<a href="#" rel="'+event_type_photo_del+'" class="close-btn icon-bg"></a>').show();
					!$.trim($input.val()) && $input.val('分享图片');
					$uploading.hide();
				}
				else {
					alertMsg({
						type: 'error',
						msg: getError(errno),
						timeout: 2
					});
					
					$uploading.hide();
					$btnPhoto.show();
					$form.show();
				}
				
				$submit.removeClass(disable_class);
			});
        }
        
        return {
            init: function(boxSelector, listSelector, needInsert){
                $box = $(boxSelector);
				
				if (needInsert)
					insertToList = needInsert;
                
                $tips = $('div.key-tips', $box);
                $input = $('#publish_text', $box);
                $submit = $('div.share-btn', $box);
                $list = listSelector ? $(listSelector): NULL;
                $photo = $('#photo_name', $box);
				$uploading = $('span.pic_uploading', $box);
                $btnPhoto = $('a.pic-icon', $box);
                $btnUpload = $('#publisher_file', $box);
				$form = $btnUpload.parent();
				
                uploader = new FileUploader($btnUpload.get(0));
                
                bindEvent($box);
                
                wbSubjoin.init();
            },
            
            insert: insert,
			
			checkInput: checkInput
        }
        
    })();
	
	/**
	 * 生成微博列表的LI HTML
	 * @param {Object} row
     * @param {Object} opt
	 */
	function toWeiboHtml(row, opt) {
        var frag = document.createDocumentFragment();
    
		var showFace, showOper, showUnread, avatarSize;
		
		if (opt) {
			showFace = opt.avatar === UNDEFINED ? TRUE : opt.avatar;
			showOper = opt.button === UNDEFINED ? TRUE : opt.button;
            showUnread = opt.isUnread;
		}
        
        var unreadClass = showUnread ? 'class="unread"' : '';
        
		$.each(row, function(i, item) {
            var 
                wbHtml = '',
                user = item.u,
                vStyle = user.sina_v ? 'class="v-icon icon-bg"' : '',
                forwardHtml = '',
                oprateHtml = '',
                faceHtml = '',
                imgHtml = '',
                userUrl = buildModulePath('ta', '', 'id='+user.id),
                detailUrl = buildModulePath('show', '', 'id='+item.id);
            
            //重复微博，跳过
            if($('#i'+item.id)[0]) { return true;}
            
            if(showFace) {
                faceHtml = '<div class="user-pic"><a href="'+userUrl+'"><img title="' +user.sn+ '" alt="' +user.sn+ '" src="'+user.p+'" /></a></div>';
            }
            
            if(showOper) {
                var delHtml = '';
                
                if(user.id == XWEIBO.uid) {
                    delHtml = '|<a rel="16" href="#">删除</a>';
                }
                
                oprateHtml = '<a href="'+detailUrl+'">查看</a>'+delHtml+'|<a rel="1" href="#">转发'+(item.rts?'('+item.rts+')':'')+'</a>|<a rel="2" href="#">收藏</a>|<a rel="3" href="#">评论'+(item.comments?'('+item.comments+')':'')+'</a></p>';
            }
            
            if(item.tp) {
                imgHtml = '<div class="preview-img"><div class="feed-img"><img alt="" rel="4" src="'+item.tp+'" class="zoom-move"></div></div>';
            }
            
            if(item.rt && item.rt.u) {
                var 
                    rtImgHtml = '',
                    rt = item.rt,
                    rtu = rt.u;
                    
                if(rt.tp) {
                    rtImgHtml = '<div class="preview-img"><div class="feed-img"><img alt="" rel="12" src="'+rt.tp+'" class="zoom-move"></div></div>';
                }
                
                forwardHtml = [
                    '<div class="box-style">',
                        '<div class="box-t skin-bg"><span class="skin-bg"></span></div>',
                        '<div class="forward box-content  showbox-f">',
                            '<p><a href="' +buildModulePath('ta', '', 'id='+rtu.id)+ '">@' +rtu.sn+ '</a>：',
                                rt.ftx,
                                '<span><a href="' +buildModulePath('show', '', 'id='+rt.id)+ '">原文转发'+(rt.rts?'('+rt.rts+')':'')+'</a>|<a href="' +buildModulePath('show', '', 'id='+rt.id)+ '">原文评论'+(rt.comments?'('+rt.comments+')':'')+'</a></span>',
                            '</p>',
                            rtImgHtml,
                        '</div>',
                        '<div class="box-b skin-bg"><span class="skin-bg"></span></div>',
                        '<span class="box-arrow skin-bg"></span>',
                    '</div>'
                ].join('');
            }
            
            wbHtml = [
                '<li id="i' + item.id + '" '+unreadClass+' style="display:none">',
                    faceHtml,
                    '<div class="feed-content">',
                        '<p class="feed-main">',
                            '<a title="' +user.sn+ '" href="'+userUrl+'" ' +vStyle+ '>' +user.sn+ '</a>：',
                            item.ftx,
                        '</p>',
                        imgHtml,
                        forwardHtml,
                        '<div class="feed-info">',
                            '<p>'+oprateHtml+'</p>',
                            '<span><a href="'+detailUrl+'">' +item.cr+ '</a> 来自 ' +item.s+ '</span>',
                        '</div>',
                    '</div>',
                '</li>'
            ].join('');
            
            frag.appendChild($(wbHtml)[0]);
        });
        
        return frag;
 
	}
    
    var wbAutoInsert = (function() {
        
        var 
            timeout = NULL,
            ctn = NULL,
            delay = 5000,
            count = 10,
            dataCache = []; //缓存新微博数据
            
        return {
            hasInit: FALSE,
            isStop: TRUE,
            
            init: function(opt) {
                log('自动插入初始化');
                if(opt) {
                    ctn = opt.ctn;
                    delay = opt.delay || delay;
                    count = opt.count || count;
                }

                this.hasInit = TRUE;
            },
            //追加数据到缓存中
            pushData: function(data) {
                if(data && data.length && data instanceof Array) {
                    log('追加数据到缓存中：%o', data);

                    $.each(data, function(i, item) {
                        var hasExist = FALSE;
                        $.each(dataCache, function(j, citem) {
                            if(citem.id === item.id) {
                                hasExist = TRUE;
                                return false;
                            }
                        });
                        hasExist || dataCache.push(item);
                    });
                }
                
                if(dataCache.length && wbReader.firstIsInVeiw()) {
                    this.stop();
                    this.insert();
                }
            },

            slideDown: function(nodes) {
                if(nodes.length) {
                    var node = nodes.shift();
                    
                    $(node).slideDown(400, function() {
                        wbAutoInsert.slideDown(nodes);
                    });
                }
            },
            
            insert: function() {
                this.isStop = FALSE;
                log('数据缓存:%s',dataCache.length);
                if(!$(ctn)[0] || !dataCache.length) { return ;}
                
                //用于计算插入后产生的高度差
                var 
                    //offsetH = 0,
                    //$first = NULL,
                    $last = $(ctn).find("li:first-child");
                
                //从缓存中取最后n=count条数据
                var startNum = dataCache.length - count;
                startNum = startNum<0 ? 0 : startNum;
                var data = dataCache.splice(startNum, count);
                
                //创建DOM，存放到文档碎片中
                var domFragment = toWeiboHtml(data, {
                    'isUnread': TRUE
                });

                var newListArr = $.makeArray(domFragment.childNodes);
                
                $(ctn)[0].insertBefore(domFragment, $last[0]);
                
                log('成功插入DOM');
                
                wbAutoInsert.slideDown(newListArr);
                
                // $first = $(ctn).find("li:first-child");
                // offsetH = ($last.offset().top - $first.offset().top);                
                // $(document).scrollTop($(document).scrollTop()+offsetH);
                
                var clild = $(ctn).children();
                while(clild.length >= 500) {
                    clild.last().empty().remove();
                }
                
                //超链接检查
                var temData = {};
                $.each(data, function(i, item) {
                    temData[item.id] = item;
                });
                
                linkRender(temData);
                
                // log('高度差:%s',offsetH);
                
                //定时执行
                timeout = setTimeout(arguments.callee, delay);
            },
            
            clearCache: function() {
                dataCache = [];
            },
            
            stop: function() {
                this.isStop = TRUE;
                log('停止自动插入');
                clearTimeout(timeout);
            }
        };
    })();
    
    var notifyChecker = (function(){
    
        var timer = NULL;
        
        var lastestId = 0;
        
        var tips = {
            //浮层
            panel: NULL,
            
            //浮层里的元素
            elements: {
                fans: NULL,
                comment: NULL,
                atme: NULL,
                priLetter: NULL
            },
            
            init: function(type){
                var $panel, $item;
            
                switch(type) {
                    case 'top':
                        $panel = $([
                            '<div class="new-tips">', 
                                '<a href="' + buildModulePath('index', 'fans') + '">n%个新粉丝</a><a href="' + buildModulePath('index', 'comments') + '">n%条新评论</a><a href="' + buildModulePath('index', 'messages') + '">n%封新私信</a><a href="' + buildModulePath('index', 'atme') + '">n%条微博提到我</a>', 
                                '<a class="close-icon icon-bg" href="javascript:;"></a>',
                                '<span class="tips-l"></span>', 
                                '<span class="tips-r"></span>', 
                            '</div>'].join(''));
                        
                        $('div.inner-header').append($panel);
                        
                        $item = $('a', $panel);

                        break;
                        
                    case 'bottom':
                        $panel = $([
                            '<div class="new-tips-fixed">',
                                '<h4>提示</h4>',
                                '<p>您有n%个新粉丝，<a href="' + buildModulePath('index', 'fans') + '">点击查看</a></p>',
                                '<p>您有n%条新评论，<a href="' + buildModulePath('index', 'comments') + '">点击查看</a></p>',
                                '<p>您有n%封新私信，<a href="' + buildModulePath('index', 'messages') + '">点击查看</a></p>',
                                '<p>有n%条微博提到我，<a href="' + buildModulePath('index', 'atme') + '">点击查看</a></p>',
                                '<a class="close-icon icon-bg" href="javascript:;"></a>',
                                '<span class="tips-t"></span>',
                                '<span class="tips-b"></span>',
                            '</div>'
                        ].join(''));
                        
                        $(document.body).append($panel);
                        
                        $item = $('p', $panel);
                        
                        break;
                }
                
                $panel.find('a.close-icon').click(function() {
                    $panel.hide();
                });
                
                this.panel = $panel; 
                var elements = this.elements;
                elements.fans = $item.eq(0);
                elements.comment = $item.eq(1);
                elements.priLetter = $item.eq(2);
                elements.atme = $item.eq(3);
            },
            
            show: function(type, fans, comment, atme, priLetter){
                var panel = this.panel;
                
                if (fans || comment || atme || priLetter) {
                    !panel && this.init(type);
                    
                    var elements = this.elements;
                    var 
                        fansTip = elements.fans, 
                        comTip = elements.comment, 
                        priTip = elements.priLetter, 
                        atmeTip = elements.atme;
                    
                    fans ? fansTip.html(fansTip.html().replace('n%',fans)).show() : fansTip.hide();
                    comment ? comTip.html(comTip.html().replace('n%',comment)).show() : comTip.hide();
                    priLetter ? priTip.html(priTip.html().replace('n%',priLetter)).show() : priTip.hide();
                    atme ? atmeTip.html(atmeTip.html().replace('n%',atme)).show() : atmeTip.hide();
                    
                    this.panel.show();
                    
                    //显示初次提醒浮层
                    if(window.XWEIBO && XWEIBO.tipshow === '' && !XWEIBO.allTip) {
                        XWEIBO.allTip = new wbTipsLayer({
                            type: 'tips',
                            confirmCallback: function() {
                                apiCall('setting', {
                                    data: {
                                        type: 'tipshow'
                                    }
                                });
                            }
                        }).init();
                        XWEIBO.allTip.show();
                    }
                }
                else {
                    panel && panel.hide();
                }
                
            }
        };
		
        /**
         * 检查新信息数
         */
        function checkNewItem(){
			var data = {};
                
            log('lastestId:%s',lastestId);
            
			if (lastestId) data.id = lastestId;
			
            apiCall('unread', {
                data: data,
                success: function(ret){
                    if (ret && (toInt(ret.errno) == 0)) {//成功返回, [新微博数,@我数,评论数,新粉丝]
                        var data = ret.rst.unread;
						
						var list = ret.rst.data;						
                        
                        //新微博数 
                        var itemNum = data[0];
                        
                        //判断是否自动插入
                        if(XWEIBO && +XWEIBO.autoshow && XWEIBO.page == 1) {
                        
                            wbAutoInsert.hasInit || wbAutoInsert.init({
                                'ctn': $('#feed-list')
                            });
                            
                            
                            wbAutoInsert.pushData(list);
                            
                            if(list) {   
                            
                                $.each(list, function(i, item) {
                                    XWEIBO.data[item.id] = item;
                                });
                                
                                lastestId = list[list.length-1].id;
                            }
                            
                        }else {
                        
                            var $newItemShow = $('#new-feed').html("你有" + itemNum + "条新微博，点击查看").attr('href', buildModulePath('index'));
                            itemNum ? $('#new-feed').slideDown('fast') : $('#new-feed').slideUp('fast');
                            
                            wbAutoInsert.hasInit && wbAutoInsert.stop();
                            
                            // if(itemNum && window.XWEIBO && XWEIBO.autoshow === '' && !XWEIBO.wbTip) {
                                // XWEIBO.wbTip = new wbTipsLayer({
                                    // type: 'weibo',
                                    // confirmCallback: function() {
                                        // apiCall('setting', {
                                            // data: {
                                                // type: 'autoshow'
                                            // }
                                        // });
                                    // }
                                // }).init();
                                // XWEIBO.wbTip.show();
                            // }
                        }
                        
                        //新fans、新评论、新@me、新私信
                        if(window.XWEIBO) {
                            log('提示浮层', data);
                            var tipType = +XWEIBO.tipshow ? 'bottom' : 'top';
                            tips.show(tipType, data[3], data[2], data[1], data[4]);
                        }
                        
                    }
                    else {//有错误
                    }
                    
                    timer = setTimeout(checkNewItem, 30000);
                },
			error: function(){
				timer = setTimeout(checkNewItem, 30000);
			}
            })
        }
        
        function checkStart(lid){
            lastestId = lid;
            
            if (!timer) {
                checkNewItem();
            }
        }
        
        return {
            start: checkStart
        }
    })();
    
    /**
     * 捕捉关注事件
     * @param {Object} $container
     * ship: 0 互相没关注 1我关注他 2他关注我 3互相关注
     */
    function listenAttention($container, type, userid, ship){
		var attention = xwb.attention, disabled_class = 'disabled';
		
		var hover_handler = function(e){
			var $target = $(e.target);
			var onList = $target.attr('tagName') == 'LI';
			var $li =  onList ? $target: findParentElement('LI', $target);
			
			var $btn = $('a.forjs-cancel-att,a.forjs-private', $li);

			if ($btn.length) {
				if ((e.type == 'mouseover') && (onList || $.contains($li.get(0), e.target))) {
					$btn.show();
				}
				else 
					if (!$.contains($li.get(0), e.relatedTarget)) {
						$btn.hide();
					}
			}
            
		}
		
		if (type == 1) { //页:我关注的人, 出现的人都已经关注
			$container.click(function(e){
				var $target = $(e.target);
				
				if ($target.hasClass('forjs-cancel-att')) {
						
						confirmBox({
							title: '提示',
							msg:'确定要取消关注吗?'
						},function(){
							var uid = $target.attr('rel');
							
							var $li = findParentElement('LI', $target);
							
							attention(uid, 0, function(ret){
								if (ret.errno == '0') {
									$li.slideUp('normal', function(){
										$li.remove();
									});
								} 
								else { //发生错误
									alertMsg({
										msg: '发生错误: ' + htmlEscape(ret.err),
										timeout: 2
									})
								}
							});
						});
					
					e.preventDefault();
				}
			}) ;
		
			$container.mouseover(hover_handler).mouseout(hover_handler);
			
		}
		else if (type == 2) {//我的粉丝，容器内的所有用户都在关注我
			$container.mouseover(hover_handler).mouseout(hover_handler);
						
			$container.click(function(e){
				var $target = $(e.target);
				
				if ($target.hasClass('forjs-cancel-att')) { //取消关注
					if (!$target.hasClass('disabled')) {
						$target.addClass('disabled');
						
						var uid = $target.attr('rel');
						attention(uid, 0, function(ret){
							if (ret.errno == '0') {
								$target.parent().replaceWith('<div class="content-r"><a rel="'+uid+'" href="#" class="addfollow-btn all-bg"></a></div>');
							}
							else {
								alertMsg({
									msg: '发生错误：' + htmlEscape(ret.err),
									timeout: 2
								});
							}
						});
					}
					
					e.preventDefault();
				}
				else if ($target.hasClass('addfollow-btn')) {
					if (!$target.hasClass('disabled')) {
						$target.addClass('disabled');
						
						var uid = $target.attr('rel');
						attention(uid, 1, function(ret){
							if (ret.errno == '0') { //成功关注
								$target.parent().replaceWith('<div class="content-r"><div class="each-follow all-bg"></div><a rel="'+uid+'" class="forjs-cancel-att" href="#">取消关注</a></div>');
							}
						})
					}
					
					e.preventDefault();
				}
			});
		}
		else if (type == 3) { //TA的微博页
			//var html =$('a.at-user', $container).html();
			
			function changeShip($obj, ns) {
				ship ^= ns;
				//var strs = ['<a href="#" class="at-user">'+html+'</a>'];
				var strs = [];
				
				if (ship == 3) { //他有关注我
					strs.push('<div class="each-follow all-bg"></div>');
					strs.push('<em>|</em>');
					strs.push('<a href="#" class="forjs-cancel-att">取消关注</a>');
				}
				else if (ship == 2 || ship == 0) {
					strs.push('<a href="#" class="general-btn addAtt"><span class="addAtt">加关注</span></a>');
				}
				else if (ship == 1) {
					strs.push('<span class="followed-icon icon-bg">已关注</span>');
					strs.push('<em>|</em>');
					strs.push('<a href="#" class="forjs-cancel-att">取消关注</a>');
				}
				
				$obj.children().not('a.at-user').remove();
				$obj.append(strs.join(''));			
				//return strs.join('');
			}
			
			$container.click(function(e){
				var $target = $(e.target);
				
				switch (TRUE) {
					case $target.hasClass('addAtt'): //关注他
						if (!$target.hasClass(disabled_class)) {
							$target.addClass(disabled_class);
							
							attention(userid, 1, function(ret){
								if (ret.errno == '0') {
									changeShip($container, 1);
									//ship ^= 1;
									//$container.html(getHtml());
									//$container.prepend($atBtn);
								}	
								else {
									alertMsg({
										type: 'error',
										msg: '发生错误：' + htmlEscape(ret.err),
										timeout:2
									})
								}						
							});
						}
					break;
					
					case $target.hasClass('forjs-cancel-att'): //取消关注他
						if (!$target.hasClass(disabled_class)) {
							$target.addClass(disabled_class);
							
							attention(userid, 0, function(ret){
								if (ret.errno == '0') {
									//ship ^= 1;
									//$container.html(getHtml());
									changeShip($container, 1);
								}	
								else {
									alertMsg({
										type: 'error',
										msg: '发生错误：' + htmlEscape(ret.err),
										timeout:2
									})
								}						
							});
						}
					break;
				}
				
				e.preventDefault();
			})
		}
		else {
			$container.click(function(e){
				var $target = $(e.target);
				
				if ($target.hasClass('addfollow-btn')) {
					if (!$target.hasClass('disabled')) {
						$target.addClass('disabled');
						
						var uid = $target.attr('rel');
						
						attention(uid, 1, function(ret){
							if (ret.errno == '0') {
								$target.replaceWith('<span class="followed-icon icon-bg">已关注</span>');
							}
							else {
								alertMsg({
									msg: '关注失败：' + htmlEscape(ret.err)
								});
							}
						})
					}
					
					e.preventDefault();
				}
			})
		}
    }
    
    xwb.linkRender = linkRender;
    
    xwb.listenAttention = listenAttention;
    
    xwb.publisher = publisher;
    
    xwb.setList = function($feedList){
    
        regEvent(event_type_thumbpic, viewMiddlePic);
        regEvent(event_type_pic_forward, viewMiddlePic);
        regEvent(event_type_video, showListVideo);
        regEvent(event_type_fav, addWeiboFavorite);
        regEvent(event_type_fav_del, delWeiboFavorite);
        regEvent(event_type_forward, weiboForward);
        regEvent(event_type_delete, deleteWeiboConfirm);
        
        //音乐播放
        regEvent(event_type_play_music, playMusic);
        
        $feedList.click(eventDispatch);

		counterAdd();
    };
    xwb.notifyChecker = notifyChecker;

	 if (!window.XWEIBO) {
		window.XWEIBO = {};
     }
    
    /*
     
     log(XWEIBO);
     
     linkRender();
     
     var $feedList = $('#feed-list');
     
     //捕捉列表区的所有点击事件
     $feedList.click(eventDispatch);
     
     publisher.init($('#publish_box'), $feedList);
     
     setTimeout(function(){
     notifyChecker.start(XWEIBO.maxid);
     }, 3000);
     });
     */
    $(document).ready(function() {
        $('.logo img').first().fixPng();
    });
 
})(jQuery);



