var $nike;
var $source;
var $mainUl;
var $sourceLi;
var _liStr;
var _itemLen;
var _middle;
var $rightUl;
var $leftUl;
var _smallWidth = 114, _bigWidth = 240, 
	_small = /small/ig,
	_big = 'big';
var runTime = 2500;
var runIndex = 1;
var runStatus = true;
var clickStatus = true;

function run(clickStatus) {
	
	if(clickStatus==false) {
		runStatus = false;
	}else{
		runStatus = true;		
	}
	$nike.find('.fake img').mouseover(function(){
		runStatus = false;
	});	
	$nike.find('.fake img').mouseout(function(){
		runStatus = true;
	});		
	
	if(runStatus==true) {
		move(runIndex);
		runIndex++;
	}
	setTimeout("run(clickStatus)", runTime);
	if(runIndex>_itemLen) runIndex=1;
}

// 控制移動的函式
function move(i){
	// 移動左右清單
	// 移動時變成不透明
	$leftUl.add($rightUl).add($('.nike_right.fake ul, .nike_left.fake  ul')).stop(false, true).animate({
		left: i * _smallWidth * -1
	}, changeLeft).find('li a').css('opacity', 1);;
	
	// 移動中間清單
	$mainUl.add($('.nike_main.fake ul')).stop(false, true).animate({
		left: i * _bigWidth * -1
	}, changeLeft);
}

// 當完成移動後的處理函式
		function changeLeft(){
			var $this = $(this),
				dis = $this.parent().attr('className').indexOf('nike_main')>-1 ? _bigWidth : _smallWidth,
				i = (parseInt($this.css('left'), 10) || 0) / dis * -1;
			
			// 處理左右清單的位移
			if(i >= _itemLen){
				$(this).css('left', dis * (i - _itemLen) * -1);
			}
			
			// 把左右清單的 li a 變成 0.5 的透明度
			if(dis==_smallWidth){
				$(this).find('li a').css('opacity', 0.5);
			}
		}
		
// 組成 li 項目的函式
		function getLiItem(startIndex, endIndex){
			var rtvl = '';
			for(var i=startIndex;i<endIndex;i++){
				rtvl += '<li>' + $sourceLi.eq(i).html() + '</li>';
			}
			return rtvl;
		}
		
		
	$(function(){
		// 先取得 .nike 及原始的 ul 項目
		// 接著產生三組 div 並各自包一個 ul 項目
		// 再來取得一些額外的參數、小圖及大圖的名稱
		$nike = $('.nike');
		$source = $nike.children('ul').remove();
		$mainUl = $('<div class="nike_main"><ul></ul></div>').children();
		$sourceLi = $source.children();
		_liStr = $source.html();
		_itemLen = $sourceLi.length;
		_middle = Math.ceil(_itemLen / 2);
			
		$rightUl = $('<div class="nike_right"><ul></ul></div>').children();
		$leftUl = $('<div class="nike_left"><ul></ul></div>').children();
		
		// 幫左邊 ul 清單加入 li 項目
		$leftUl.append(getLiItem(_middle - 2 - 1, _itemLen) + _liStr);
		// 幫右邊 ul 清單加入 li 項目
		$rightUl.append(getLiItem(_middle, _itemLen) + _liStr + getLiItem(0, _itemLen - _middle));
		// 幫中間 ul 清單加入 li 項目
		$mainUl.append((getLiItem(_middle - 1, _itemLen) + _liStr).replace(_small, _big));
		// 把 ul 清單部份都加到 .nike 中
		$nike.append($leftUl.parent(), $rightUl.parent(), $mainUl.parent());
		// 加入遮罩 .mask
		$nike.append('<div class="mask"></div>');
		// 加入控制用的遮罩 ul
		$nike.append($leftUl.parent().clone().addClass('fake'), $rightUl.parent().clone().addClass('fake'), $mainUl.parent().clone().addClass('fake'));
		// 隱藏控制用的遮罩 ul 中的圖片
		$nike.find('.fake img').css('opacity', 0);
		// 幫左右兩邊的 ul li a 加上 0.5 的透明度
		$rightUl.add($leftUl).find('li a').fadeTo(200, 0.5);
	
		
		// 幫控制用的左右兩邊遮罩的 ul li a 加上 hover 事件
		// 當滑鼠移到項目時就變成不透明；移出則再變成 0.5 的透明度
		$('.nike_right.fake, .nike_left.fake').find('li a').hover(function(){
			var $this = $(this);
			($this.parents('div').attr('className').indexOf('nike_right')>-1 ? $rightUl : $leftUl).children('li').eq($this.parent().index()).children().fadeTo(200, 1);
		}, function(){
			var $this = $(this);
			($this.parents('div').attr('className').indexOf('nike_right')>-1 ? $rightUl : $leftUl).children('li').eq($this.parent().index()).children().fadeTo(200, 0.5);
		});

		$nike.find('a').focus(function(){this.blur();});
		
		setTimeout("run(clickStatus)", runTime);
	});

	
    jQuery(document).ready(function($) {
      $('a[rel*=facybox]').facybox({
        // noAutoload: true
      });
      
      $("h2",$("#changelog")).css("cursor","pointer").click(function(){
          $(this).next().slideToggle('fast');
      }).trigger("click");
      
    });


