// JavaScript Document
var imgsw_index = 0;
var imgsw_fading = false;
var imgsw_lastbtn = null;
var imgsw_btncheck = null;

function addLoadEvent(func)
{
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	} else {
		window.onload = function() {
			if (oldonload) {
				oldonload();
			}
			func();
		}
	}
}

addLoadEvent(initImgSw);

function initImgSw()
{
	$(".imgswitcher").removeClass("preload");

	$(".imgswitcher").find(".item:eq(" + imgsw_index + ")").css("z-index", -1);
	$(".imgswitcher").find(".item:eq(" + imgsw_index + ")").show();

	$(".imgswitcher").find(".btn:eq(" + imgsw_index + ")").addClass("selected");

	$(".imgswitcher").find(".btn").each(function(index, domElement) {
		$(this).bind("mouseenter", index, enterBtn);
		$(this).bind("mouseleave", index, leaveBtn);
	});
	$(".imgswitcher").find(".btn").show();
}

$(function(){

	$(".imgswitcher").find(".item").hide();
	$(".imgswitcher").find(".btn").hide();
	
	$(".imgswitcher").find(".item").css("z-index", -3);
	$(".imgswitcher").find(".item").css("position", "absolute");
	$(".imgswitcher").find(".item").css("top", 0);
	$(".imgswitcher").find(".item").css("left", 0);

	$(".imgswitcher").css("height", $(".imgswitcher").find(".item:eq(0)").height());
	$(".imgswitcher").addClass("preload");
});

function enterBtn(ev)
{
	imgsw_lastbtn = ev.data;
	setTimeout("checkBtn(" + ev.data + ")", 300);
}

function leaveBtn(ev)
{
	if (imgsw_lastbtn === ev.data)
		imgsw_lastbtn = null;
}

function checkBtn(index)
{
	if (imgsw_lastbtn === index)
	{
		imgsw_btncheck = index;
		if (!imgsw_fading && index !== imgsw_index)
		{
			showImg(index);
		}
	}
}

function showImg(index)
{
	imgsw_fading = true;

	var $newimg = $(".item:eq(" + index + ")");
	var $oldimg = $(".item:eq(" + imgsw_index + ")");

	$(".btn:eq(" + imgsw_index + ")").removeClass("selected");
	$(".btn:eq(" + index + ")").toggleClass("selected");

	imgsw_index = index;

	$newimg.css("z-index", -2);
	$newimg.show();

	$oldimg.fadeOut("slow", function(){
		$oldimg.css("z-index", -3);
		$newimg.css("z-index", -1);
		if (imgsw_btncheck !== null && imgsw_btncheck !== index)
		{
			showImg(imgsw_btncheck);
		}
		else
			imgsw_fading = false;
	});
}
