// Check to see if the function Exists
jQuery.fn.exists = function(){
	return jQuery(this).length > 0;
}

var blank = "/swappler_data/store_templates/arnsdorfnyc/templates/images/blank.png";
var loaderAnimation = "/swappler_data/store_templates/arnsdorfnyc/templates/images/loader.gif";
var loadingClass = "loading";
var fadeSpeed = "fast";
var noLazyLoadingClass = "no-lazy-loading";

$.expr[':'].loaded = function(obj) {
	var o = $(obj);
	if(!o.hasClass(noLazyLoadingClass))
		return o.attr("src") == o.attr("original");
		
	return true;
}; // loaded

var initLazyLoading = function() {
	var toLazyLoad = $("img").not(":loaded");

	toLazyLoad.addClass(loadingClass);
		
	toLazyLoad.lazyload({
		placeholder: blank,
		effect: "fadeIn",
		threshold : 700
	}); // lazyload
}; // initLazyLoading

var initInfiniteScroll = function(executed) {
	$('#scrapbook > div:first').infinitescroll({
		navSelector  : "div.pagination",            
		nextSelector : "span#nextBtn a",    
		itemSelector : "#scrapbook > div img",
		loadingImg   : loaderAnimation,
		loadingText  : "",
		donetext     : ""
	}, executed); // infinitescroll
}; // initInfiniteScroll


var initIndex = function() {
	var imgs = $("#home img");
	var loaders = $(".loading");
	
	loaders.show();
	imgs.hide();
	
	imgs.one('load', function() {
		var img = $(this);
		img.parent().prev().fadeOut(fadeSpeed, function() {
			img.fadeIn(fadeSpeed);
		}); // fadeOut
	}).each(function() {
		if(this.complete) $(this).load();
	}); // each
}; // initIndex

var initAbout = function() {
	var imgs = $("#about #pane-right img");
	var loaders = $(".loading");
	
	loaders.show();
	imgs.hide();

	imgs.one('load', function() {
		var img = $(this);
		img.next().fadeOut(fadeSpeed, function() {
			img.fadeIn(fadeSpeed);
		}); // fadeOut
	}).each(function() {
		if(this.complete) $(this).load();
	}); // each
}; // initAbout

var lockedImage = null;