;(function($) {

$.fn.fixPNG = function() {
return this.each(function () {
var image = $(this).css('backgroundImage');

if (image.match(/^url\(["']?(.*\.png)["']?\)$/i)) {
image = RegExp.$1;
$(this).css({
'backgroundImage': 'none',
'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=" + ($(this).css('backgroundRepeat') == 'no-repeat' ? 'crop' : 'scale') + ", src='" + image + "')"
}).each(function () {
var position = $(this).css('position');
if (position != 'absolute' && position != 'relative')
$(this).css('position', 'relative');
});
}
});
};

  //TODO refactor using data.content_klass
  $.facybox = function(data, klass) {
    $.facybox.loading();
    $.facybox.content_klass = klass;
    if (data.ajax) revealAjax(data.ajax);
    else if(data.image) revealImage(data.image);
    else if(data.images) revealGallery(data.images,data.initial);
    else if(data.div) revealHref(data.div);
    else if($.isFunction(data)) data.call($);
    else $.facybox.reveal(data);
  }

  /*
* Public, $.facybox methods
*/

  $.extend($.facybox, {
    //possible option: noAutoload --- will build facybox only when it is needed
    settings: {
opacity : 0.3,
overlay : true,
modal : false,
imageTypes : [ 'png', 'jpg', 'jpeg', 'gif' ],
imageMimeTypes : [ 'image/jpeg', 'image/png', 'image/gif' ]
    },

    html : function(){
      return '\
<div id="facybox" style="display:none;"> \
<div class="popup"> \
<table> \
<tbody> \
<tr> \
<td class="nw"/><td class="n" /><td class="ne"/> \
</tr> \
<tr> \
<td class="w" /> \
<td class="body"> \
<div class="footer"> </div> \
<a href="#" class="close"></a>\
<div class="content"> \
</div> \
</td> \
<td class="e"/> \
</tr> \
<tr> \
<td class="sw"/><td class="s"/><td class="se"/> \
</tr> \
</tbody> \
</table> \
</div> \
</div> \
<div class="loading"></div> \
'
    },

    loading: function(){
      init();
      if($('.loading',$('#facybox'))[0]) return;//already in loading state...
      showOverlay();
      $.facybox.wait();
      if (!$.facybox.settings.modal) {
        $(document).bind('keydown.facybox', function(e) {
          if(e.keyCode == 27) $.facybox.close();//ESC
        });
      }
      $(document).trigger('loading.facybox');
    },

    wait: function(){
      var $f = $('#facybox');
      $('.content',$f).empty();//clear out old content
      $('.body',$f).children().hide().end().append('<div class="loading"></div>');
      $f.fadeIn('fast');
$.facybox.centralize();
      $(document).trigger('reveal.facybox').trigger('afterReveal.facybox');
    },

    centralize: function(){

var $f = $('#facybox');
var pos = $.facybox.getViewport();
var wl = parseInt(pos[0]/2) - parseInt($f.find("table").width() / 2);
var fh = parseInt($f.height());

if(pos[1] > fh){
var t = (pos[3] + (pos[1] - fh)/2);
$f.css({ 'left': wl, 'top': t });
// console.log('height smaller then window: '+fh, pos[1], pos[3])
} else {
var t = (pos[3] + (pos[1] /10));
$f.css({ 'left': wl, 'top': t });
// console.log('height bigger then window')
}
    },

getViewport: function() {
// [1009, 426, 0, 704]
return [$(window).width(), $(window).height(), $(window).scrollLeft(), $(window).scrollTop()];
},

    reveal: function(content){
$(document).trigger('beforeReveal.facybox');
var $f = $('#facybox');
$('.content',$f)
.attr('class',($.facybox.content_klass||'')+' content') //do not simply add the new class, since on the next call the old classes would remain
.html(content);
$('.loading',$f).remove();

var $body = $('.body',$f);

$body.children().fadeIn('fast');

$.facybox.centralize();

$(document).trigger('reveal.facybox').trigger('afterReveal.facybox');
    },

    close: function(){
      $(document).trigger('close.facybox');
      return false;
    }
  })

  /*
* Bind to links, on click they open a facybox which
* contains what their href points to
*/
  $.fn.facybox = function(settings) {
    var $this = $(this);
    if(!$this[0]) return $this;//called on empty elements, just stop and continue chain
    if(settings)$.extend($.facybox.settings, settings);
    if(!$.facybox.settings.noAutoload) init();

    $this.bind('click.facybox',function(){
      $.facybox.loading();
clickStatus=false;
      // support for rel="facybox.inline_popup" syntax, to add a class
      // also supports deprecated "facybox[.inline_popup]" syntax
      var klass = this.rel.match(/facybox\[?\.(\w+)\]?/);
      $.facybox.content_klass = klass ? klass[1] : '';
      revealHref(this.href);
      return false;
    });
    return $this;//continue chain
  }

  /*
* Private methods
*/
  // called one time to setup facybox on this page
  function init() {
    if($.facybox.settings.inited) return;
    else $.facybox.settings.inited = true;

    $(document).trigger('init.facybox');
    makeBackwardsCompatible();

    var imageTypes = $.facybox.settings.imageTypes.join('|');
    $.facybox.settings.imageTypesRegexp = new RegExp('\.(' + imageTypes + ')', 'i');

    $('body').append($.facybox.html());//insert facybox to dom


// ie hacks
var $f = $("#facybox");

// it amazes me that this is still better than native png32 support in ie8...
if($.browser.msie){
$(".n, .s, .w, .e, .nw, .ne, .sw, .se", $f).fixPNG();
// ie6
if(parseInt($.browser.version) <= 6){
var css = "<style type='text/css' media='screen'>* html #facybox_overlay { position: absolute; height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');}</style>"
$('head').append(css);
$(".close", $f).fixPNG();
$(".close",$f).css({
'right': '15px'
});
}
$(".w, .e",$f).css({
width: '13px',
'font-size': '0'
}).text("&nbsp;");
}

    //if we did not autoload, so the user has just clicked the facybox and pre-loading is useless
    if(! $.facybox.settings.noAutoload){
preloadImages();
}
        $('#facybox .close').click($.facybox.close);
        $('#facybox .close').click(function(){
        	clickStatus = true;
           });
  }

  //preloads all the static facybox images
  function preloadImages(){
    //TODO preload prev/next ?
    $('#facybox').find('.n, .close , .s, .w, .e, .nw, ne, sw, se').each(function() {
      var img = new Image();
      img.src = $(this).css('background-image').replace(/^url\(\"?/, "").replace(/\"?\)$/, "");
    });
    // var img = new Image();
    // img.src = 'images/loading.gif';
    /*
TODO: remove and load preloader from filament group
*/
  }

  function makeBackwardsCompatible() {
    var $s = $.facybox.settings;
    $s.imageTypes = $s.image_types || $s.imageTypes;
    $s.facyboxHtml = $s.facybox_html || $s.facyboxHtml;
  }

  // Figures out what you want to display and displays it
  // formats are:
  // div: #id
  // image: blah.extension
  // ajax: anything else
  function revealHref(href) {
    // div
    if(href.match(/#/)) {
      var url = window.location.href.split('#')[0];
      var target = href.replace(url,'');
      if (target == '#') return
      $.facybox.reveal($(target).html(), $.facybox.content_klass);
    // image
    } else if(href.match($.facybox.settings.imageTypesRegexp)) {
      revealImage(href);
    // ajax
    } else { revealAjax(href)}
  }

  function revealGallery(hrefs, initial) {
    //initial position
    var position = $.inArray(initial||0,hrefs);
    if(position ==-1){
position = 0;
}

    //build navigation and ensure it will be removed
var $footer = $('#facybox div.footer');

    $footer.append($('<div class="navigation"><a class="prev"/><a class="next"/><div class="counter"></div></div>'));
    var $nav = $('#facybox .navigation');

    $(document).bind('afterClose.facybox',function(){$nav.remove()});

    function change_image(diff){
      position = (position + diff + hrefs.length) % hrefs.length;
      revealImage(hrefs[position]);
      $nav.find('.counter').html(position +1+" / "+hrefs.length);
    }
    change_image(0);

    //bind events
    $('.prev',$nav).click(function(){change_image(-1)});
    $('.next',$nav).click(function(){change_image(1)});
    $(document).bind('keydown.facybox', function(e) {
      if(e.keyCode == 39)change_image(1); // right
      if(e.keyCode == 37)change_image(-1); // left
    });
  }

  function revealImage(href){

var $f = $("#facybox");

    $('#facybox .content').empty();
    $.facybox.loading();//TODO loading must be shown until image is loaded -> stopLoading() on onload
    var image = new Image();
    image.onload = function() {
$.facybox.reveal('<div class="image"><img src="' + image.src + '" /></div>', $.facybox.content_klass);

var $footer = $("div.footer",$f);
var $content = $("div.content",$f);
var $navigation = $("div.navigation",$f);
var $next = $("a.next",$f);
var $prev = $("a.prev",$f);
var $counter = $("div.counter",$f);

var size = [$content.width(), $content.height()];

$footer.width(size[0]).height(size[1]);
$navigation.width(size[0]).height(size[1]);
$next.width(parseInt(size[0]/2)).height(size[1]).css({ left: (size[0]/2) });
$prev.width(size[0]/2).height(size[1]);
$counter.width(parseInt($f.width() -26)).css({'opacity' : 0.5, '-moz-border-radius' : '8px', '-webkit-border-radius' : '8px'})

    }
    image.src = href;
  }

  function revealAjax(href) {
    // $.get(href, function(data) { $.facybox.reveal(data) });
$.ajax({
type: "GET",
url: href,
complete: function(XMLHttpRequest, textStatus) {
content_type = XMLHttpRequest.getResponseHeader("Content-Type");
if ( jQuery.inArray(content_type, $.facybox.settings.imageMimeTypes) >= 0 ) {
revealImage(href)
$.facybox.centralize();
} else {
$.facybox.reveal( XMLHttpRequest.responseText );
}
}
});
  }

  function skipOverlay() {
    return $.facybox.settings.overlay == false || $.facybox.settings.opacity === null
  }

  function showOverlay() {
    if(skipOverlay()) return;

    if($('#facybox_overlay').length == 0){
      $("body").append('<div id="facybox_overlay" class="facybox_hide"></div>');
    }

    $('#facybox_overlay').hide().addClass("facybox_overlayBG")
      .css('opacity', $.facybox.settings.opacity)
      .fadeIn(200);
    if(!$.facybox.settings.modal){
      $('#facybox_overlay').click(function(){ $(document).trigger('close.facybox')})
    }
  }

  function hideOverlay() {
    if(skipOverlay()) return;

    $('#facybox_overlay').fadeOut(200, function(){
      $("#facybox_overlay").removeClass("facybox_overlayBG").
        addClass("facybox_hide").
        remove();
    })
  }

  /*
* Bindings
*/

  $(document).bind('close.facybox', function() {
    $(document).unbind('keydown.facybox');

// ie hacks
var $f = $("#facybox");
if($.browser.msie){
$('#facybox').hide();
hideOverlay();
$('#facybox .loading').remove();
} else {
$('#facybox').fadeOut('fast',function() {
$('#facybox .content').removeClass().addClass('content');//revert changing class
hideOverlay();
$('#facybox .loading').remove();
})
}

    $(document).trigger('afterClose.facybox');
  });

})(jQuery);
