/***************************************************************************
 * 
 * Copyright (c) 2011 tuan.com.cn, Inc. All Rights Reserved
 * $Id$ 
 * 
 **************************************************************************/
 
 
 
/**
 * webroot/js/tuan.js ~ 2011/01/19 22:14:44
 * @author tuan(tuan@tuan.com.cn)
 * @version $Revision$ 
 * @description 
 * 
 **/

function AddFavorite() {
  var url = 'http://www.tuan.com.cn',
      description = '团购城';
  if (document.all) {
    window.external.addFavorite(url, description);
  } else if (window.sidebar) {
    window.sidebar.addPanel(description, url, '');
  }
}

function parseDateTime(datetime){
  var pattern = /(\d+)-(\d+)-(\d+) (\d+):(\d+):(\d+)/;
  var match = datetime.match(pattern);
  if(match){
    return new Date(
      parseInt(match[1], 10), 
      parseInt(match[2], 10) - 1,
      parseInt(match[3], 10),
      parseInt(match[4], 10),
      parseInt(match[5], 10),
      parseInt(match[6], 10)
    );
  }
}

function getLeftTime(time){
  var seconds = parseInt(time / 1000, 10);
  
  var days = parseInt(seconds / (24 * 60 * 60), 10);
  seconds -= days * 24 * 60 * 60;
  
  var hours = parseInt(seconds / (60 * 60), 10);
  seconds -= hours * 60 * 60;

  var minutes = parseInt(seconds / (60), 10);
  seconds -= minutes * 60;

  return ((days > 0) ? (days + "天") : '') + 
    ((hours > 0) ? (hours + "小时") : '') + 
    ((minutes > 0) ? (minutes + "分") : '') + 
    ((seconds > 0) ? (seconds + "秒") : '');
}

function Countdown() {
  this._timer = 0;
  this._root = null;
}

Countdown.prototype.setRoot = function(root) {
  this._root = root;
}

Countdown.prototype.start = function() {
  var root = $(this._root);
  this._timer = setInterval(function(){
    var now = new Date().getTime();
    root.find(".buying_date").each(function(){
      var deal_end_time = parseDateTime($(this).data("end-time")).getTime();
      if (now >= deal_end_time) {
        // TODO
        $(this).html("已经结束");
        if (location.href.indexOf('/deals/past') == -1) {
          // 没有在往期团购页面
          if (!$(this).data('has_update_status')){
            // 已经更新过了
            $(this).data('has_update_status', true);
            $.post('/deals/update_status/' + $(this).data("id"));
          }
        }
      } else {
        $(this).html(getLeftTime(deal_end_time - now));
      }
    });
  }, 1000);
}

Countdown.prototype.stop = function() {
  if (this._timer) {
    clearInterval(this._timer);
  }
}

$(function(){
  $(".ui-city-switch .switch-city a:first-child").click(function(){
    $(".switch-city div:last-child").toggle();
  });   

  $(".switch-city").hover(function(){
    $(this).addClass("switch-city-hover");
  }, function(){
    $(this).removeClass("switch-city-hover");
  });

  function InitTabs(selector){
    var countDown = new Countdown();
    $(selector).tabs({
      'load' : function(event, ui){
        countDown.stop();
        countDown.setRoot(ui.panel);
        countDown.start();
      }
    });
  }

  function InitSearchResults(selector){
    var countDown = new Countdown();
    countDown.stop();
    countDown.setRoot(selector);
    countDown.start();
  }
 
  function InitDealList(selector) {
    var countDown = new Countdown();
    countDown.stop();
    countDown.setRoot(selector);
    countDown.start();
  }

  function InitPagination(selector){
    $(selector + " .pagination a").live("click", function(){
      $(this).parents(".ui-tabs-panel").load($(this).attr("href"));
      return false;
    });;
  }

  InitDealList(".ui-deal-item");
  // InitTabs(".deal-list");
  // InitPagination(".deal-list");
  // InitTabs(".today-proposed-deal-list");
  // InitSearchResults(".deal-search-list");
});


var tuan = {};

/**
 * @constructor
 * @param {string} title 标题
 * @param {string} url 链接地址
 */
tuan.Share = function(title, url) {
  this.title = title;
  this.url = url;

  this._map = {};

  this.init();
}