var initImagePreview = function() {
	var mask = $("#thumbs #table #mask");
	var viewImage = $("#pane-right img");
	var view = $("#pane-right div");
	var loader = $("div.loading");
	var lastActiveImage = null;
	var imgCount = -1;
	var images = new Array();
	var lockedIndex = 0;
	var imageIndex = 0;
	var arrowImageLeft = $("#pane-right .arrow-left");
	var arrowImageRight = $("#pane-right .arrow-right");
	
	mask.css("opacity", 0.25); // do not change the opacity
	view.show();
	loader.hide();
	arrowImageLeft.hide();
	arrowImageRight.hide();

	var maskMove = function(img) {
		mask.offset({top: $(img).offset().top, left: $(img).offset().left});
	}; // maskMove
	
	arrowImageLeft.click(function() {
		imageIndex--;
		changeView(lockedImage);
	}); // click
	
	arrowImageRight.click(function() {
		imageIndex++;
		changeView(lockedImage);
	}); // click

	var changeView = function(elem) {
		var targetImage;
		var imageExists = -1;
		var hiddenImages = $(elem).siblings("input").get();
		var hiddenImagesCount = $(elem).siblings("input").length;
		var peach = $("#pane-right #peach");
		var peachContent = $(elem).siblings("ul");
		
		imageIndex = (imageIndex < 0) ? 0 : imageIndex;
		imageIndex = (imageIndex > hiddenImagesCount - 1) ? hiddenImagesCount - 1 : imageIndex;
		
		var src = $(hiddenImages[imageIndex]).val();

		if(src == lastActiveImage)
			return;

		if(peachContent.exists()) {
			peach.children().remove();
			peachContent.children().clone().appendTo(peach);
			
			var t = ($(window).height() - peach.height()) / 2;
			peach.css({top: t});

			peach.attr("data-show", true);
		} else {
			peach.attr("data-show", false);
		}
		

		var arrow = function(l, r) {
			var v = "visible";
			var h = "hidden";

			arrowImageLeft.css("visibility", l ? v : h);
			arrowImageRight.css("visibility", r ? v : h);
		};

		if(typeof(elem) != "undefined") {
			if(hiddenImagesCount > 1) {
				if(imageIndex == 0)
					arrow(false, true);
				else if (imageIndex == hiddenImagesCount - 1)
					arrow(true, false);
				else
					arrow(true, true);
				}
			else
				arrow(false, false);
		}
			
		lastActiveImage = src;
		
		for(i = 0; i < imgCount + 1; i++)
			if(images[i].src == src) {
				imageExists = i;
				break;
			}

		if(imageExists > -1) {
			targetImage = images[imageExists];
			
			viewImage.attr("src", src);
			view.show();
			loader.hide();
		} else {
			imgCount++;
			images[imgCount] = new Image();
			targetImage = images[imgCount];

			view.hide();
			loader.show();

			$(targetImage).load(function() {
				tSrc = $(this).attr("src");
				if(tSrc == lastActiveImage) {
					viewImage.attr("src", tSrc);
					view.show();
					loader.hide();
				}
			});
		}

		targetImage.src = lastActiveImage;
	}; // changeView
						
	$("#thumbs #table > div img").click(function() {
		lockedImage = $(this);
		lockedIndex = 0;
		imageIndex = 0;
		
		maskMove(this);
	}); // click
	
	$("#thumbs #table > div img").hoverIntent({
		over: function() {
				if(imageIndex != 0)
					lockedIndex = imageIndex;
				imageIndex = 0;
				
				changeView(this);
			},
		out: function() {
			},
		interval: 200
	}); // hoverIntent
	
	$("#thumbs #table").mouseleave(function() {
		if(lockedIndex != 0)
			imageIndex = lockedIndex;

		changeView(lockedImage);
	}); // mouseleave
	
	$("#mask").mouseenter(function() {
		changeView(lockedImage);
	}); // mouseenter
	
	var tableArrowLeft = $("#thumbs .arrow-left");
	var tableArrowRight = $("#thumbs .arrow-right");
	var colIndex = 0;	
	var cols = $("#table .col");
	var colsLength = cols.length;

	var firstThumb = function() {
		fImg = $("#col" + (colIndex+1) + " #first img");
		lockedImage = fImg;
		lockedIndex = 0;
		
		changeView(fImg);
		maskMove(fImg);
	}; // firstThumb
	
	firstThumb();
	
	var arrow = function(l, r) {
		var v = "visible";
		var h = "hidden";

		tableArrowLeft.css("visibility", l ? v : h);
		tableArrowRight.css("visibility", r ? v : h);
	};
		
	tableArrowLeft.click(function() {
		colIndex--;
		imageIndex = 0;
				
		updateThumbs();
		firstThumb();
	});
	
	tableArrowRight.click(function() {
		colIndex++;
		imageIndex = 0;

		updateThumbs();
		firstThumb();
	});
	
	var updateThumbs = function() {
		colIndex = (colIndex < 0) ? 0 : colIndex;
		colIndex = (colIndex > colsLength - 1) ? colsLength - 1 : colIndex;

		if(colsLength > 1)	{
			if(colIndex == 0)
				arrow(false, true);
			else if(colIndex == colsLength - 1)
				arrow(true, false);
			else
				arrow(true, true);
		} else
			arrow(false, false);
		
		cols.hide();
		$("#col" + (colIndex + 1)).show();
	};
	
	updateThumbs();
}; // initImagePreview

