//--------------------------------------------------[createAnimation]
var FX = {};
FX.createAnimation = function() {
  function animate(o) {
    var time = 0;
    if (o.timeStamp) {
      time = new Date().getTime() - o.timeStamp;
    }
    else {
      o.timeStamp = new Date().getTime();
    }
    if (time > o.duration) {
      time = o.duration;
    }
    o.tween(o.mode(time / o.duration));
    if (time == o.duration) {
      stop(o);
    }
  }

  function play(o) {
    if (o.instance) {
      return;
    }
    o.instance = setInterval(function() {
      animate(o);
    }, o.interval);
    if (o.before) {
      o.before();
    }
  }

  function stop(o) {
    if (!o.instance) {
      return;
    }
    clearInterval(o.instance);
    o.instance = null;
    o.timeStamp = 0;
    if (o.after) {
      o.after();
    }
  }

  var mode = {
    normal:function(x) {
      return x;
    },
    easeIn:function(x) {
      return x * (2 - x);
    },
    easeOut:function(x) {
      return x * x;
    },
    backIn:function(x) {
      return 1.5 * x * x - 0.5 * x;
    }
  };
  return function(config) {
    var o = {
      before:config.before,
      tween:config.tween,
      after:config.after,
      mode:config.mode in mode ? mode[config.mode] : mode.normal,
      duration:config.duration || 1000,
      interval:config.interval || 10,
      timeStamp:0,
      instance:null
    };
    return {
      play:function() {
        play(o);
      },
      stop:function() {
        stop(o);
      }
    };
  };
}();

//--------------------------------------------------[插入样式表]
/**
 * 在页面中添加样式表。
 * @name addStyleRules
 * @param {Array} styleRules 要添加的样式规则集数组，每项为一单行字符串。
 * @version sundongguo 20110802
 */
function addStyleRules(styleRules) {
  document.getElementsByTagName('head')[0].appendChild(document.createElement('style'));
  var styleSheets = document.styleSheets;
  var styleSheet = styleSheets[styleSheets.length - 1];

  var styleRule = null;
  while (styleRule = styleRules.shift()) {
    if (styleSheet.insertRule) {
      styleSheet.insertRule(styleRule, styleSheet.cssRules.length);
    } else {
      var lBraceIndex = styleRule.indexOf('{');
      var rBraceIndex = styleRule.indexOf('}');
      var selector = styleRule.slice(0, lBraceIndex);
      var properties = styleRule.slice(lBraceIndex + 1, rBraceIndex);
      if (selector.indexOf(',') === -1) {
        styleSheet.addRule(selector, properties);
      } else {
        var selectors = selector.split(',');
        while (selector = selectors.shift()) {
          alert(selector + ':' + properties);
          styleSheet.addRule(selector, properties);
        }
      }
    }
  }
}