tuan.Share.prototype.init = function() {
  // register
  this._map['sina'] = '<a class="share-2-sina" target="_blank" href="http://v.t.sina.com.cn/share/share.php?title=${title}&url=${url}">微博</a>';
  this._map['qq'] = '<a class="share-2-qq" target="_blank" href="http://v.t.qq.com/share/share.php?title=${title}&url=${url}">微博</a>';
  this._map['kaixin001'] = '<a class="share-2-kaixin001" target="_blank" href="http://www.kaixin001.com/repaste/share.php?rtitle=${title}&rurl=${url}"> </a>';
  this._map['renren'] = '<a class="share-2-renren" target="_blank" href="http://share.renren.com/share/buttonshare.do?link=${url}&title=${title}"> </a>';
  this._map['douban'] = '<a class="share-2-douban" target="_blank" href="http://www.douban.com/recommend/?url=${url}&title=${title}"> </a>';
  this._map['::MAIL::'] = '<a class="share-2-mail" target="_blank" href="mailto:?subject=${title}&body=${url}"> </a>';
}

/**
 * @return {string}
 */
tuan.Share.prototype._getLink = function(tpl) {
  var html = tpl.replace(/\${title}/, encodeURIComponent(this.title))
                .replace(/\${url}/, encodeURIComponent(this.url));
  return html;
}

/**
 * @param {*...} var_args
 */
tuan.Share.prototype.to = function(var_args) {
  var html = [],
      tpl = null;
  for (var i = 0, j = arguments.length; i < j; i ++) {
    tpl = this._map[arguments[i]];
    if (tpl) {
      html.push(this._getLink(tpl));
    }
  }

  return html.join('&nbsp;');
}


/**
 * @namespace
 * tuan.ui
 */
tuan.ui = {}

/**
 * @constructor
 */
tuan.ui.Tab = function() {
}

/**
 * @param {HTMLElement} obj
 * @param {string} id
 */
tuan.ui.Tab.prototype.init = function(obj, id) {
  var arrayli = obj.parentNode.getElementsByTagName("li"); //获取li数组
  var arrayul = document.getElementById(id).getElementsByTagName("ul"); //获取ul数组
  for(i=0;i<arrayul.length;i++) {
    if(obj==arrayli[i]) {
      arrayli[i].className = "cli";
      arrayul[i].className = "";
    } else {
      arrayli[i].className = "";
      arrayul[i].className = "hidden";
    }
  }
}


/**
 * 批量显示团购交易的数据
 * @constructor
 * @param {string} container
 * @param {string=} bind_url
 */
tuan.ui.DealItems = function(container, opt_bind_url) {
  this.container = container;
  this.bind_url = opt_bind_url || null;
}

/**
 * 开始倒计时
 * @param {string|jQueryObect} root
 */
tuan.ui.DealItems.prototype._countDown = function(root) {
  var timer = new Countdown();
  timer.stop();
  timer.setRoot(root);
  timer.start();
}


/**
 * 显示内容吧
 */
tuan.ui.DealItems.prototype.render = function() {
  var me = this,
      bind_url = this.bind_url,
      container = this.container;

  $(container).each(function(){
    var url = bind_url || $(this).data("bind-url");
    if (url) {
      $(this).load(url, function(){
        me._countDown(container);
      });
    }
  });

  $(container + " .ui-pagination a").live("click", function(){
    $(this).parents(container).load($(this).attr("href"), function(){
      me._countDown(container);
    });
    return false;
  });
}

/**
 * 推荐的团购交易数据.
 * @constructor
 */
tuan.ui.ProposedDealItems = function(selector) {
  this.selector = selector;
  this.items = $(selector);
  this.index = -2; // 初始位置-2
  this.block = 2; // 每次显示2个
  this.timer = null;
}
tuan.ui.ProposedDealItems.prototype.slideshow = function() {
  if (this.items.length <= this.block) {
    this.items.show();
    return;
  }

  var me = this;
  $(this.selector).parents(".ui-deal-items-container").mouseenter(function(){
    if(me.timer) {
      clearTimeout(me.timer);
    }
  }).mouseleave(function(){
    me.timer = setTimeout(function(){ me.next() }, 5000);
  });
  this.next();
}
tuan.ui.ProposedDealItems.prototype.next = function() {
  // 隐藏当前的
  var selector = []
  for(var i = this.index, j = 0, k = this.items.length;
      j < this.block && i < k;
      i ++, j ++) {
    selector.push(this.selector + ':nth(' + i + ')');
  }
  $(selector.join(',')).hide('slide');

  // 显示现在的
  var new_selector = [];
  var new_index = this.index + this.block;
  if (new_index >= this.items.length) {
    new_index = 0;
  }
  for(var i = new_index, j = 0, k = this.items.length;
      j < this.block && i < k;
      i ++, j ++) {
    new_selector.push(this.selector + ':nth(' + i + ')');
  }
  $(new_selector.join(',')).show('slide');
  this.index = new_index;

  var me = this;
  this.timer = setTimeout(function(){ me.next() }, 5000);
}

try {document.execCommand("BackgroundImageCache", false, true);}catch(ex) {}













/* vim: set ts=4 sw=4 sts=4 tw=100 noet: */