var initCollections = function() {
	var peach = $("#pane-right #peach");
	peach.hide();
	
	initImagePreview();
	
	$("#pane-right").mouseenter(function() {
		if(peach.attr("data-show") == "true")
			peach.fadeIn(fadeSpeed);
	}); // mouseenter
	
	$("#pane-left").mouseenter(function() {
		if(peach.attr("data-show") == "true")
			peach.fadeOut(fadeSpeed);
	}); // mouseenter
	
	var windowResized = function () {
		var lockedUl = lockedImage.siblings("ul");
		
		if(!lockedUl.exists())
			lockedUl = $("#peach1 ul");
		
		var top = ($(window).height() - lockedUl.height()) / 2;
		peach.css({top: top});
	}
	
	windowResized();
	$(window).resize(windowResized);
};

var initPress = function() {
	initImagePreview();	

	$("#table > div > div").hoverbox();

	var initHeight = function() {
		var h = $("#press > #pane-right > div:last").height();
		var w = h * 960 / 1440;
		var minWidth = parseFloat($("body").css("min-width")) / 2;
		
		w = w > minWidth ? w : minWidth;

		$("#press > #pane-right > div:last").width(w);
	};
		
	initHeight();
	
	$(window).resize(initHeight);
	$(window).load(initHeight);
};

var initDesigners = function() {
	var windowResized = function() {
		var picturebox = $("#picturebox");
		var w = picturebox.width();
		var h = w / 985 * 352;
		picturebox.height(h);
		
		var paddingTop = ($(window).height() - picturebox.height()) / 2;
		$("#designers").css("padding-top", paddingTop);
	};
	
	var images = new Array();
	var inputs = $("#picturebox input").get();
	var loader = $("#picturebox .loading");
	var view = $("#picturebox div:last");
	var viewImage = $("#picturebox div img");
	var arrowLeft = $("#picturebox .arrow-left");
	var arrowRight = $("#picturebox .arrow-right");
	var imageIndex = 0;
	var hiddenImagesCount = inputs.length;
	var imgCount = -1;
	
	var changeView = function() {
		var src = $(inputs[imageIndex]).val();
		var imageExists = -1;
		
		loader.show();
		view.hide();
		
		imageIndex = (imageIndex < 0) ? 0 : imageIndex;
		imageIndex = (imageIndex > hiddenImagesCount - 1) ? hiddenImagesCount - 1 : imageIndex;

		var arrow = function(l, r) {
			var v = "visible";
			var h = "hidden";

			arrowLeft.css("visibility", l ? v : h);
			arrowRight.css("visibility", r ? v : h);
		};
		
		if(hiddenImagesCount > 1) {
			if(imageIndex == 0)
				arrow(false, true);
			else if (imageIndex == hiddenImagesCount - 1) 
				arrow(true, false);
			else
				arrow(true, true);
		} else
			arrow(false, false);
		
		for(i = 0; i < imgCount; i++)
			if(images[i].src == src) {
				imageExists = i;
				break;
			}

		if(imageExists > -1) {
			loader.hide();
			view.show();
			viewImage.attr("src", images[imageExists].src);		
		} else {
			imgCount++;
			images[imgCount] = new Image();
			
			$(images[imgCount]).load(function() {
				viewImage.attr("src", $(this).attr("src"));
				loader.hide();
				view.show();
			});		

			images[imgCount].src = src;
		}
	}; // changeView
	
	arrowLeft.click(function() {
		imageIndex--;
		changeView();
	});
	
	arrowRight.click(function() {
		imageIndex++;
		changeView();
	});
	
	changeView();
	
	windowResized();
	$(window).resize(windowResized);
}; // initDesigners

var initScrapbook = function() {	
	var initImageHeights = function() {
		$("#scrapbook img").each(function(i) {
			var h = $(this).attr("data-height");
			var w = $(this).attr("data-width");
			$(this).css("min-height", h * 0.5);
			$(this).css("max-height", h);
			$(this).css("min-width", w * 0.5);
			$(this).css("max-width", w);
		}); // each
	}; // initImageHeights

	var infiniteScrollExecuted = function() {
		initLazyLoading();
		initImageHeights();
	}; // infiniteScrollExecuted

	initInfiniteScroll(infiniteScrollExecuted);
	initImageHeights();
	
	var windowResized = function() {
		$("#scrapbook img").each(function(i) {
			var h = $(this).attr("data-height") * $(window).height() / screen.height;
			var w = $(this).attr("data-width") * h / $(this).attr("data-height");
			$(this).height(h);
			$(this).width(w);
		}); // each
	}; // windowResized

	initImageHeights();
	windowResized();
	$(window).resize(windowResized);	
 }; // initScrapbook

