var isZoomed = false;

function loadXXLImage(imageContainer){
	if(!xxlImagesLoaded){
		var xlImage = imageContainer.find("img.xl");
		var xxlImage = imageContainer.find("img.xxl");
		var xlImageSource = xlImage.attr("src");
		var xxlImageSource = xxlImage.attr("src");
		if(xlImageSource != null && xxlImageSource == ""){
			var xlImageSoucreInsert = xlImageSource.length - 11;
			xxlImageSource = xlImageSource.substr(0,xlImageSoucreInsert) + "zoom" + xlImageSource.substr(xlImageSoucreInsert + 6);
			xxlImage.attr("src",xxlImageSource);
		}
	}
}
function loadAllXXLImages() {
	if(!xxlImagesLoaded){
		$.each($(".productImagesItems > div "), function(){
			loadXXLImage($(this))
		});
		xxlImagesLoaded = true;
	}
}
function raiseZIndex(layer,layerIdToStopAt) {
	var parent = layer.parent();
	if(parent!=null && parent.attr("id")!==layerIdToStopAt){
		parent.css("z-index","9989"); //TODO remove hardcoded 9999
		raiseZIndex(parent);
	}
}
function resetZIndex(layer,layerIdToStopAt) {
	var parent = layer.parent();
	if(parent!=null && parent.attr("id")!==layerIdToStopAt){
		parent.css("z-index","");
		resetZIndex(parent);
	}
}
function resizeImage(imageContainer, largeImageSize, event, delta, productImageLayerName) {
	var defaultImageSize = $("#" + productImageLayerName + " .productImages").width();
	var oldWidth = imageContainer.find("img").width();
	var newWidth = oldWidth + (delta*60);
	if (newWidth <= defaultImageSize) {
		if(defaultImageSize != largeImageSize) {
			repositionImageAccordingToMouse(imageContainer, 0, 0, productImageLayerName);
		} else {
			repositionImageAccordingToMouse(imageContainer, 0, event.pageY, productImageLayerName);
		}
		resetImages(defaultImageSize, largeImageSize);
		
	} else {
		loadXXLImage(imageContainer);
		imageContainer.find("img.xxl").show();
		$("#" + productImageLayerName + " .reset-button").show();
		imageContainer.find("img").css("width", newWidth + "px");
		repositionImageAccordingToMouse(imageContainer, event.pageX, event.pageY, productImageLayerName);
	}
}
function resizeImageFixedSize(imageContainer, event, largeImageSize, productImageLayerName) {
	loadXXLImage(imageContainer);
	$("#" + productImageLayerName + " .xxl").show();
	$("#" + productImageLayerName + " .reset-button").show();
	imageContainer.find("img").css("width", largeImageSize + "px");
	repositionImageAccordingToMouse(imageContainer, event.pageX, event.pageY, productImageLayerName);
}
function resetImages(defaultImageSize, largeImageSize){
	$("div.productImagesItems > div > img").css("width",defaultImageSize);
	if(defaultImageSize < largeImageSize - 10) { //for some reason IE7 doesn't like largeImageSize?
		$(".xxl").hide();
	}
	$(".reset-button").hide();
}
function repositionImageAccordingToMouse(container, leftPosition, topPosition, productImageLayerName) {
   	var mouseXPosition = leftPosition - $("#" + productImageLayerName + " .productImages").offset().left;
   	var mouseYPosition = topPosition - $("#" + productImageLayerName + " .productImages").offset().top;
   	if(isZoomed){
	   	var imageWidth = container.find(".xxl").width();
	   	var imageHeight = container.find(".xxl").height();
   	}else{
	   	var imageWidth = container.find("img").width();
	   	var imageHeight = container.find("img").height();
   	}   	
   	var zoomWindowWidth = $("#" + productImageLayerName + " .productImages").width();
   	var zoomWindowHeight = $("#" + productImageLayerName + " .productImages").height();
   	var newXPosition = 0 - ((mouseXPosition / zoomWindowWidth * imageWidth) - mouseXPosition);
   	var newXPosition = Math.ceil(newXPosition);
   	var newYPosition = 0 - ((mouseYPosition / zoomWindowHeight * imageHeight) - mouseYPosition);
   	var newYPosition = Math.ceil(newYPosition);
	
	if(newXPosition>0){
		newXPosition = 0;
	}
	if(newYPosition>0){
		newYPosition = 0;
	}
	container.find("img").css({
		left: newXPosition+"px",
		top: newYPosition+"px"
	});
}
function maintainCurrentImage(productImageLayerName, scrollingSpeed) {
	var imageWidth = $("#" + productImageLayerName + " .productImages").width();
	$("#" + productImageLayerName + " div.productImagesItems > div > img").css("width",imageWidth);
	var currentImage = apiScrollable.getIndex() + 1;
	apiScrollable.onBeforeSeek(function(){
		this.getConf().speed = 0;
	});
	apiScrollable.begin();
	if(currentImage<=1){ //TODO Rework this
		apiScrollable.seekTo(2);
	}
	apiScrollable.seekTo(currentImage);
	apiScrollable.onBeforeSeek(function(){
		this.getConf().speed = scrollingSpeed;
	});
	manageNextPrevButtonVisibility(apiScrollable, productImageLayerName);
}
function manageNextPrevButtonVisibility(apiScrollableName, productImageLayerName){
	if(apiScrollableName.getItems().size() <= 3) {
		$("#" + productImageLayerName + " .next").hide();
		$("#" + productImageLayerName + " .prev").hide();
	} else {
		$("#" + productImageLayerName + " .next").show();
		$("#" + productImageLayerName + " .prev").show();
	}
}
function loadZoom(productImageLayerName, productImagesOffset, animationSpeed, topSpace, largeImageSize, siteContentOffsetLeft, siteContentWidth){	
	var currentImage = apiScrollable.getIndex() + 2;
	loadAllXXLImages();
	if($.browser.msie && $.browser.version < 7){
		$("select").hide();
	}
	var overlayMaskLeft = Math.ceil(productImagesOffset.left);
	var overlayMaskTop = Math.ceil(productImagesOffset.top);
	currentImageUrl = $("#" + productImageLayerName + " .productImagesItems > div:nth-child("+currentImage+")").find("img.xxl").attr("src");
	if(currentImageUrl == null){
		currentImageUrl = "";
	}

	$("#overlayMask").attr("src",currentImageUrl).css({
		left: overlayMaskLeft + "px",
		top: overlayMaskTop + "px",
		opacity: 1,
		position: "absolute",
		width: "290px",
		zIndex: 1000000
	}).fadeIn(100).animate({
		borderWidth: 0,
		left: siteContentOffsetLeft + (siteContentWidth - largeImageSize)/2 + "px",
		top: $(window).scrollTop() + topSpace + "px",
		width: largeImageSize + "px"
	},
	animationSpeed,	function(){
		zoomOverlayAPI.load();
	});
}
function onZoomStarted(productImageLayerName, largeImageSize, windowHeight, zoomWindowHeight, zoomXPosition, zoomYPosition, scrollingSpeed) {
	apiScrollable.stop();
	$("#" + productImageLayerName + " .productImagesItems > div").removeClass("zoom-trigger");
	$("#" + productImageLayerName + " .zoom-button").hide();
	$("#" + productImageLayerName + " .enlarge-button").hide();
	$("#" + productImageLayerName + " .reset-button").hide();
	$("#" + productImageLayerName).addClass("zoommodal");
	$("#" + productImageLayerName + " .productImages").css({
		height: zoomWindowHeight,
		borderWidth: "0px" //IE6+7 need this
	});
	$("#" + productImageLayerName + " .productImages div").css({
		height: zoomWindowHeight
	});
	$("#" + productImageLayerName + " .productThumbnails").css("height", windowHeight);
	$("#"+ productImageLayerName).css({
		height: zoomWindowHeight,
		left: zoomXPosition + "px",
		top: zoomYPosition + "px",
		width: largeImageSize + "px"
	});
	$("#" + productImageLayerName + " .xl").css("opacity","0.5");
	$("#" + productImageLayerName + " .xxl").show();
	maintainCurrentImage(productImageLayerName, 0);
}
function onZoomLoaded(productImageLayerName, animationSpeed, scrollingSpeed) {
	if($.browser.msie && $.browser.version < 8){ //to fix z-index bug in IE
		raiseZIndex($("#" + productImageLayerName),"wrapper");
	}

	repositionImageAccordingToMouse($("#" + productImageLayerName + " div.productImagesItems > div"), 0, 0, productImageLayerName);
	$("#overlayMask").animate({
		opacity: 0
	}, animationSpeed, function(){
		$(this).hide();
		$(this).attr("src","");
	});
	$("#" + productImageLayerName + " .up").show();
	$("#" + productImageLayerName + " .down").show();

	isZoomed = true;
}
function closeZoom(productImageLayerName, scrollingSpeed) {
	$("#" + productImageLayerName + " .productImagesItems > div").addClass("zoom-trigger");
	$("#" + productImageLayerName + " .zoom-button").show();
	//$("#" + productImageLayerName + " .enlarge-button").show();
	$("#" + productImageLayerName + " .xl").show();
	$("#" + productImageLayerName + " .productImages").css({
		height: "",
		borderWidth: "1px"
	});
	$("#" + productImageLayerName + " .productThumbnails").css("height", "");
	$("#" + productImageLayerName).removeClass("zoommodal").css({
		display: "block",
		height: "",
		left: "0",
		position: "relative",
		top: "0",
		width: "",
		zIndex:""
	});
	$("#" + productImageLayerName + " .xl").css("opacity","1");
	$("#" + productImageLayerName + " .xxl").hide();

	maintainCurrentImage(productImageLayerName, scrollingSpeed);
	var currentImage = apiScrollable.getIndex() + 1;
	repositionImageAccordingToMouse($("#" + productImageLayerName + " div.productImagesItems > div#image" + currentImage), 0, 0, productImageLayerName);

	$("div.ad-banner").show();
	$("#" + productImageLayerName + " .reset-button").hide();

	if($.browser.msie && $.browser.version < 8){
		resetZIndex($("#" + productImageLayerName),"wrapper");
		if($.browser.version < 7){
			$("select").show();
		}
	}
	$("#" + productImageLayerName + " .up").hide();
	$("#" + productImageLayerName + " .down").hide();
	isZoomed = false;
}
function fixIE8Bug(productImageLayerName, imageWidth) {
	if($.browser.msie && $.browser.version < 9){ //for a bug with the jQuery position function in IE	
		$("#" + productImageLayerName + " .productImagesItems").css("left",Math.round( $("#" + productImageLayerName + " .productImagesItems").position().left / imageWidth ) * imageWidth );
	}
}
$(document).ready(function(){
	xxlImagesLoaded = false;
	var	topSpace = 10;
	var largeImageSize = 800;
	var animationSpeed = 500;
	var scrollingSpeed = 400;
	var siteContentOffsetLeft = $("#wrapper").offset().left;
	var siteContentWidth = $("#wrapper").width();
	apiScrollable = $("#productImageLayer .productImages").scrollable({
		size: 1,
		clickable: false,
		onSeek: function(event, i) {
			repositionImageAccordingToMouse($("div.productImagesItems > div"), 0, 0, "productImageLayer");
			var imageWidth = $("#productImageLayer .productImages").width();
			resetImages(imageWidth, largeImageSize);
			loadXXLImage($(".image"+i));
			fixIE8Bug("productImageLayer", imageWidth);

			var $t = $('.current img');	
			var lrgImagelgth = $t.attr('src').length - 10;
			var lrgImageSrc = $t.attr('src').substr(0, lrgImagelgth) + "large" + $t.attr('src').substr(lrgImagelgth + 5);
			$(".enlarge-button").attr('href', lrgImageSrc);
		},
		speed: scrollingSpeed
	}).autoscroll({interval: 8000, autopause: false, autoplay: false}).circular().navigator({
		navi: ".productThumbnails",
		naviItem: 'a',
		activeClass: 'current',
		api: true
	});
	zoomOverlayAPI = $("#productImageLayer").overlay({
		expose: {
			color: '#000',
			closeSpeed: animationSpeed,
			loadSpeed: animationSpeed,
			maskId: 'productzoomoverlay',
			opacity: 0.5,
			zIndex: 1000000,
			onLoad: function(){
				var productImagesOffset = $("#wrapper").offset();
				if($.browser.msie){ //to fix z-index bug in IE  //&& $.browser.version < 8
					$("#overlayMask,#productzoomoverlay").css({
						left: "-" + productImagesOffset.left+"px",
						top: "0px"
					}).prependTo($(".content_product_images"));
				}
			}
		},
		absolute: false,
		closeOnClick: true,
		onStart: function() {
			apiScrollable.stop();
			var windowOffsetTop = $(window).scrollTop();
			var windowHeight = parseInt($(window).height());
			var zoomWindowHeight = windowHeight - (topSpace * 4);
			var productImagesOffset = $("#wrapper").offset();
			var zoomXPosition = (siteContentWidth - largeImageSize)/2 - productImagesOffset.left + siteContentOffsetLeft;
			var zoomYPosition = 0 - productImagesOffset.top + windowOffsetTop + topSpace;
			onZoomStarted("productImageLayer", largeImageSize, windowHeight, zoomWindowHeight, zoomXPosition, zoomYPosition, scrollingSpeed);
		},
		onLoad: function() {
			apiScrollable.stop();
			onZoomLoaded("productImageLayer", animationSpeed, scrollingSpeed);
		},
		onBeforeClose: function() {
			var currentImage = apiScrollable.getIndex() + 1 + 1;
			var productImagesOffset = $("#content_product_images_box").offset();
			currentImageUrl = $("#productImageLayer .productImagesItems > div:nth-child("+currentImage+")").find("img.xxl").attr("src");
		},
		onClose: function() {
			closeZoom("productImageLayer", scrollingSpeed);
			apiScrollable.play();
		},
		api: true
	});
	manageNextPrevButtonVisibility(apiScrollable, "productImageLayer");
	$("#productImageLayer .reset-button").click(function(){
		var currentImage = apiScrollable.getIndex() + 1;
		repositionImageAccordingToMouse($("#productImageLayer div.image" + currentImage), 0, 0, "productImageLayer");
		defaultImageSize = $("#productImageLayer .productImages").width();
		resetImages(defaultImageSize, largeImageSize); //TODO - could just reset this image
		pageTracker._trackEvent("Product Page", "Button", "Reset");
		return false;
	});
	$(".zoom-button").show().addClass("zoom-trigger");
	//$(".enlarge-button").show().addClass("enlarge-trigger");
	$("#productImageLayer .productImagesItems > div").addClass("zoom-trigger");
	$("#productImageLayer .zoom-trigger").live("click", function(){
		var productImagesOffset = $("#content_product_images_box").offset();
		loadZoom("productImageLayer", productImagesOffset, animationSpeed, topSpace, largeImageSize, siteContentOffsetLeft, siteContentWidth);
		pageTracker._trackEvent("Product Page", "Button", "Zoom");
		return false;
	});
	//$(".enlarge-button").unbind("click").fancybox({
	//	onStart:	function(){
	//		pageTracker._trackEvent("Product Page", "Button", "Enlarge");
	//	}
	//});
	$("#productImageLayer div.productImagesItems > div").live("mousemove", function(event) {
		repositionImageAccordingToMouse($(this), event.pageX, event.pageY, "productImageLayer");
		return false;
	});
	$("#productImageLayer div.productImagesItems > div").mousewheel(function(event, delta){
		resizeImage($(this), largeImageSize, event, delta, "productImageLayer");
		return false;
	});
	loadXXLImage($(".image1"));
	$("body").append("<img id='overlayMask'/>");
	$(".close-popup").bind("click",function(){
		$(".reset-button").click();
		pageTracker._trackEvent("Product Page", "Gallery", "Close Popup");
	});
	$(".productImagesItems").live("mouseover", function(){
		$('.zoom-button').addClass('zoomOn');
	}).live("mouseout", function(){
		$('.zoom-button').removeClass('zoomOn');
	});
	apiScrollable.play();
});