function log() {
	if (typeof console != 'undefined') {
		if (console.debug) {
			console.debug(arguments);
		}
		else {
			(console.log(typeof JSON != 'undefined' ? JSON.stringify([].slice.call(arguments, 0)) : arguments));
		}
	}
}

(function(){
		
	var 
    UNDEFINED,
	
	NULL = null,
	
	TRUE = true,
	
	FALSE = false,
	
	window = this,
	
    slice = Array.prototype.slice,
	
    toString = Object.prototype.toString,
	
	toInt = parseInt,
	isIE6 = !!($.browser.msie && $.browser.version == '6.0'),
	isArray = $.isArray,    
    isFn = $.isFunction;
	
	window.XWB = {
		extend: extend,
		flash: getFlashObject,
		url: buildModulePath,
		alert: alertMsg,
		escape: htmlspecialchars,
		confirm: confirmBox,
		apiCall: apiCall,
		attention: attention
	};
	
	var xwb = XWB;
	
	/**
	 * 过滤 < > 
	 * @param {String} html
	 */
	function htmlspecialchars(html) {
		return (typeof html == 'string') ? html.replace(/</g, '&lt;').replace(/>/g, '&gt;'): '';
	}
	
	/**
	 * API统一调用处
	 * @param {Object} module 模块名称
	 * @param {Object} params 参数,与$.ajax一致
	 */
	function apiCall(module, params) {
		params = $.extend({
			url: buildModulePath('action', module),
			dataType: 'json',
			type: 'post'
		}, params);
		
		var callback = params.success;
		
		params.success = function(ret){

			if (ret && (parseInt(ret.errno) == 20017)) {
				alertMsg({
					title: '提示：',
					msg: 'api调用次数超出限制了，请稍候后试...',
					timeout: 2
				});
			} else {
				callback && callback(ret);
			}
		}
		
		$.ajax(params);
	}

	/**
	* 扩展
	* @return {Function|Object} 返回扩展后的子对象
	* @param {Function|Object} c 子对象
	* @param {Function|Object} p 父对象
	*/
	function extend(c, p) {
	    var
	        _cType = toString.call(c).replace(/(?:^.* )|\]/g,''),
	        _pType = toString.call(p).replace(/(?:^.* )|\]/g,''),
	        _cache;
	        
	    if(_cType === 'Object') {
	        if(_pType === 'Function') {
	            p = new p();
	        }
	        for(var attr in p) {
	            c[attr] || (c[attr] = p[attr]);
	        }
	    }else if(_cType === 'Function') {
	        _cache = c.prototype;
	        if(_pType === 'Function') {
	            c.prototype = new p();
	        }else {
	            for(var attr in p) {
	                c.prototype[attr] || (c.prototype[attr] = p[attr]);
	            }   
	        }
	        for(var attr in _cache) {
	            c.prototype[attr] = _cache[attr];
	        }
	        
	        c.prototype.constructor = c;
	    }
	    
	    _cType = _pType = _cache = null;
	    
	    return c;
	};
	
	/**
	* 模块管理对象
	*/    
	var modMgr = {
	    /**
	    * 模块缓存
	    */
	    mod: {},
	    /**
	    * 实例缓存
	    */
	    instances: {},
	    /**
	    * 注册模块
	    * @param {String} name 模块名称
	    * @param {Funtion|Object} ctor 模块构造器或者对象
	    * 可带参数，用于produce方法，模块实例初始化时传入
	    */
	    regist: function(name, ctor /*arguments*/) {
	        if(this.mod[name] === UNDEFINED) {
	            this.mod[name] = {};
	        }
	        
	        this.mod[name].ctor = ctor;
	        this.mod[name].args = slice.call(arguments, 2);
	    },
	    
	    /**
	    * 模块产生
	    * @return {Object} 模块实例或副本
	    * @param {String} name 格式: '模块名称|模块别名' 
	                    模块名和别名用'|'分隔，用于区分同个模块不同实例
	    * 可带参数，这里参数的优先级高于注册时的参数
	    */
	    produce: function(name /*arguments*/) {
	        var _name = name.split('|');
	        var aname = _name[1];
	        name = _name[0];
	        _name = NULL;
	        
	        if(!this.mod[name]) {return ;}
	        
	        var newObj, _args = slice.call(arguments, 1);
	        
	        if(_args.length === 0) {
	            _args = this.mod[name].args;
	        }
	        
	        if(isFn(this.mod[name].ctor)) {
	            newObj = new this.mod[name].ctor();
	        }else {
	            newObj = this.mod[name].ctor;
	        }
	        
	        aname = aname || name;
	        if(this.instances[aname]) {
	            extend(this.instances[aname], newObj);
	        }else {
	            this.instances[aname] = newObj;
	        }        
	        
	        newObj.init && newObj.init.apply(newObj, _args);
	        
	        _args = NULL;
	        
	        return newObj;
	    },
	    
	    /**
	    * 模块销毁
	    * @param {String} name 模块名称
	    */
	    remove: function(name) {
	        if(this.mod[name]) {
	            
	            this.mod[name].destroy && this.mod[name].destroy();
	            
	            this.mod[name] = NULL;
	            delete this.mod[name];
	        }
	    },
	    
	    /**
	    * 调用模块实例的方法
	    * @return 模块实例的方法的返回值
	    * @param {String} name 模块别名
	    * @param {String} fn 模块方法名
	    */
	    notify: function(name, fn /*arguments*/) {
	        var returnValue, _obj = this.instances[name];
	        
	        if(_obj && _obj[fn]) {
	            var _args = slice.call(arguments, 2);
	            
	            returnValue = _obj[fn].apply(_obj, _args);
	            
	            _args = NULL;
	        }
	        
	        _obj = NULL;
	        
	        return returnValue;
	    }
	};
	
	/**
	* 事件管理对象
	*/   
	var eventMgr = {
	    /**
	    * 事件缓存
	    */  
	    cache: {},
	    
	    /**
	    * 事件注册
	    */   
	    add: function(name, fn) {
	        if(this.cache[name]) {
	            this.cache[name].push(fn);
	        }else {
	            this.cache[name] = [fn];
	        }       
	    },
	    
	    /**
	    * 删除事件
	    */   
	    remove: function(name, fn) {
	        if(!this.cache) {return;}
	
	        if(fn === UNDEFINED){
	        
	            this.cache[name] = NULL;
	            delete this.cache[name];
	            
	        }else {
	        
	            for(var i=0,l=this.cache[name].length;i<l;i++) {
	                if(this.cache[name][i] == fn){
	                    this.cache[name].splice(i,1);
	                    break;
	                }
	            }
	            
	        }
	    },
	    
	    /**
	    * 事件通知
	    */   
	    broadcast: function(name) {
	        if(this.cache[name]) {
				var args = slice.call(arguments, 1);
	            for(var i=0,l=this.cache[name].length;i<l;i++) {
	                this.cache[name][i].apply(NULL, args);
	            }
	        }
	    }
	};
	
	xwb.eventMgr = eventMgr;
	
	/**
	 * 所有UI组件都继承于uiComponent
	 */
	var uiComponent = function() {
	    this.cid = 'uiComponent'; //组件的类型ID
	    this.element = NULL; //组件的DOM
	};
	
	uiComponent.prototype = {
	    init: function(data, callback, scope) {
	        if(isFn(callback)) {
	            callback.call(scope || this, this);
	        }
	    },
	    config: function(option) {
	        $.extend(this, option);
	    },
	    show: function() {
	        $(this.element).show();
	    },
	    hide: function() {
	        $(this.element).hide();
	    },
	    remove: function() {
	        $(this.element).remove();
	        this.element = NULL;
	    }
	};
    
	/**
	* 栏目内容交替
	*/
    var columnReplace = function() {
        this.cid = 'columnReplace';
        this.duration = 500;
        this.delay = 10000;
        this.first = NULL;
        this.next = NULL;
        this.stop = FALSE;
        this.replaceCallback = NULL;
    };
    columnReplace.prototype = (function() {
        var interval;
        
        return {
            init: function(data) {
                this.element = data.el;            
                $(this.element).css('position', 'relative');
                
                this.stop || this.animate();
            },
            
            replace: function() {
                var cr = this;
                this.next.show();
                
                this.first.animate({'opacity': 0}, {'duration':this.duration});
                
                this.next.animate({'opacity':1}, {
                    'duration': this.duration, 
                    'complete': function() {
                        cr.next.css({
                            'position': '',
                            'top': '',
                            'left': ''
                        });
                        
                        $(cr.element).append(cr.first);
                        
                        cr.replaceCallback(cr.first, cr.next);
                        
                        cr.stop || cr.animate();
                    }
                });
            },
            
            animate: function() {
                this.first = $(this.element).children().eq(0);
                this.next = this.first.next();
                
                if(!this.first[0] || !this.next[0]) {return;}
                
                this.next.css({
                    'opacity': 0,
                    'position': 'absolute',
                    'top': 0,
                    'left': 0
                });
                
                if(interval) {
                    this.stopAnimate();
                }
                
                interval = setTimeout((function(cr) {
                    return function() {
                        cr.replace();
                    }
                })(this), this.delay);
            },
            
            stopAnimate: function() {
                clearTimeout(interval);
                interval = NULL;
            }
        };
    })();
    extend(columnReplace, uiComponent);
    
	/**
	* 图片左右移动
	*/
    var photoViewer = function() {
        this.cid = 'photoViewer';
        this.lBtn = NULL;
        this.rBtn = NULL;
        this.itemWidth = 150; //每个子区块的宽度
        this.pages = 0; //总页数
        this.curPage = 1; //当前页码
        this.count = 3; //每页个数
        this.total = 0; //总数
        this.delay = 10; //延迟时间，值越大滚动速度越慢
        this.speed = 25; //滚动速度，值越大单次移动距离越大
    };
    photoViewer.prototype = (function() {
        var interval;
        
        return {
            init: function(data) {
                this.element = data.el;
                this.lBtn = data.lBtn;
                this.rBtn = data.rBtn;
                
                lineUp.call(this, this.itemWidth);
                
                eventBind.call(this);
                
                this.element.scrollLeft = 0;
            },
            
            roll: function(dir) {
                if(interval) {return;}
                
                if(dir === 'left') {
                    if(this.curPage == this.pages) {return;}
                    this.curPage++;
                }else {
                    if(this.curPage == 1) {return;}
                    this.curPage --;
                }
                
                if(this.curPage == 1) {
                    this.rBtn.show();
                    this.lBtn.hide();
                }else if(this.curPage >= this.pages) {
                    this.rBtn.hide();
                    this.lBtn.show();
                }else {
                    this.rBtn.show();
                    this.lBtn.show();
                }
                
                var pv = this;

                interval = setInterval(function() {
                    var limit, sl = pv.element.scrollLeft;
                    if(dir === 'left') {
                        limit = (pv.curPage-1) * pv.itemWidth * pv.count;
                        if(sl < limit) {
                            pv.element.scrollLeft = sl+pv.speed;
                        }else {
                            clearInterval(interval);
                            pv.element.scrollLeft = limit;
                            interval = NULL;
                        }
                    }else {
                        limit = (pv.curPage-1) * pv.itemWidth * pv.count;
                        if(sl > limit) {
                            pv.element.scrollLeft = sl-pv.speed;
                        }else {
                            clearInterval(interval);
                            pv.element.scrollLeft = limit;
                            interval = NULL;
                        }     
                    }                    
                }, this.delay);
            }        
        
        }
        
        function lineUp(baseNum) {
            var $items = $(this.element).children();
            this.total = $items.length;                
            this.pages = Math.ceil(this.total/this.count);
            
            $.each($items, function(i, item) {
                $(item).css({
                    'left': baseNum * i
                });
            });
            
            var mod = this.total%this.count;

            if(mod) {
                $($items[this.total-1]).width((3-mod+1)*this.itemWidth);
            }
            
            if(this.total <= this.count) {
                this.rBtn.hide();
            }
            
            this.lBtn.hide();
        }
        
        function eventBind() {
            var obj = this;
            $(this.rBtn).bind('click', function() {
                obj.roll('left');
            });
            $(this.lBtn).bind('click', function() {
                obj.roll('right');
            });
        }
    })();
    extend(photoViewer, uiComponent);
	
	/**
	 * 图片控制组件
	 */
	var imgCtrler = function() {
	    this.cid = 'imageCtrler';
	    this.canvas = NULL;
	    this.maxWidth = 440;
	    this.width = 0;
	    this.height = 0;
	    this.curAngle = 0;
	};
	imgCtrler.prototype = {
	    /**
	    * 初始化
	    * 支持canvas的创建canvas，IE使用矩阵滤镜
	    */
	    init: function(data) {
	        var _el = data.el;
	        
	        this.width = _el.offsetWidth;
	        this.height = _el.offsetHeight;
	        
	        if($.browser.msie) {
	            var _matrix = 'DXImageTransform.Microsoft.Matrix';
	            
	            _el.style.filter = 'progid:DXImageTransform.Microsoft.Matrix()';
	            _el.filters.item(_matrix).SizingMethod = "auto expand";
	            $(_el).addClass('narrow-move');
	            _matrix = NULL;
	        }else {
	            this.canvas = $('<canvas></canvas>')
	                .attr({
	                    'height': this.height,
	                    'width': this.width
	                })
					.addClass('narrow-move')
	                .insertBefore(_el)[0];
	            
	            if(this.canvas.getContext) {
	                $(_el).hide();
	                
	                var ctx = this.canvas.getContext('2d');
	                
	                //ctx.drawImage(_el,0,0);
	
	            }
	        }
	        
	        this.element = _el;
	    },
	    
	    /**
	    * 旋转图片
	    *@param {String} dir  旋转方式，'left'或者'right'
	    */
	    rotate: function(dir) {
	        if(!this.element) {return;}
	        
	        //相对原始图片的旋转角度
	        var _angle;
	        if(dir === 'right') {
	            _angle = this.curAngle + 90;
	            this.curAngle = _angle>=360 ? 0 : _angle;
	        }else if(dir === 'left') {
	            _angle = this.curAngle - 90;
	            this.curAngle = _angle<0 ? 360+_angle : _angle;
	        }
	        _angle = NULL;
	        
	        //调整图片旋转后的大小
	        var drawW,drawH, h=this.width,w=this.height;
	            
	        this.width = w;
	        this.height = h;
	
	        if(w > this.maxWidth) {
	            h = toInt(this.maxWidth * h/w);
	            w = this.maxWidth;
	        }
	        
	        if(this.canvas) {
	            var 
	                ctx = this.canvas.getContext('2d'), el = this.element, 
	                cpx=0, cpy=0;
	            //设置画布大小，重置了内容
	            $(this.canvas).attr({
	                'width': w,
	                'height': h
	            });
	            
	            ctx.clearRect(0,0,w,h);
	            
	            switch(this.curAngle) {
	                case 0:
	                    cpx = 0;
	                    cpy = 0;
	                    drawW = w;
	                    drawH = h;
	                    break;
	                case 90:
	                    cpx = w;
	                    cpy = 0;
	                    drawW = h;
	                    drawH = w;
	                    break;
	                case 180:
	                    cpx = w;
	                    cpy = h;
	                    drawW = w;
	                    drawH = h;
	                    break;
	                case 270:
	                    cpx = 0;
	                    cpy = h;
	                    drawW = h;
	                    drawH = w;
	                    break;
	            }
	            
	            ctx.save();
	            ctx.translate(cpx,cpy);
	            ctx.rotate(this.curAngle * Math.PI/180);
	            ctx.drawImage(el, 0, 0, drawW,drawH);
	            ctx.restore();
	            
	        }else {
	            var 
	                _rad = this.curAngle * Math.PI/180,
	                _cos = Math.cos(_rad),
	                _sin = Math.sin(_rad),
	                _el = this.element,
	                _matrix = 'DXImageTransform.Microsoft.Matrix';
	                
	            _el.filters.item(_matrix).M11 = _cos;
	            _el.filters.item(_matrix).M12 = -_sin;
	            _el.filters.item(_matrix).M21 = _sin;
	            _el.filters.item(_matrix).M22 = _cos;
	            
	            // this.width = _el.offsetWidth;
	            // this.height = _el.offsetHeight;
	            
	            switch(this.curAngle) {
	                case 0:
	                case 180:
	                    drawW = w;
	                    drawH = h;
	                    break;
	                case 90:
	                case 270:
	                    drawW = h;
	                    drawH = w;
	                    break;
	            }
	            
	            _el.width = drawW;
	            _el.height = drawH;
	            //修正IE8下图片占位的问题
	            //18是操作菜单的高度
	            if($.browser.version == 8) {
	                _el.parentNode.style.height = _el.offsetHeight+18;
	            }
	        }
	    }
	};
	extend(imgCtrler, uiComponent);
	
	/**
	 * 浮层组件
	 */
	 var layer = function() {
	    this.cid = "layer";
	    this.rel = NULL;
	    this.ox = 0;
	    this.oy = 0;
	    this.showCallback = NULL;
	    this.closeCallback = NULL;
	 };
	 layer.prototype = {
	    init: function(data) {
	        this.element = data.el;
	        this.rel = data.rel || document.body;
	        
	        $(this.element).css({
	            'position': 'absolute',
	            'z-index': ++$.layerIndex
	        });
	    },
	    
	    show: function() {
	        $(this.element).show().css('z-index', ++$.layerIndex);
	        this.resize();
	        this.setCommonEvent();
	        isFn(this.showCallback) && this.showCallback(this);

	    },
	    
	    close: function() {
	        $(this.element).hide();       
	        isFn(this.closeCallback) && this.closeCallback(this);
	    },
	    
	    resize: function() {
	        var 
	            offset = $(this.rel).offset(),
	            ox = offset.left + this.ox,
	            oy = offset.top + this.oy;
	    
	        $(this.element).css({
	            'top': oy,
	            'left': ox
	        });
	    },
	    
	     /**
	     * 设置组件公有事件
	     */
	    setCommonEvent: function() {
	        $(document.body).one('click', this, function(e) {
	            var obj = e.data;
	            if(obj.element != e.target && !$.contains(obj.element, e.target)) {
	                obj.hide();
	            }else {
	                obj.element.offsetHeight && obj.setCommonEvent();
	            }
	        });
            
	        
	        $(window).bind('resize', (function(obj) {
	            return function() {obj.resize()};
	        })(this));
	    }
	    
	 };
	 extend(layer, uiComponent);
	 
	 /**
	 * 窗口组件
	 * 继承自浮层组件
	 */
	 var xwin = function() {
	    this.cid = "xwin";
	    this.isShowBg = TRUE; //是否显示背景
	    this.bg = NULL //显示对应DOM
	 };
	 xwin.prototype = {
	    init: function(data) {
	        this.element = data.el;
	        
	        $(this.element).css({
            //'position': 'absolute',
	            'z-index': ++$.layerIndex
	        });
            
            $(window).resize(function(obj) {
                return function() {
                    obj.resize();
                }
            }(this));
            
	    },
	    
	    show: function() {
	        this.isShowBg &&  this.showBg();
	        
	        $(this.element).show();
	        
	        this.resize();
	        
	        isFn(this.showCallback) && this.showCallback(this);
	    },
		
		remove: function(){
			this.close();
			this.bg && $(this.bg).remove();
		},
	    
	    close: function() {
	        $(this.element).hide();
	        
	        if(this.isShowBg) {
                $(this.bg).hide();
                $('#xwinIframe').hide();
            }
	        
	        isFn(this.closeCallback) && this.closeCallback(this);
	    },
	    
	    showBg: function() {
	
	        if(!this.bg) {
	            this.bg = $('<div></div>')
	                .addClass('shade-div')
	                .css({
	                    //'position': 'absolute',
	                    'z-index': 10000
	                })
	                .appendTo($(document.body))[0];
                    
                if(isIE6 && !$('#xwinIframe')[0]) {
                    $('<iframe></iframe>')
                        .attr({'id':'xwinIframe', 'frameborder': 0})
                        .addClass('shade-div shade-iframe')
                        .css({
                            //'position': 'absolute',
                            'z-index': 9999
                        })
                        .appendTo($(document.body));
                }
	        }
	        
	        $(this.bg).show();
            $('#xwinIframe').show();
	    },
	    
	    resize: function() {
	        //var 
	            //$w = $(window),
	            //$d = $(document);
            
            //这里会引起某些IE浏览器透明度滤镜失效 超过4096px ati显卡
            var wholeHeight = parseInt(document.documentElement.clientHeight);            
            if(this.bg){
                //this.bg.style.height = wholeHeight+"px"
                $(this.bg).height(wholeHeight);
                $('#xwinIframe').height(wholeHeight);
            };
            
	        // $(this.element).css({
	            // 'top': ($w.height() - this.element.offsetHeight)/2,
	            // 'left': ($w.width() - this.element.offsetWidth)/2
	        // });
	    }
	 };
	extend(xwin, layer);
	 
	/**
	 * 表情浮层组件
	 * 继承自浮层组件
	 */
	 var emotion = function() {
	    this.cid = 'emotion';
	    this.input = NULL;
	    this.ctn = NULL;
	    this.eList = NULL;
	 };
     
	 emotion.prototype = {
	    init: function(data) {
	        this.element = data.el;
	        this.rel = data.rel || document.body;
	        this.ctn = data.emotionArea || this.element;
	        
	        $(this.element).css({
	            'position': 'absolute',
	            'z-index': ++$.layerIndex
	        });
	        
	        $(this.ctn).bind('click', this, function(e) {
	            var obj = e.data;
	            var num = NULL;
	            $(this).children().each(function(i, item) {
	                if(item == e.target || $.contains(item, e.target)) {
	                    num = i;   
	                    
	                    obj.hide();
	                    
	                    return FALSE;
	                }
	            });
	            (num == NULL) || obj.insert(num);
	        });
	    },
	    
	    insert: function(num) {
	        var text = this.eList[num];
	        text && this.input && $(this.input).insertText('['+text+']');
            $(this.input).focus();
            
            this.insertCallback && this.insertCallback(this.input);
	    }
	 };
	 extend(emotion, layer);
	 
	 /**
	 * 拖动组件
	 */
	 var drag = function() {
	    this.cid = 'drag';
	    this.posX = 0;
	    this.posY = 0;
	    this.allowX = TRUE;
	    this.allowY = TRUE;
	    this.dragArea = NULL;
	    this.startDrag = FALSE;
	    this.onDrag = NULL;
	    this.onDragEnd = NULL;
	 };
	 drag.prototype = (function() {    
	    return {
	        init: function(data) {
	            this.element = data.el;
	            this.dragArea = data.dragArea || this.element;
	            
	            var offset = $(this.element).offset();
	            
	            $(this.element).css({
	                'position': 'absolute',
	                'z-index': ++$.layerIndex,
	                'top': offset.top,
	                'left': offset.left
	            }).appendTo($(document.body));
	            
	            $(this.dragArea).bind('mousedown', this, function(e) {
	                var drag = e.data;
	
	                drag.startDrag = TRUE;
	                
	                drag.posX = e.pageX;
	                drag.posY = e.pageY;
	                
	                document.body.style.MozUserSelect = 'none';
	                $.browser.msie && $(document.body).bind('selectstart', function(e) {e.preventDefault()});
	                
	                $(document.body)
	                    .bind('mousemove', drag, dragOn)
	                    .bind('mouseup', drag, dragOff);
	                
	                e.preventDefault();
	                
	            });
	     
	        }
	    }
	    
	    function dragOn(e) {
	        var el, drag = e.data;
	        
	        if(!drag.startDrag) {return;}
	        
	        el = drag.element;
	        
	        var
	            _x = e.pageX - drag.posX,
	            _y = e.pageY - drag.posY;
	        
	        drag.allowY && (el.style.top = toInt(el.style.top) + _y + 'px');
	        drag.allowX && (el.style.left = toInt(el.style.left) + _x + 'px');
	        
	        drag.posX = e.pageX;
	        drag.posY = e.pageY;
	        
	        drag.onDrag && drag.onDrag(drag);
	    }
	    
	    function dragOff(e) {
	        var drag = e.data;
	        
	        drag.startDrag = FALSE;
	        
	        $(document.body)
	            .unbind('mousemove', dragOn)
	            .unbind('mouseup', dragOff);
	        
	        setTimeout(function() {document.body.style.MozUserSelect = '';}, 0);
	        $.browser.msie && $(document.body).unbind('selectstart');
	        
	        drag.onDragEnd && drag.onDragEnd(drag);
	    }
	 })();
	 extend(drag, uiComponent);
	 
	$.extend({
	    'modMgr': modMgr,
	    'eventMgr': eventMgr,
        'prefix': {
            'imgCtrler': 'xweibo_img_',
            'layer': 'xweibo_layer_',
            'drag': 'xweibo_drag_',
            'xwin': 'xweibo_win_',
            'emotion': 'xweibo_emo_',
            'photoViewer': 'xweibo_pv_',
            'columnReplace': 'xweibo_cr_'
        },
	    'uicid': 0,
        'layerIndex': 10000,
	
	    /**
	    * 获取指定组件的实例
	    */
	    getInstance: function(type, config) {
	        var
	            obj,
	            el = config.el,
	            instances = $.modMgr.instances,
	            prefix = $.prefix[type];
	         
	        if(el.id && instances[prefix+el.id]) {
	            obj = instances[prefix+el.id];
	        }else {
	            el.id || (el.id = prefix+ ++$.uicid);                
	            obj =  $.modMgr.produce(type+'|'+prefix+el.id, config);
	        }
	        
	        return obj;
	    },
	
	    /**
	    *   1.	1小时内产生的信息   
	            小于1分钟：**秒前
	            大于1分钟小于1小时：**分钟前   取整，舍去秒数
	        2.	当日00:00后产生的信息，发送时间已超过1小时前，包括1小时整，
	            时间显示 今天**：**
	        3.	当年内产生的信息，时间显示 **月**日 **：**
	        4.	本年度前产生的信息，时间显示 ****年**月**日 **：**
	    */
	    formatDate: function(date) {
	        var str = '未知时间';
	        if(date instanceof Date) {
	            var di = Math.ceil((new Date() - date)/1000);
	
	            if(di<60) { 
	                str = di+'秒前';
	                
	            }else if(di<3600) {            
	                str = Math.floor(di/60)+'分钟前';
	                
	            }else if(di<24*3600 && date.getDate() == new Date().getDate()) {            
	                str = '今天 '+date.getHours()+':'+date.getMinutes();
	                
	            }else if(date.getFullYear() == new Date().getFullYear()) {            
	                str = (date.getMonth()+1)+'月'+date.getDate()+'日 '+date.getHours()+':'+date.getMinutes();
	            
	            }else {
	                str = date.getFullYear()+'年'+(date.getMonth()+1)+'月'+date.getDate()+'日 '+date.getHours()+':'+date.getMinutes();
	            }            
	        }
	        
	        return str;
	    }
	});
	
	//组件注册
	modMgr.regist('imgCtrler', imgCtrler);
	modMgr.regist('layer', layer);
	modMgr.regist('xwin', xwin);
	modMgr.regist('drag', drag);
	modMgr.regist('emotion', emotion);
	modMgr.regist('photoViewer', photoViewer);
    modMgr.regist('columnReplace', columnReplace);
	
	//扩展至jQuery
	$.extend($.fn, {
	    /**
	    * 图片旋转
	    * @return {Object} jQuery对象
	    *@param {String} dir  旋转方式，'left'或者'right'
	    */
	    imgRotate: function(dir) {
	       
	        this.each(function() {
	            if(this.tagName !== 'IMG') {return FALSE};
	            var img;
	            
	            img = $.getInstance('imgCtrler', {'el':this});
	            
	            img.rotate(dir);
	        });
	        
	        return this;
	    },
	        
	    /**
	    * 形成浮层对象
	    *@return {Object} layer实例对象
	    */
	    toLayer: function() {
	
	        var layer;
	        
	        this.each(function() {           
	            
	            layer = $.getInstance('layer', {'el':this});
	
	        });
	        
	        return layer;
	    },
	    
	    /**
	    * 形成窗口对象
	    *@return {Object} xwin实例对象
	    */
	    toXwin: function() {
	
	        var xwin;
	        
	        this.each(function() {           
	            
	            xwin = $.getInstance('xwin', {'el':this});
	
	        });
	        
	        return xwin;
	    },
	    
	    /**
	    * 形成拖动对象
	    *@return {Object} drag实例对象
	    *@param {Object} opt  拖动组件配置对象
	        opt.dragArea 设置拖动的触发对象
	    */
	    toDrag: function(opt) {
	
	        var drag;
	        
	        this.each(function() {           
	            
	            drag = $.getInstance('drag', {'el':this, 'dragArea': opt.dragArea});
	
	        });
	        
	        return drag;
	    },
	    
	    /**
	    * 形成表情浮层对象
	    *@return {Object} emotion实例对象
	    *@param {Object} opt  表情组件配置对象
	        opt.emotionArea 设置表情列表的容器
	    */
	    toEmotion: function(opt) {
	
	        var emo;
	        
	        this.each(function() {
	            
	            emo = $.getInstance('emotion', {'el':this, 'emotionArea': opt.emotionArea});
	
	        });
	        
	        return emo;
	    },
	    
	    /**
	    * 形成图片滑动对象
	    *@return {Object} emotion实例对象
	    *@param {Object} opt  图片滑动组件配置对象
	        opt.lBtn 配置向左滚动按钮
            opt.rBtn 配置向右滚动按钮
	    */
	    toPhotoViewer: function(opt) {
	
	        var pv;
	        
	        this.each(function() {
	            
	            pv = $.getInstance('photoViewer', {'el':this, 'lBtn': opt.lBtn, 'rBtn': opt.rBtn});
	
	        });
	        
	        return pv;
	    },
        
	    toColReplace: function() {
	
	        var cr;
	        
	        this.each(function() {
	            
	            cr = $.getInstance('columnReplace', {'el':this});
	
	        });
	        
	        return cr;
	    },
        
	    /**
	    * 插入文字到光标处
	    *@return {Object} jQuery对象
	    *@param {String} text  要插入的文字
	    */
	    insertText: function(text) {
	        this.each(function() {
	            if(this.tagName !== 'INPUT' && this.tagName !== 'TEXTAREA') {return;}
	            if (document.selection) {
	                this.focus();
	                var cr = document.selection.createRange();
	                cr.text = text;
                    cr.collapse();
                    cr.select();
	            }else if (this.selectionStart || this.selectionStart == '0') {
	                var 
	                    start = this.selectionStart,
	                    end = this.selectionEnd;
	                this.value = this.value.substring(0, start)+ text+ this.value.substring(end, this.value.length);
                    
                    this.selectionStart = this.selectionEnd = start+text.length;
                    
	            }else {
	                this.value += text;
	            }
	        });        
	        return this;
	    },
	    
	    /**
	    * 检查输入的字数
	    *@return {Number}  返回剩余的字数
	    *@param {Number} limit  限制字数
	    */
	    checkText: function(limit) {
	        var limit = limit || 140;
	        var last = limit;
	        
	        this.each(function() {
	            var text = '', cLen=0;
	            if(this.tagName == 'INPUT' || this.tagName == 'TEXTAREA') {
	                text = $.trim(this.value);
	            }else {
	                text = $.trim($(this).text());
	            }
	            
	            try{
	                cLen  = text.match(/[^\x00-\xff]/g).length;
	            }catch(err){}
                
	            last = Math.floor((limit*2 - text.length - cLen)/2);
	        });    
	        
	        return last;
	    },
        
	    /**
	    * 焦点聚到指定位置
	    *@return jQuery
	    *@param {Number} num  位置，默认末尾
	    */
        focusEnd: function(num) {
	        this.each(function() {
                try{
                    this.focus();
                }catch(err){
                    return;
                }
                var end = num == UNDEFINED ? this.value.length : num;
                if(document.selection) {
                    var cr = this.createTextRange();
                    cr.collapse();
                    cr.moveStart('character', end);
                    cr.moveEnd('character', end);
                    cr.select();
                }else  {
                    this.selectionStart = this.selectionEnd = end;
                }
	        });
            
            return this;
        },
        
	    /**
	    * 按宽度，截取字符
	    *@return jQuery
	    *@param {Number} limitWidth  宽度
	    */
        substrByWidth: function(limitWidth) {
            if(!limitWidth) {return ;}
            
            this.each(function() {
                var overflow = FALSE;
                while(parseInt(this.offsetWidth) > limitWidth) {
                    overflow = TRUE;                    
                    var text = $(this).text();
                    if(text.length == 0) {
                        break;
                    }
                    $(this).text(text.substr(0, text.length-1));
                }
                
                if(overflow) {
                    text = $(this).text();
                    $(this).text(text.replace(/.{3}$/,'...'));
                }
            });
            
            return this;
        },
        
	    /**
	    * 截取微博内容
	    *@return jQuery
	    *@param {Number} num  位置，默认10
        *@param {Boolean} hasFace  是否显示表情图片，否为文字代替
        *@param {String} postfix  后缀
	    */
        substrText: function(num, hasFace, postfix) {
            var re = new RegExp('(?:<a.*?>.*?<\\/a>)|(?:<img.*?>)|.','gi');
            
	        this.each(function() {
                var 
                    cache = [],
                    postfix = postfix || '...',
                    text = this.innerHTML,
                    match = text.match(re);
                    
                num = num||10;
                    
                if(match && match.length > num) {
                    
                    match = match.slice(0, num).join('');

                    text = hasFace ? match : match.replace(/<img.*?title=\"(.*?)\".*?>/gi, '[$1]');
                    
                    $(this).html(text+postfix);
                }
	        });
            
            return this;
        },
        
	    /**
	    * 文字放大渐隐（微博数增加效果）
	    *@return jQuery
        *@param {Number} num 增加数值
	    *@param {Number} times 放大倍数
	    */
        zoomText: function(num, times) {
            this.each(function() {
                var
                    $clone,
                    $el = $(this),
                    offset = $el.offset(),
                    text = $el.text();
                    
                times = isNaN(times) ? 2 : times;
                
                if(!isNaN(+text)) {
                    text = +text + (num || 1);
                }
                
                $el.text(text);
                
                $clone = $el.clone()
                    .attr('id', '')
                    .css({
                        'position': 'absolute',
                        'top': offset.top,
                        'left': offset.left,
                        'font': $el.css('font'),
                        'color': $el.css('color')
                    })
                    .appendTo($(document.body));
                
                var fontsize = times * parseInt($el.css('font-size'));
                
                $clone.animate({
                    'font-size': fontsize,
                    'top': offset.top - ($el.height()/4),
                    'left': offset.left - ($el.width()/2),
                    'opacity': 0.1
                }, {
                    'duration': 300,
                    'complete': function() {
                        $clone.remove();
                    }
                });
                
            });
            
            return this;
        },
        
	    /**
	    * IE6修复PNG图片
	    *@return jQuery
	    */
        fixPng: function() {
            if(isIE6) {
                this.each(function() {
                    if(this.tagName == 'IMG') {
                        var $img = $('<span></span>').css({
                            width: this.offsetWidth,
                            height: this.offsetHeight,
                            display: 'inline-block'
                        });
                        $img[0].style.filter = 'progid:DXImageTransform.Microsoft.AlphaImageLoader(src="'+this.src+'", sizingMethod="scale")';                        
                        $(this).replaceWith($img);
                    }
                });
            }
            
            return this;
        },
        
	    /**
	    * 把目标节点移至浏览器可视区域
	    *@return jQuery
	    */
        moveToView: function(offsetTop) {
            offsetTop = isNaN(offsetTop) ? 80 : offsetTop;

            this.each(function() {
                var top = $(this).offset().top;
                document.body.scrollTop = document.documentElement.scrollTop = top - offsetTop;
                
            });
            
            return this;
        },
        
	    /**
	    * 判断目标节点是否在浏览器可视区域内
	    *@return jQuery
	    */
        isInView: function() {
            var result = TRUE;
            
            this.each(function() {               
                var 
                    top = $(this).offset().top,
                    st = $(document).scrollTop(),
                    tooHigh = top<st,
                    tooLow = top+$(this).height() > st+$(window).height();
                
                if(tooHigh || tooLow) {
                    result = FALSE;
                    return FALSE;
                }
            });
            
            return result;
        },
        
        tagUp : function(tagName, filter){
          var nd;
          this.each(function(){
            var p = $(this).parent();
            while(p.length){
              if(p.get(0).tagName === tagName && (!filter || filter(p))){
                nd = p;
                return false;
              }
              p = p.parent();
            }
          });
          return nd;
        }
	});

/**
 * 计算字符串长度，一个宽字符当两个字符
 * @param {String} text
 */
function asciiLen(text){
	if (text) {
		var matchs = text.match(/[\u4e00-\u9fa5]/g);
		
		var len = text.length;
		
		return len + (matchs ? matchs.length: 0);
	}
	
	return 0;
}
    
xwb.layerMgr = (function() {

    return {
        layers: {
            'default': {}
        },
        
        showLayer: function(id, group) {
            var layer = this.get(id, group);
            
            if(!layer) {return;}
            
            var layers = this.layers[layer['group']];
            
            for(var i in layers) {
                layers[i].close();
            }
            
            layer.show();
        },

        addLayer: function(option) {
            var 
                $layer, layer, isNew,
                layers = this.layers,
                type = option.type,
                id = option.layerid||'',
                group = option.group||'default',
                html = option.content,
                config = option.config;
            
            if(!layers[group]) {
                layers[group] = {};
                isNew = TRUE;
            }else if(!layers[group][id]) {
                isNew = TRUE
            }else {
                layer = layers[group][id];
            }
            
            if(isNew) {
                $layer = this.create(id, group, html);
                
                switch(type) {
                    case 'emotion':
                        $layer.addClass('emotion-window');
                        layer = $layer.toEmotion({
                            'emotionArea': $layer.find('div.emotion-box')[0]
                        });
                        break;
                        
                    case 'music':
                    case 'video':
                        $layer.addClass('insert-window');
                        layer = $layer.toLayer();
                        break;
                }
                
                config && layer.config(config);
                

                $layer.find('a.close-btn').click(function(e) {
                    layer.close();
                    e.preventDefault();
                });
            }
            
            layers[group][id] = layer;
            layer.group = group;
            
            return layer;
        },
        
        get: function(id, group) {
            var layer = NULL, range = this.layers[group] || this.layers;
            
            for(var i in range) {
                if(!group) {
                    layer = this.get(id, i);
                    if(layer) {
                        break;
                    }                    
                }else {
                    layer = this.layers[group][id];
                }
            }
            
            return layer;
        },
        
        create: function(id, group, html) {
            var $layer, $content, isNew = FALSE;

            html = html || '';
            
            $layer = $('<div></div>')
                .attr('id', id)
                .addClass('pop-window')
                .html([
                    '<div class="pop-t"></div>',
                    '<div class="pop-content">'+html+'</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 class="arrow all-bg"></div>',
                    '<a class="close-btn icon-bg" href="javascript:;" title="关闭"></a>'
                ].join(''))
                .appendTo($(document.body));
            
            return $layer;
        },
        
        setContent: function(id, html) {
            var layer = this.get(id);
            if(layer) {
                $(layer.element).find('div.pop-content').html(html);
            }
        }
    };
})();
    
	/**
	 * 
	 * http://flowplayer.org/tools/toolbox/flashembed.html
	 *
	 * Since : March 2008
	 * Date  :    Wed May 19 06:53:17 2010 +0000 
	 * modify by : guolianghu
	 * opts.height 高 （必须）
	 * opts.width 宽 (必须）
	 * opts.id dom-id
	 * opts.name dom-name
	 * opts.src flash地址 （必须）
	 * opts.nocache 禁用cache （可选）
	 * opts.w3c 
	 * 
	 * conf: 配置  （可选）
	 */ 
	function getFlashObject(opts, conf) {
		var IE = $.browser.msie;
	
		opts = opts || {};
		
		/******* OBJECT tag and it's attributes *******/
		var html = '<object width="' + opts.width + 
			'" height="' + opts.height + 
			(opts.id ? '" id="' + opts.id: '') + 
			(opts.name ? '" name="' + opts.name: '') + '"';
		
		if (opts.nocache) {
			opts.src += ((opts.src.indexOf("?") != -1 ? "&" : "?") + Math.random());		
		}
		
		if (opts.w3c || IE) {
			html += ' data="' +opts.src+ '" type="application/x-shockwave-flash"';		
		} else {
			html += ' classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"';	
		}
		
		html += '>'; 
		
		/******* nested PARAM tags *******/
		if (opts.w3c || IE) {
			html += '<param name="movie" value="' +opts.src+ '" />'; 	
		} 
		
		// not allowed params
		opts.width = opts.height = opts.id = opts.w3c = opts.src = null;
		opts.onFail = opts.version = opts.expressInstall = null;
		
		for (var key in opts) {
			if (opts[key]) {
				html += '<param name="'+ key +'" value="'+ opts[key] +'" />';
			}
		}	
	
		/******* FLASHVARS *******/
		var vars = "";
		
		if (conf) {
			for (var k in conf) { 
				if (conf[k]) {
					var val = conf[k]; 
					vars += k +'='+ (/function|object/.test(typeof val) ? f.asString(val) : val) + '&';
				}
			}
			vars = vars.slice(0, -1);
			html += '<param name="flashvars" value=\'' + vars + '\' />';
		}
		
		html += "</object>";	
		
		return html;
	}
	
	function buildModulePath(module, action, querystring) {
		var base = typeof BASE_PATH == 'undefined' ? '': BASE_PATH;
		
		var mode = ROUTE_MODE || 0;
		
		if (mode == 2 || mode == 3) {
			var uri = base + module;
			
			if (action) {
				if (action.indexOf('.') > -1) {
					uri += '/';
				}
				else {
					uri += '.';
				}
				uri += action;
			}
			
			if (querystring) {
				if (uri.indexOf('?') == -1) {
					uri += '?';
				}
				uri += querystring;
			}
			
			return uri;
		}
		else {
			var params = '?m=' + module;
			if (action) {
				params += '.' + action;
			}
			
			if (querystring) {
				params += '&' + querystring;
			}
			
			return base + params; 
		}
	}
	
	/**
	 * 弹出提示框 
	 * @param {Object} param
	 */
	function confirmBox(param, callback) {
		var title = param.title;
		var msg = param.msg;
		
		var html =[ '<div class="pop-window tips-window fixed-window">',
	    	'<div class="pop-t"></div>',
	        '<div class="pop-content">',
	        	'<h4 class="pop-title x-bg"><a class="close-btn icon-bg"  rel="close" href="#"></a>'+title+'</h4>',
	            '<div class="tips-box">',
	            	'<div class="tips-c"><div class="alert-icon all-bg"></div><p>'+msg+'</p></div>',
	                '<div class="btn-area">',
	                    '<a class="general-btn highlight" href="#" rel="enter"><span rel="enter">确定</span></a>',
						'<a class="general-btn" href="#" rel="cancel"><span rel="cancel">取消</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 $msg = $(html);
		
		$msg.appendTo('body');
		
		var win = $msg.toXwin()
		
		win.show();
		
		var close = function() {
			win.remove();
			$msg.remove();
		}
		
		$msg.click(function($e){
			var rel = $($e.target).attr('rel');
			
			switch (rel) {
				case 'cancel':
				case 'close':
					close();
				break;
				
				//确定
				case 'enter':
					close();
					callback && callback();
				break;
			}
			
			$e.preventDefault();
		});
		
		if(param.focus){
		  switch(param.focus){
		    case 'cancel':
		      $msg.find('a[rel=cancel]').focus();
		      break;
		    case 'enter':
		      $msg.find('a[rel=enter]').focus();
		      break;
		  }
		}
	}
	
	/**
	 * 弹出提示信息
	 * @param {Object} info
	 * info.title 显示的标题
	 * info.msg 提示信息
	 * info.timeout 超时时间，单位（秒），超时后自动关闭
	 */
	function alertMsg(info) {
		var title = info.title || "提示";
		var msg = info.msg;
		var timeout = info.timeout;
		var callback = info.callback;
		var type = info.type ? info.type: 'alert';   //error、msg
		
		var html =[ '<div class="pop-window tips-window fixed-window">',
	    	'<div class="pop-t"></div>',
	        '<div class="pop-content">',
	        	'<h4 class="pop-title x-bg"><a class="close-btn icon-bg"  rel="close" href="#"></a>'+title+'</h4>',
	            '<div class="tips-box">',
	            	'<div class="tips-c"><div class="'+type+'-icon all-bg"></div><p>'+msg+'</p></div>',
	                '<div class="btn-area">',
	                    '<a class="general-btn highlight" 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 $msg = $(html);
		
		$msg.appendTo('body');
		
		var win = $msg.toXwin()
		
		win.show();
		
		var closed = FALSE;
		
		var close = function() {
			if (closed) return;
			
			closed = TRUE;
			
			win.remove();
			$msg.remove();
			callback && callback();
		}
		
		$msg.click(function($e){
			var rel = $($e.target).attr('rel');
			
			switch (rel) {
				case 'close':
					close();
				break;
			}
			
			$e.preventDefault();
		})
		
		if (timeout) {
			setTimeout(close, timeout*1000);
		}
	}
	
	/**
	 * 关注某人（可多个）
	 * @param user_ids [Array|String]用户ID
	 * @param int 1/0 1:添加 0:取消
	 */
	function attention(user_ids, type, callback) {
		apiCall(type ? 'createFriendship': 'deleteFriendship', {
			data: {user_id: user_ids},
			success: callback
		});
	}
	
	/**
	 * 文件上传类
	 */
	function FileUploader(file_input) {
		this.state = 0;
		
		var uid = FileUploader.uid++;
		
		this.file = file_input;
		
		this.form = file_input.form;
		
		var formName = 'upload_frame_'+uid;
		
		//生成上传图片需要的iframe
        this.iframe = $('<iframe id="'+formName+'" src="about:blank" name="'+formName+'" style="display:none;"></iframe>').appendTo('body');
        
		this.form.target = formName;
		this.form.action = buildModulePath('action', 'upload_pic');
		
        //添加callback参数
        $('<input type="hidden" name="callback"/>').appendTo(file_input.form);
	}
	
	FileUploader.uid = 0;
	
	FileUploader.prototype = {
		/**
		 * 上传
		 */
		upload: function(callback){
			//生成jsonp回调
	        var ts = (new Date()).getTime();
	        var cb = 'jsonp' + ts;
			
			var uploader = this;
	        
	        window[cb] = function(ret){
				callback(ret);
				
				uploader.state = 0;
	        }
			
			//this.form.elements['callback'].value = 'parent.' + cb;
			var callname = 'parent.' + cb;
			var action = this.form.action;
			if (action.indexOf('callback') > -1) {
				action.replace('callback=[^&]+', callname);
			}
			else {
				action += ((action.indexOf('?') > -1) ? '&callback=': '?callback=') + callname; 
			}
			this.form.action = action;
			
			this.state = 1; //开始上传
			this.form.submit();
			
			return cb;
		},
		
		getStatus: function() {
			return this.state;
		},
		
		cancel: function(cb){
			$.isFunction(window[cb]) && (window[cb] = function(){});
		}
	}
	
	xwb.FileUploader = FileUploader;
	
	/**
	 * 
	 * @param {Object} input
	 */
	xwb.bindSearch = function($input, $btnSubmit){
		if (!$input || !$input.length) return;
		
		var chooselist = NULL;
		
		$input.attr('autocomplete', 'off');
		
		var $form = $input.parent();
		
		function submit() {
			var kw = $('input[name=k]', $form).val();
			
			var url = buildModulePath('search', (chooselist && chooselist.getSelect() == 0) ? '':'user', 'k=' + kw);
			
			window.location.href = url;
		}
		
		$btnSubmit.click(submit);
		
		
		function init() {
			var $list = $('<ul class="head-searchlist" style="display:none"></ul>');
			var $options = $('<li class="mouseover">含<span></span>的微博</li><li>名<span></span>的人</li>');
			var selectedIndex = 0;
			var isShow = FALSE;
			
			
			$list.append($options);
			
			$list.appendTo($form.parent().parent());
			
			function showList() {
				$list.show();
				isShow = TRUE;
			}
			
			$input.keydown(function(event){
				if (isShow) {
					switch (event.keyCode) {
						case 13: //enter
							submit();
							return FALSE;
						break;
						
						case 38: //up						
						case 40: //down
							selectedIndex ^= 1;
							$options.eq(selectedIndex^1).removeClass('mouseover');
							$options.eq(selectedIndex).addClass('mouseover');
						break;
					}
				}
			});
			
			$list.click(function(e){
				var target = e.target;
				var $target = $(target);
				var index = $options.index($target);
				selectedIndex = index;
				$options.eq(selectedIndex^1).removeClass('mouseover');
				$target.addClass('mouseover');
				submit();
			});
			
			chooselist = {
				getSelect: function(){
					return selectedIndex;
				},
				
				setVal: function(val){
					val = $.trim(val);
					var len = asciiLen(val);
					
					if (val) {
						var $spans = $('span', $options).text(val);
						
						!isShow && showList();
						
						//检查宽度，如果超过了用"..."截断
						var width,oldWidth;
						width = oldWidth =$spans.eq(0).width();
						
						while (width > 48) {
							val = val.substring(0, val.length-1);
							$spans.text(val);
							width = $spans.eq(0).width();
						}
						
						if (oldWidth > width) {
							$spans.text(val + '...');
						}
					}else {
						isShow = FALSE;
						$list.hide();
					}
				}
			};
			
			//return chooselist;
		}
		
		$input.focus(function(){
			if (!chooselist) init();
		})
		
		$input.keyup(function(){
			chooselist.setVal(this.value);
		})
	}
	
	/**
	 * 模块的功能配置
	 */
	var moduleConfig = {
		'myindex':'',
		'myprofile':'',
		'profile':'',
		'pub':'',
		'setting':'',
		'pub':'',
		'myfollow':'',
		'myfans':'',
		'follow': '',
		'fans':''
	}
	
	xwb.click = function(selector, type, handler) {
		$(selector).click(function(e){
			var $target = $(e.target);
			
			var rel = $target.attr('rel');
			
			var params = rel.split('_');
			
			var ret = handler(e, params);
			
			return ret;
		})
	}
	
	xwb.avatar = function(uid, size) {
		var mod = uid % 4 + 1, time = (new Date()).getTime(), size = size || 50;
		return 'http://tp' + mod + '.sinaimg.cn/' + uid + '/' + size + '/' + Math.ceil(time/3600000);
	}
	
	/**
	 * 針對頁面的初始化函数
	 * @param {Object} page 
	 * 			show(详细）| myindex（我的首页）| myprofile(我的微博) | profile(他的微博) | setting(设置）|
	 * 			pub(茶馆）| myfollow(我关注的）| myfans(我的粉丝) | follow(他关注的) | fans(他的粉丝)
	 * @param {Object} cfg
	 */
	xwb.init = function(page, cfg) {
		var cfg = cfg || {};
		
		$(function(){
			switch (page) {
				case 'show':
					var $content = $(cfg.container);
					xwb.showInit($content, cfg.mid, cfg.isForward);
				break;
				
				case 'myindex':
				
				break;
			}
		});
	}
	
})(jQuery);

/**
 * jQuery 高亮查找插件，完全基于文本结点的DOM操作，对原有非文本结点不造成任何影响。
 * 用法:
 <pre>
   高亮:
   $('#ss').highlight(['keyword', ... ]);
   清除:
   $('#ss').clearHighlight();
   
   或者传递自定义的样式类
   $('#ss').highlight(['keyword', ... ], 'cssClass');
   清除:
   $('#ss').clearhighlight('cssClass');   
 </pre>
 请确保每次高亮前清除先前已高亮内容。
 可选配置信息：
 
 $.fn.highlight.cls
*/
 
(function(){

// private
var IGNORE,S,ESC,LT,GT, inited;

// private
function init(){
    IGNORE = /INPUT|IMG|SCRIPT|STYLE|HEAD|MAP|AREA|TEXTAREA|SELECT|META|OBJECT|IFRAME/i;
    S      = /^\s+$/;
    ESC    = /(\.|\\|\/|\*|\?|\+|\[|\(|\)|\]|\{|\}|\^|\$|\|)/g;
    LT     = /</g;
    GT     = />/g;
    inited = true;
}

// entry
function entry(keys, cls){
    if(!inited)
      init();
  
    if(typeof keys === 'string')
      keys = $.trim(keys).split(S);

    // normalize
    var arr = [];
    for(var i=0,len=keys.length;i<len;i++){
       if(keys[i] && !S.test(keys[i])) {
          arr[arr.length] = keys[i].replace(LT, '&lt;')
                                   .replace(GT, '&gt;')
                                   .replace(ESC, '\\$1');
       }
    }
    var reg     = new RegExp('(' + arr.join('|') + ')', 'gi'),
        placing = '<span class="'+(cls||entry.cls)+'">$1</span>',
        div     = document.createElement('DIV');
    this.each(function(){
      highlightEl(this, reg, placing, div);
    });

	return this;
}

// public
$.fn.highlight = entry;

$.fn.clearHighlight = function(cls) {
  if(!inited)
    init();
  var cls = cls||entry.cls;
  this.each(function(){
    clearElhighlight(this, cls);
  });
};


// private
function replaceTextNode(textNode, reg, placing, div) {
  var data = textNode.data;
  if(!S.test(data)){
     data = data.replace(LT, '&lt;').replace(GT, '&gt;');
     if(reg.test(data)){
        if(!div)
          div = document.createElement('DIV');
        // html escape
        div.innerHTML = data.replace(reg, placing);
        // copy nodes
        var chs = div.childNodes,
            arr = [],
            fr = document.createDocumentFragment();
        
        // copy to array
        for(var i=0,len=chs.length;i<len;i++)
          arr[i] = chs[i];
        
        for(i=0;i<len;i++)
          fr.appendChild(arr[i]);
        
        textNode.parentNode.replaceChild(fr, textNode);
     }
  }
}

// private
function highlightEl(el, reg, placing, div){
    var chs = el.childNodes, 
        arr = [], i, len, nd;
      
      // copy to array
      for(i=0,len=chs.length;i<len;i++){
        if(!IGNORE.test( chs[i].tagName ))
          arr.push(chs[i]);
      }
      
      for(i=0,len=arr.length;i<len;i++){
        nd = arr[i];
        // textnode
        if(nd.nodeType === 3){
          try { 
            replaceTextNode(nd, reg, placing, div);
          }catch(e){}
        }else arguments.callee(nd, reg, placing, div);
      }
}


// private
function clearElhighlight(el, cls) {
  var chs = el.childNodes, 
      arr = [], i, len, nd, t;
      
  // copy to array
  for(i=0,len=chs.length;i<len;i++){
    if(!IGNORE.test( chs[i].tagName ))
    arr.push(chs[i]);
  }

  for(i=0,len=arr.length;i<len;i++){
    nd = arr[i];
    t = nd.nodeType;
    // textnode
    if(t === 3)
      continue;
    // span
    if(t === 1 && nd.tagName === 'SPAN' && nd.className === cls){
      // merge text nodes
      var textNode = nd.childNodes[0], 
          p        = nd.parentNode,
          pre      = nd.previousSibling,
          nxt      = nd.nextSibling;
      
      if(pre && pre.nodeType === 3){
        p.removeChild(pre);
        textNode.data = pre.data + textNode.data;
      }
      
      if(nxt && nxt.nodeType === 3){
        p.removeChild(nxt);
        textNode.data = textNode.data + nxt.data;
      }

      p.replaceChild(textNode, nd);
    }else arguments.callee(nd, cls);
  }
}

entry.cls = 'red-color';

})();