var initStore = function() {
	$("a.store_thumb").hoverbox();
	
	var initThumbs = function() {
		$("span.img_0").stop().show();
		$("span.img_1").stop().hide();
	}; // initThumbs
	
	initThumbs();
	
	$("span.img_0").mouseenter(function() {
		if($(this).next().exists()) {
			initThumbs();			
			$(this).hide();
			$(this).next().show();
		}
	}); // mouseenter
	
	$("span.img_1").mouseleave(function() {
		initThumbs();
		$(this).hide();
		$(this).prev().show();
	}); // mouseleave
}; // initStore

var newBG = function() {
	var zoomBig = $("#pane-right div#cloud-zoom-big");
	var viewImage = $("#pane-right img");
	var zoomSrc = viewImage.attr("src");
	zoomSrc = "url('" + zoomSrc + "')";
	zoomBig.css("background-image", zoomSrc);
};

var initStoreItem = function()
{
	$('#VariationQuantity').val('Quantity').focus(function() {
	if ($(this).val() == 'Quantity') {
			$(this).val('');
		}
	}).blur(function() {
		if ($(this).val() == '') {
			$(this).val('Quantity');
		}
	});
	
	$("input#add_to_cart").val("Add to Shopping Cart");
	var variation = $("select#VariationId option").text();
	$("select#VariationId option").text(variation.toLowerCase());

	var viewImage = $("#pane-right img");
	var view = $("#pane-right div");
	var loader = $("div.loading");
	var images = new Array();
	var imageIndex = 0;
	var imageInputs = $("#pane-right input").get();
	var imageInputsCount = imageInputs.length;
	var imagesCount = -1;
	var imageExists = -1;
	var targetImage;
	var arrowImageLeft = $("#pane-right .arrow-left");
	var arrowImageRight = $("#pane-right .arrow-right");
		
	arrowImageLeft.click(function() {
		imageIndex--;
		changeView();
	}); // click
	
	arrowImageRight.click(function() {
		imageIndex++;
		changeView();
	}); // click

	view.hide();
	loader.show();
	
	var initHeight = function() {	
		var h = $("#store_item > #pane-right > div:last").height();
		var w = h * 960 / 1440;
		var minWidth = parseFloat($("body").css("min-width")) / 2;
		
		w = w > minWidth ? w : minWidth;
		
		$("#store_item > #pane-right > div:last").width(w);
	};
	
	var changeView = function() {
		imageIndex = (imageIndex < 0) ? 0 : imageIndex;
		imageIndex = (imageIndex > imageInputsCount - 1) ? imageInputsCount - 1 : imageIndex;

		var src = $(imageInputs[imageIndex]).val();
		
		view.hide();
		loader.show();

		var arrow = function(l, r) {
			var v = "visible";
			var h = "hidden";

			arrowImageLeft.css("visibility", l ? v : h);
			arrowImageRight.css("visibility", r ? v : h);
		};

		if(imageInputsCount > 1) {
			if(imageIndex == 0)
				arrow(false, true);
			else if (imageIndex == imageInputsCount - 1)
				arrow(true, false);
			else
				arrow(true, true);
		} else
			arrow(false, false);
		
		for(i = 0; i < imagesCount; i++)
			if(images[i].src == src) {
				imageExists = i;
				break;
			}
				
		if(imageExists > -1) {
			targetImage = images[imageExists];
			
			viewImage.attr("src", src);
			view.show();
			loader.hide();
		} else {
			imagesCount++;
			images[imagesCount] = new Image();
			targetImage = images[imagesCount];

			$(targetImage).load(function() {
				viewImage.attr("src", $(this).attr("src"));
				view.show();
				loader.hide();
			});
		}
		
		targetImage.src = src;
	};
		
	initHeight();
	
	changeView();
	
	$(window).resize(initHeight);
};

