// JavaScript Document
(function ($) {
	$.fn.visual = function (options) {
		options = $.extend({'fadeTime': 1000,
		'playInterval': 5000,
		'initBorderPos': 214}, options);
		var $this = $(this),
		    $photos = $('#mainphoto > li', $this),
			$thumbs = $('#thumbnail > li', $this);
		var nowAnimate = false, nowVisual = 0, timerId = 0, nextBorderPos = 214;
		
		var changeVisual = function (i) {
			if (nowAnimate || nowVisual == i) return;
			nowAnimate = true;
			autoPlayStop();
			$photos.eq(nowVisual).css({'z-index': '5'}).fadeOut(options.fadeTime, function () {
				nowAnimate = false;
				autoPlayStart();
			});
			nowVisual = i;
			nextBorderPos = options.initBorderPos + nowVisual * 83;
			$('#thumbBorder').animate({'left': nextBorderPos},{duration: options.fadeTime});
			$photos.eq(nowVisual).css({'z-index': '1'}).show();
		}
		
		var autoPlayStart = function () {
			timerId = setTimeout(autoPlay, options.playInterval);
		}
		
		var autoPlayStop = function () {
			clearTimeout(timerId);
		}
		
		var autoPlay = function () {
			if (nowAnimate) return;
			var nextNo = nowVisual + 1;
			if (nextNo >= $photos.length) nextNo = 0;
			changeVisual(nextNo);
		}
		
		var initialize = function () {
			if ($photos.length != $thumbs.length && $photos.length <= 0) return $this;
			$photos.each(function (index, elem) {
				var $img = $('img', this);
				var src = $img.attr('src');
				$img.remove();
				$(this).css({'background-image': 'url(' + src + ')'}).hide();
			});
			$photos.eq(0).show();
			$thumbs.each(function (index, elem) {
				$('> a', this).attr({'href': 'javascript:void(0);'}).click(function () {
					changeVisual(index);
				});
			});
			
			autoPlayStart();
			
			return $this;
		}
		
		return initialize();
	}
})(jQuery);