//--------------------------------------------------[广告轮播器]
var createADCarousel = function($target, data, duration) {
  // 生成模版。
  var id = '#' + $target.id + ' ';
  addStyleRules([
    id + '.ad { position: relative; height: 255px; font: bold 32px/255px Verdana; text-align: center; }',
    id + '.ad * { display: block; position: absolute; left: 0; top: 0; width: 614px; height: 255px; border: 0 none; }',
    id + '.ad a { background: url(/flash/flashAd/img/transparent.gif); }',
    id + '.ad div { left: -10000px; }', // 将变化 display 改为变化坐标，以支持 Opera。
    id + '.ad div.active { left: 0; }',
    id + '.carousel { overflow: hidden; zoom: 1; }',
    id + '.carousel div { float: left; height: 63px; }',
    id + '.carousel div.control a { display: block; width: 37px; height: 63px; background: url(/flash/flashAd/img/btn.jpg) no-repeat 0 0; }',
    id + '.carousel div.next a { background-position: -37px 0; }',
    id + '.carousel div.control a:hover { }',
    id + '.carousel div.viewport { position: relative; width: 540px; height: 63px; overflow: hidden; zoom: 1; }',
    id + '.carousel ul { position: relative; left: 0; top: 0; list-style: none; width: 540px; height: 63px; margin: 0; padding: 0; background: #166FAB;}',
    id + '.carousel li { display: inline; float: left; width: 179px; height: 63px; margin: 0 1px 0 0; padding: 0; cursor: pointer; }',
    id + '.carousel li h1 { height: 18px; margin: 10px 0 0 65px; padding: 0; font: bold 12px/18px Verdana; color: #D3F2FF; }',
    id + '.carousel li p { height: 18px; margin: 0 0 0 65px; padding: 0; font: normal 12px/18px Verdana; color: #D3F2FF; }',
    id + '.carousel li.active { background-position: 0 -63px; cursor: default; }',
    id + '.carousel li.active h1 { color: #000; }',
    id + '.carousel li.active p { color: #2293D2; }'
  ]);

  $target.innerHTML = [
    '<div class="ad"></div>' +
        '<div class="carousel">' +
        '  <div class="control prev"><a href="javascript:void(\'prev\');"></a></div>' +
        '  <div class="viewport"><ul></ul></div>' +
        '  <div class="control next"><a href="javascript:void(\'next\');"></a></div>' +
        '</div>'
  ].join('\n');

  var divElements = $target.getElementsByTagName('div');
  var ulElements = $target.getElementsByTagName('ul');
  var aElements = $target.getElementsByTagName('a');
  var $ad = divElements[0];
  var $carousel = divElements[1];
  var $viewport = divElements[3];
  var $container = ulElements[0];
  var $prev = aElements[0];
  var $next = aElements[1];

  // 选定一个项。
  var current = 0;

  function highlightItem(n, className) {
    $container.children[n - 1].className = className;
    if (n <= showItems) {
      $container.children[totalItems + n - 1].className = className;
    }
  }

  function onSelect(n) {
    active = n;
//console.log('activeL: ' + activeL, 'active: ' + active, 'activeR: ' + activeR);
    if (current) {
      highlightItem(current, '');
      $ad.children[current - 1].className = '';
    }
    $ad.children[n - 1].className = 'active';
    highlightItem(n, 'active');
    current = n;
  }

  // 添加内容项。
  function createItem(item, n, fillAd) {
//    var className = 'item_' + n;
    var li = document.createElement('li');
    li.innerHTML = '<h1>' + item.menuTitle + '</h1><p>' + item.menuDescreption + '</p>';
//    li.className = className;
    li.style.backgroundImage = 'url(' + item.menuImage + ')';
//    li.onmouseover = function() {
//      this.className = className + ' hover';
//    };
//    li.onmouseout = function() {
//      this.className = className;
//    };
    li.onclick = function() {
      onSelect(n);
    };
    $container.appendChild(li);
    if (fillAd) {
      var $div = document.createElement('div');
      var $a = document.createElement('a');
      $a.href = item.adLink;
      $a.target = '_blank';
      $div.appendChild($a);
      var isFlash = item.adUrl.slice(-3).toLowerCase() === 'swf';
      if (isFlash) {
        var $temp = document.createElement('div');
        $temp.id = 'temp_flash_' + n;
        $div.insertBefore($temp, $a);
        setTimeout(function() {
          swfobject.embedSWF(item.adUrl, 'temp_flash_' + n, '614', '255', '9.0.0', 'Images/expressInstall.swf', null, {menu: 'false', scale: 'showall', wmode: 'transparent'});
        }, 0);
      } else {
        var $img = new Image();
        $img.src = item.adUrl;
        $a.appendChild($img);
      }
      $ad.appendChild($div);
    }
  }

  // 添加内容。
  for (var i = 0, l = data.length; i < l; i++) {
    createItem(data[i], i + 1, true);
  }

  // 处理内容。
  var itemWidth = 180;
  var showItems = 3;
  var totalItems = $container.children.length;

  // 扩充内容。
  var n = 0;
  while (n < showItems) {
    createItem(data[n++], n, false);
  }
  $container.style.width = (totalItems + showItems) * itemWidth + 'px';

  // 滚动容器。
  var x = 0;
  var style = $container.style;

  function setX(value) {
    x = value;
    style.left = value + 'px';
  }

  // 设置活动项。
  var activeL = 1;
  var activeR = 3;
  var active = 0;

  function setActive(n) {
    activeL += n;
    activeR += n;
    if (activeL < 1) {
      activeL += totalItems;
    }
    if (activeR < 1) {
      activeR += totalItems;
    }
    if (activeL > totalItems) {
      activeL -= totalItems;
    }
    if (activeR > totalItems) {
      activeR -= totalItems;
    }
    active = n < 0 ? activeL : activeR;
  }

  // 滚动动画。
  var tween = FX.createAnimation({
    before: function() {
      playing = true;
    },
    tween: function(n) {
      setX(from + (to - from) * n);
    },
    after: function() {
      playing = false;
      onSelect(active);
    },
    mode: 'easeIn',
    duration: 200,
    interval: 10
  });

  // 滚动方法。
  var playing = false;
  var from = 0;
  var to = 0;

  function prev() {
    if (playing) {
      return;
    }
    if (x === 0) {
      x = -itemWidth * totalItems;
      setX(x);
      active = totalItems + 1;
    }
    from = x;
    to = from + itemWidth;
    setActive(-1);
    tween.play();
  }

  function next() {
    if (playing) {
      return;
    }
    if (x === -totalItems * itemWidth) {
      x = 0;
      setX(x);
    }
    from = x;
    to = from - itemWidth;
    setActive(1);
    tween.play();
  }

  // 不再点击左右按钮即滚动，而是先在内容区域滚动。暂时固定为 3 个可视项：-1 0 1。
  var ballance = 0;
  $prev.onclick = function() {
    ballance = (active === activeL ? -1 : (active === activeR ? 1 : 0));
    if (ballance === -1) {
      prev();
    } else {
      active--;
      if (active < 1) {
        active = totalItems;
      }
      onSelect(active);
    }
  };
  $next.onclick = function() {
    ballance = (active === activeL ? -1 : (active === activeR ? 1 : 0));
    if (ballance === 1) {
      next();
    } else {
      active++;
      if (active > totalItems) {
        active = 1;
      }
      onSelect(active);
    }
  };

  // 默认选择第一项。
  onSelect(1);

  // 自动轮播。
  var timer = null;

  function start() {
    timer = window.setInterval($next.onclick, duration * 1000);
  }

  function stop() {
    window.clearInterval(timer);
  }

  var hoverTimer = null;
  var hover = false;
  $target.onmouseover = function() {
    if (!hover) {
      hover = true;
      stop();
    }
    if (hoverTimer) {
      window.clearTimeout(hoverTimer);
      hoverTimer = null;
    }
  };
  $target.onmouseout = function() {
    if (!hoverTimer) {
      hoverTimer = window.setTimeout(function() {
        hover = false;
        start();
      }, 0);
    }
  };
  start();
};