var initNewsletter = function()
{
	$('#StoreSubscriberFirstName').val('First Name').focus(function() {
	if ($(this).val() == 'First Name') {
			$(this).val('');
		}
	}).blur(function() {
		if ($(this).val() == '') {
			$(this).val('First Name');
		}
	});
	
	$('#StoreSubscriberLastName').val('Last Name').focus(function() {
	if ($(this).val() == 'Last Name') {
			$(this).val('');
		}
	}).blur(function() {
		if ($(this).val() == '') {
			$(this).val('Last Name');
		}
	});
	
	$('#StoreSubscriberEmail').val('Email').focus(function() {
	if ($(this).val() == 'Email') {
			$(this).val('');
		}
	}).blur(function() {
		if ($(this).val() == '') {
			$(this).val('Email');
		}
	});
};
 
var stickLeft = function(selectors, leftPadding, width) {
	var minWidth = parseFloat($("body").css("min-width"));
	$(selectors).each(function() {
		if($(window).width() < minWidth)
			$(this).css({
				left: -($(window).scrollLeft() - leftPadding),
				right: "auto"
			});
		else
			$(this).css({
				left: leftPadding,
				right: "auto"
			});
			
		if(typeof(width) != 'undefined')
			$(this).width(width);
	});	// each
}; // stickLeft

var stickTop = function(selectors, topPadding, height) {
	var minHeight = parseFloat($("body").css("min-height"));
	$(selectors).each(function() {
		if($(window).height() < minHeight)
			$(this).css({
				top: -($(window).scrollTop() - topPadding),
				bottom: "auto"
			});
		else
			$(this).css({
				top: topPadding,
				bottom: "auto"
			});
			
		if(typeof(height) != 'undefined')
			$(this).height(height);
	});	// each
}; // stickTop

var stickRight = function(selectors, rightPadding, width) {
	var minWidth = parseFloat($("body").css("min-width"));
		$(selectors).each(function() {
			if($(window).width() < minWidth)
				$(this).css({
					left: minWidth - $(window).scrollLeft() - $(this).width() - rightPadding - 1,
					right: "auto"
				});
			else
				$(this).css({
					left: "auto",
					right: rightPadding
				});

			
		if(typeof(width) != 'undefined')

			$(this).width(width);
	});	 // each
}; // stickRight

var stickBottom = function(selectors, bottomPadding, height) {
	var minHeight = parseFloat($("body").css("min-height"));
		$(selectors).each(function() {
			if($(window).height() < minHeight)
			{
				$(this).css({
					top: $(window).height() - $(window).scrollTop() - $(this).height() + bottomPadding - 1,
					bottom: "auto"
				});
			}
			else
				$(this).css({
					top: "auto",
					bottom: bottomPadding,
				});
			
		if(typeof(height) != 'undefined')
			$(this).height(height);
	});	 // each
}; // stickBottom

// Change Main image on Store view
function display_img(thumb_src, full_src, target, index) {
	$('.altimg').attr({
		"class" : "altimg"
	});
	$('#alt_img_' + index).attr({
		"class" : "altimg active"
	});
	$('#' + target + ' > div > a').attr({
		"href" : full_src
	});
	$('#' + target + ' > div > a > img').attr({
		"src" : thumb_src
	});
	$('.cloud-zoom, .cloud-zoom-gallery').CloudZoom();
}

$(document).ready(function(){
	$("#logo img").addClass(noLazyLoadingClass);

	initLazyLoading();

	widthBag = $("#bag").width();
	widthTerms = $("#terms").width() + 1;
	
	var stickFooterHeader = function() {
		stickLeft("#logo, #menu", 20);

		stickRight("#bag", 20, widthBag);
		stickRight("#terms", 20, widthTerms);

		//stickTop("#logo, #bag", 20);
		//stickBottom("#menu, #terms", 20);
	};
	
	stickFooterHeader();
	$(window).resize(stickFooterHeader);
	$(window).scroll(stickFooterHeader);
	
});

