/**
 * @fileoverview 该文件是 xweibo 茶馆页面JS。
 */

(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,
    
    isFn = $.isFunction;

/**
 * 今日话题
 */
var hotTopic = (function() {
    var cr, data, $ui = {}, curNum = -1;
        
    return {
        init: function() {
            $ui.ctn = $('#container div.hot-topic div.column-body');
            data = dataInit();
            
            if(!data || $ui.ctn.length == 0) {return;}
            
            this.fillContent(true);
            
            cr = $ui.ctn.toColReplace();
            
            cr.config({
                'replaceCallback': replaceCallback
            });
            
            $ui.ctn.hover(function() {
                cr.stopAnimate();
            }, function() {
                cr.animate();
            });
            
            XWB.listenAttention($ui.ctn);
        },
        
        fillContent: function(isFirst) {
            if(!data || $ui.ctn.length == 0) {return;}

            if(++curNum >= data.length) {
                curNum = 0;
            }

            var $item = $(data[curNum]).appendTo($ui.ctn);
            
            $item.find('p.feedback').substrText(70);
            
            if(isFirst) {
                this.fillContent();
            }else {
                $item.addClass('next');
            }
        }
    };
    
    function dataInit() {
        var data = NULL;
        
        if(today_topic_weibo) {
            data = [];
            $.each(today_topic_weibo, function(i, item) {
                data[data.length] = item;
            });
        }        
        
        return data;
    }
    
    function replaceCallback($first, $next) {
        $first.remove();
        $next.removeClass('next');
        hotTopic.fillContent();
    }
})();

/**
* 随便看看
*/
var random = (function() {
    var 
        interval,
        stop = FALSE,
        $ui = {},
        speed = 1,
        delay = 50;
    
    return {
        init: function() {
            $ui.ctn = $('#container div.random-list div.column-body');
            
            $ui.ctn[0].scrollTop = 0;
            interval || this.scroll();
            
            var rd = this;
            
            $ui.ctn
                .hover(function() {
                    rd.stop();
                }, function() {
                    stop || rd.scroll();
                })
                .focus(function() {
                    rd.stop();
                    stop = TRUE;
                })
                .blur(function() {
                    stop && rd.scroll();
                    stop = FALSE;
                });
        },
        
        scroll: function() {
            if(interval) {
                this.stop();
            }
            
            var ctn = $ui.ctn[0];
            
            interval = setInterval(function() {

                ctn.scrollTop = ctn.scrollTop + speed;

                if(ctn.scrollTop >= ctn.scrollHeight - parseInt(ctn.offsetHeight)) {
                    ctn.scrollTop = 0;
                }
                
            }, delay);
        },
        
        stop: function() {
            if(interval) {
                clearInterval(interval);
                interval = NULL;
            }
        }
    };
})();

/**
 * 名人推荐图片滚动
 */
var celebrity = (function() {
    var $ui = {};
    
    return {
        init: function() {
            var $tem = $('#container div.recommand-list');
            $ui.photoCtn = $tem.find('div.column-body');
            
            if($ui.photoCtn.length > 0) {
                $ui.photoCtn.toPhotoViewer({
                    'lBtn': $tem.find('a.leftBtn'),
                    'rBtn': $tem.find('a.rightBtn')
                });
            }            
        }
    }
})();


/**
* 随便看看
*/

function SlideMover(opt){
  
  this._round = this._round;
  
  for(var i in opt) 
    this[i] = opt[i];
  
  this._createHolder();
};

SlideMover.prototype = {
/**@cfg {Number} interval*/  
    interval : 100,
/**@cfg {Number} timeout*/
    timeout : 3500,
/**@cfg {Number} step*/
    step : 10,
/**@cfg {Function} onempty*/

    start : function(){
      if(this.prepare()){
        this.setup(true);
      }
    },
    
    prepare : function(){
      var isIdle = this._checkIdle(),
          el = this.curEl = this.list.shift(),
          holder = this.holderEl;
      if(el){
        $(el).css({
          opacity    : 0.8,
          visibility : 'hidden',
          display    : 'block'
        });
        
        this.ctEl.appendChild(el);
        this._c = el.offsetHeight;
        el.style.display = 'none';
        this.ctEl.insertBefore(holder, this.ctEl.firstChild);
        holder.style.height = '0px';
        holder.style.display = 'block';
        this._b = 0;
        this._t = 0;
        this.prepared = true;
      }
      
      return !isIdle;
    },
    
    
    finish : function(){
      this.setup(false);
      this.holderEl.style.display = 'none';
      $(this.curEl).fadeTo(800, 1);
      this.ctEl.insertBefore(this.curEl, this.holderEl);
      this.curEl.style.visibility = '';
      this.curEl.style.display = '';
      this.ctEl.removeChild(this.holderEl);
      if(!this._checkIdle())
        this._enableNext(true);
      if(this.onfinish)
        this.onfinish();
      this.prepared = false;
    },
    
    setup : function(b){
      if(!b){
        this.loopTimer !== false && clearInterval(this.loopTimer);
        this.loopTimer = false;
        this._enableNext(false);
      }else {
        if(!this.loopTimer && !this.idle && this.prepared)
          this.loopTimer = setInterval(this._getLooper(), this.interval);
        if(!this.idle && !this.prepared)
          this._enableNext(true);
      }
    },
    
    _checkIdle : function(){
      this.idle = !this.list.length;
      if(this.idle){
        this.onempty && this.onempty(this.list);
        this.idle = !this.list.length;
      }
      return this.idle;
    },
    
    _enableNext : function(b, timeout){
      if(!b){
        this.nextTimer !== false && clearTimeout(this.nextTimer);
        this.nextTimer = false;
      }else {
        this.nextTimer = setTimeout(this._getNexter(), timeout || this.timeout);
      }
    },
    
    _getNexter : function(){
      if(!this._nexterFunc){
        var self = this;
        this._nexterFunc = function(){
          self.start();
        };
      }
      return this._nexterFunc;
    },
    
    _getLooper : function(){
      if(!this._timerFunc){
        var self = this;
        this._timerFunc = function(){
          self._round();
        };
      }
      return this._timerFunc;
    },
  
    _round : function(){
      var t = this._t, 
          d = this.step,
          c = this._c,
          h = (t/=d/2) < 1 ? 
            c/2*t*t*t + this._b : 
            c/2*((t-=2)*t*t + 2) + this._b;

      
      if(t < d) 
        this._t ++;

      else h = c;
      this.holderEl.style.height = h + 'px';
      h == c && this.finish();
    },
    
    _createHolder : function(){
      this.holderEl = document.createElement(this.holderTag||'LI');
      $(this.holderEl).css({
        display : 'block',
        overflow: 'hidden',
        fontSize: '0px',
        padding : '0px',
        margin  : '0px',
        border  : 'none',
        background : 'none'
      });
    },
    
    curEl : null,
    
    nextTimer : false,
    
    loopTimer : false
};

xwb.SlideMover = SlideMover;


//茶馆页面初始化
$(document).ready(function() {
    hotTopic.init();
    celebrity.init();
    
    var 
        $feedList = $('#feed-list'),
        scrollor = $('.random-list .column-body').get(0),
        lis = $feedList.find('li'), 
        arr = [],
        preH = scrollor.offsetHeight;
    
    //$feedList.css('visibility', 'hidden');
    lis.each(function(){
      this.parentNode.removeChild(this);
      arr.push(this);
    });

    while(arr.length){
      var li = arr.pop();
      $feedList.append(li);
      if(scrollor.scrollHeight > preH){
        li.parentNode.removeChild(li);
        arr.push(li);
        break;
      }
    }
    
    $feedList.css('visibility', '');

    var mover = new XWB.SlideMover({
      ctEl : $feedList.get(0),
      list : arr,
      onempty : function(list){
        var last = $feedList.find("li:last-child");
        list.push(last.get(0));
        last.remove();
      }
    });
    
    $feedList.hover(function(){
      mover.setup(false);
    }, function(){
      mover.setup(true);
    });
    mover.start();

    // XWB.setList($feedList);
    // XWB.linkRender();
    // XWB.comment.init();
    
});


})();