(function($) {
	var site = window.site = {
		data : {
			globalOverlay : null,
			globalOverlaySelector : "#overlayLayer",
			currentWindowSize : [],
			storeLocatorLayerTimer : null,
			storeLocatorOpenLayerTimer : null,
			useBackgroundImage : true,
			backgroundSafteyMargin : 50,
			minSiteWidth : 960,
			minSiteHeight : 0
		},
		func : {
			getLoadingHTML : function() {
				return 	'<div id="genericLoadingLayer" class="layerLayout">' +
						'	<div class="layerContent">' +
						' 		<img src="/assets/images/img/img-ajaxLoader.gif" alt="Loading Content..." />' +
						'	</div>' +
						'</div>';
			},
			leftnavSetup : function(){
				var activeIndex = $("#subcat > li").index($('#subcat > li.active'));
				if ($("#subcat li").size() > 8 && activeIndex < 6 ) {
					$("#subcat li").slice(7).hide();
					$("#subcat .js-show").parent().show();
					$('.js-show').click(function (evt) {
						evt.preventDefault();
						$("#subcat li").show();
						$("#subcat .js-show").parent().hide();
					});
				}
			},
			utils : {
				equalizeHeights : function(elements) {
					var h = 0;
					$(elements).each(function() {
						var newH = $(this).height();
						h = ( newH > h ) ? newH : h;
					});
					$(elements).height(h);
				}
			},
			sizeGrid : function(selector, columns) {
				/* Equalize the heights in each row */
				var rowElements = [];
				var end = $(selector).size() - 1;
				$(selector).each(function(i) {
					if((i%columns == 0) && (i != 0))
					{ 
						site.func.utils.equalizeHeights(rowElements); 
						rowElements = [];
					}
					rowElements.push(this);
					if( i == end )
					{ site.func.utils.equalizeHeights(rowElements); }
				});
				/* ---------------- */
			},
			openGenericLayer : function(url) {
				site.func.globalOverlay.create();
				lib.layer.create("#genericLayer", {
					url : url,
					defaultContent : site.func.getLoadingHTML(),
					method : "post",
					keepCentered : true,
					callback: function() {
						$(".js-closeLayer,"+ site.data.globalOverlaySelector).click(function(evt) {
							evt.preventDefault();
							lib.layer.remove("#genericLayer");
							site.func.globalOverlay.remove();
						});	
					}
				});
			},
			setupFooterEmailSubscribe : function() {
				$("#js-subscribeForm").submit(function(evt){
					evt.preventDefault();
					$("#js-subscribeForm .errorText, #js-subscribeForm .informationText").remove();
					$.post($(this).attr("action"), $(this).serialize(), function(data) {
						$("#js-subscribeForm").append(data);
					});
				});
			},
			setupTooltips : function() {
				$(".js-hasTooltip").unbind("mouseenter.tooltip").unbind("mouseleave.tooltip").bind("mouseenter.tooltip", function() {
					var thisItem = this;
					var pos = lib.utils.getPosition(thisItem)[0];
					var showBelow = ( $(thisItem).hasClass("js-tooltipVertical") ) ? true : false;
					var ttHTML = '<div class="top ie6png"><!-- --></div>' +
								'<div class="mid">' + $(".js-isTooltip", this).html() + "</div>" +
								'<div class="bottom ie6png"><!-- --></div>';
					lib.layer.create("#tooltipLayer", {
						xPos : pos[0],
						yPos : pos[1],
						defaultContent : ttHTML,
						callback : function() {
							if( !showBelow )
							{
								pos[0] = pos[0] - ($("#tooltipLayer").width() / 2) + ($(thisItem).width() / 2);
								pos[1] = pos[1] - $("#tooltipLayer").height() + 10;
							}
							else
							{
								pos[0] = pos[0] - ($("#tooltipLayer").width() / 2) + ($(thisItem).width() / 2);
								pos[1] = pos[1] + $(thisItem).height() - 10;
								$("#tooltipLayer .top").addClass("topBelow");
								$("#tooltipLayer .bottom").addClass("bottomBelow");
							}
							$("#tooltipLayer").css({left : pos[0]+"px", top : pos[1]+"px"}).show();
						}
					});
					
				}).bind("mouseleave.tooltip",function() {
					lib.layer.remove("#tooltipLayer");
				});
			},
			setupRefinements : function() {
				$("#refinementOptions a").click(function(evt) { evt.preventDefault(); });
				/* setup the accordian functionality */
				$("#refinementOptions > li > a").toggle(
					function() {
						$(this).parent().addClass("opened");
						$("ul", $(this).parent()).slideDown(350);
					},
					function(evt) {
						$(this).parent().removeClass("opened");
						$("ul", $(this).parent()).slideUp(350);
					}
				);
				$("#refinementOptions > li.opened > a").click();
				/* -------------- */
				/* Setup the active functionality for the checkboxes for visual */
				$("#refinementOptions input[type=checkbox]").click(function(evt) {
					if( $(this).attr("checked") )
					{ $(this).parent().addClass("active"); }
					else
					{ $(this).parent().removeClass("active"); }
				});
				$("#refinementOptions input[type=checkbox][checked]").parent().addClass("active");
				/* --------------------- */
			},
			setupQuicklook : function() {
				$(".js-quicklookItem").unbind("click.quicklookItem").unbind("mouseenter.quicklookItem").unbind("mouseleave.quicklookItem");
				$(".js-quicklookItem").css({position: "relative", width: "100%"}).bind("mouseenter.quicklookItem", function() {
					var qlHTML = '<span class="js-quicklookButton quicklookButton"><a href=" ' + $(".js-quickLookItemURL", this).attr("href") + '"><img src="/assets/images/btn/btn-quickview.gif" width="72" height="22" border="0" /></a></span>';
					$(this).append(qlHTML);
					$(".js-quicklookButton a").click(function(evt) {
						evt.preventDefault(); 
						site.func.openQuicklook($(this).attr("href"));
					});
				}).bind("mouseleave.quicklookItem", function() {
					$(".js-quicklookButton").remove();
				});
			},
			openQuicklook : function(url) {
				site.func.globalOverlay.create();
				lib.layer.create("#genericLayer", {
					url : url,
					defaultContent : site.func.getLoadingHTML(),
					method : "post",
					keepCentered : true,
					callback : function() {
						/* setup overlay and close button */
						$(".js-closeLayer,"+ site.data.globalOverlaySelector).click(function(evt) {
							evt.preventDefault();
							site.func.closeQuicklook();
						});	
						/* -------------------- */
					}
				});
			},
			closeQuicklook : function() {
				lib.layer.remove("#genericLayer");
				site.func.globalOverlay.remove();
			},
			setupPagination : function() {
				$(".js-paginationSort option[value=" + $.browser.queryParams["sortByColumnName"] + "]").attr("selected", "true");
				$(".js-paginationSort").change(function(evt){
					/* where did these functions come from? */
					$.browser.queryParams["sortByColumnName"] = this.options[this.selectedIndex].value;
					window.location = $.browser.serializeQueryParams() + "#sortBy";
					//alert($.browser.serializeQueryParams() + "#sortBy")
				});
			},
			bodyBackground : {
				setupResizing : function() {
					/* Only need to resize if a background image exists */
					if( site.data.useBackgroundImage )
					{
						var windowSizeTimeout = null;
						$(window).bind("resize.background_sizing", function() {
							clearTimeout(windowSizeTimeout);
							windowSizeTimeout = setTimeout(function() {
								site.func.bodyBackground.updateBackground();
							}, 100 );
						});
					}
				},
				createBackgroundURL : function(settings) {
					var settings = $.extend({
						baseURL : "",
						wid : 0,
						sharpen : 1
					}, settings);
					
					var url = settings.baseURL + "?wid=" + settings.wid + "&sharpen=" + settings.sharpen;
					return url;
				},
				updateBackground : function() {
					var newWindowSize = lib.screen.size();
					newWindowSize[0] = (newWindowSize[0] < site.data.minSiteWidth) ? site.data.minSiteWidth : newWindowSize[0];
					var maxWithoutUpdate = site.data.currentWindowSize[0] + site.data.backgroundSafteyMargin;
					var minWithoutUpdate = site.data.currentWindowSize[0] - site.data.backgroundSafteyMargin;
					if( (newWindowSize[0] > maxWithoutUpdate) || (newWindowSize[0] < minWithoutUpdate) )
					{
						site.data.currentWindowSize = newWindowSize;
						var newBaseURL = $("body").css("background-image").split("url(")[1].split("?")[0];
						var bgURL = site.func.bodyBackground.createBackgroundURL({
							wid : (newWindowSize[0] + site.data.backgroundSafteyMargin),
							baseURL : newBaseURL
						});
						$("body").css("background-image", "url(" + bgURL + ")");
					}
				}
			},
			globalOverlay : {
				create : function() {
					if( site.data.globalOverlay == null )
					{ site.data.globalOverlay = new lib.obj.pageOverlay({selector : site.data.globalOverlaySelector}); }
					else
					{ 
						site.func.globalOverlay.remove(); 
						site.data.globalOverlay.addOverlay();
					}
				},
				remove : function() {
					if( site.data.globalOverlay != null )
					{ site.data.globalOverlay.removeOverlay(); }
				}
			},
			setupRecentlyViewed : function() {
				var recentlyViewedSlider = null;
				$("#js-activateRecentlyViewed").toggle(
					function(evt) {
						evt.preventDefault();
						$("#js-recentlyViewedContainer").addClass("recentlyViewedItemsOpen");
						$("#js-recentlyViewedSlider").slideDown("slow", function() { });
						
						if( recentlyViewedSlider == null )
						{ 	
							recentlyViewedSlider = new lib.obj.itemSlider({
								viewport: "#js-recentlyViewedSlider .viewport",
								content: "#js-recentlyViewedSlider .content",
								next: "#js-recentlyViewedSlider .next a",
								prev: "#js-recentlyViewedSlider .prev a",
								item: "#js-recentlyViewedSlider .item",
								direction: "horizontal",
								showAmount: 1,
								scrollAmount : 1      
							});
						}
					},
					function(evt) {
						evt.preventDefault();
						$("#js-recentlyViewedSlider").slideUp("slow", function() {
							$("#js-recentlyViewedContainer").removeClass("recentlyViewedItemsOpen");
						});
					}
				);
			},
			priceManipulation : {
				initVariantPricing : function(scope) {
					/* Setup Variant Prices */ 
					$(scope + " .VariantMatrix").each(function(i) {
						$(this).widgetBind("updatevariant", function(evt, productId, variantId, selectedVariant, saleOnly) {
							// ugly assignment ensuring same targeting for sale and non-sale variants
							if (saleOnly && i==1) { i = 0; }
							var priceParent = $(".js-price:eq(" + i + ")");
							if( selectedVariant != null ) /* Show Variant Price */
							{
								/* Show as Sale or as Normal */
								var priceHTML = '<p class="pricing"><span class="productPriceNormal">' + selectedVariant.props.price + '</span></p>';
								if( (selectedVariant.props.salePrice != null) && (selectedVariant.props.salePrice != "$0.00") )
								{ priceHTML = '<p class="pricing"><span class="productPriceOld">' + selectedVariant.props.price + '</span>&nbsp;&nbsp;<span class="productPriceSale">' + selectedVariant.props.salePrice + '</span></p>'; }
								/* ------------------- */
								
								$(".js-defaultPrice", priceParent).hide();
								$(".js-variantPrice", priceParent).html(priceHTML).show();
							} else if (variantId == -1 && selectedVariant == null) 
							{
								//do nothing due to more updatevariant events now firing from the VariantMatrixWidget.js
							} else /* Show Default Price */
							{
								$(".js-variantPrice", priceParent).hide();
								$(".js-defaultPrice", priceParent).show();
							}
						});
					});
					/* ----------- */
				}
			},
			imageManipulation : {
				initProductImages : function(scope, settings) {
					var settings = $.extend({
						justSwatches : false,
						defaultColor : "",
						imageParams : null
					}, settings);
					
					if( !settings.justSwatches ) 
					{
						/* Intialize variant Pricing */
						site.func.priceManipulation.initVariantPricing(scope);
						
						/* Create Scene7 Viewers */
						var viewers = scene7.func.initViewers(scope, settings.imageParams);
						
						/* Zoom In/Out buttons */
						$(scope + " .js-zoomControls").each(function(i) {
							
							/* setup the buttons */
							$("a img", this).each(function() {
								var imgOff = $(this).attr("src");
								var imgOn = $(this).attr("src").split("_off")[0] + "_on.gif";
								new lib.obj.button({
									off: imgOff,
							        hover: imgOn,
						        	buttonSelector: this,
						        	buttonCollectionSelector : ".js-zoomControls a img"
								});
							});
							/* ---------------- */
							
							/* Setup the Zoom In/Out */
							$("a", this).click(function(evt) {
								evt.preventDefault();
								if( $(this).is(".js-zoomIn") )
								{ scene7.func.zoomIn(viewers[i]); }
								else
								{ scene7.func.zoomOut(viewers[i]); }
							});
							/* ------------------- */
							
						});
						/* ------------------ */
						
						
					}
					
					$(scope + " .js-swatches").each(function(i) {
						var thisCollection = this;
						var variantSelector = ".COLOR_NAME ." + $(this).attr("id");
						if (variantSelector.substring((variantSelector.length - 4)) != "sale") {
							var otherVariantSelector = variantSelector + "-sale";
							var saleOnly = false;
						} else {
							var otherVariantSelector = variantSelector.substr(0, (variantSelector.length - 5));
							var saleOnly = true;
						}
											
						/* Swatch as Button */
						new lib.obj.button({
							hasClick: true,
				        	activeId: "js-activeSwatch",
				        	cssButton: true,
				        	cssOff: "swatchOff",
				        	cssOn: "swatchOn",
				        	cssHover: "swatchOn",
				        	buttonSelector: $(".js-aSwatch", thisCollection),
				        	buttonCollectionSelector : $(".js-aSwatch", thisCollection)
						});
						/* ------------------ */
						
						/* Click Swatch */
						$(".js-aSwatch", this).unbind("click.swatches").bind("click.swatches", function(evt) {
							evt.preventDefault();
							var color = $("img", this).attr("alt");
							site.func.imageManipulation.updateColorDropdown(variantSelector, color);
						});
						/* ------------- */
						
						/* Setup the Dropdown [everything runs through this] */
						if( !settings.justSwatches )
						{
							$(variantSelector).unbind("change.swatches").bind("change.swatches", function() {
								var color = $(this).val();
								if( color != "")
								{
									site.func.imageManipulation.resetColorDropdown(otherVariantSelector);
									// ugly assignment ensuring same targeting for sale and non-sale variants
									if (saleOnly && i==1) { i = 0; }
									var sku = $(".js-aSwatch [alt=" + $(this).val() + "]", thisCollection).attr("id");
									var variantInStock = $(".js-aSwatch [alt=" + $(this).val() + "]", thisCollection).attr("class");
									site.func.imageManipulation.updateViewer( viewers, sku, i);
									site.func.imageManipulation.updateColorSwatch(thisCollection, color);
									site.func.imageManipulation.updateColorName(scope, color, i);
									site.func.imageManipulation.updateSku(scope, sku, i);
									$("div[class^='js-inventory-']").css('display','none');
									$(".js-inventory-" + sku ).css('display','block');

									if(variantInStock == "true"){
										$(".productInStockDetails").css('display','block');
										$(".productNotInStockDetails").css('display','none');
									} else if (variantInStock == "false") {
										$(".productInStockDetails").css('display','none');
										$(".productNotInStockDetails").css('display','block');
									}
									site.func.imageManipulation.createMoreViews(scope, sku, i, null, viewers);
								}
							}).change();
						}
						/* -------------------- */
						
						/* Setup the See More link */
						$(".js-swatchesSeeMore", this).unbind("click.swatchesSeeMore").bind("click.swatchesSeeMore", function(evt) {
							evt.preventDefault();
							var pos = lib.utils.getPosition(this)[0];
							site.func.imageManipulation.showSwatchLayer( $(this).attr("href"), pos[0], pos[1], $(variantSelector).val() );
						});
						/* --------------------- */
						
						/* Setup the default showing swatch */
						if( settings.defaultColor != "")
						{ 
							if( !settings.justSwatches )
							{ site.func.imageManipulation.updateColorDropdown(variantSelector, settings.defaultColor); }
							
							var defaultSwatch = $(".js-aSwatch [alt=" + settings.defaultColor + "]", thisCollection).parent();
							$(defaultSwatch).triggerHandler("click.button"); 
						}
						/* ---------------- */
					});
				},
				createMoreViews : function(scope, sku, i, views, viewers) {
					if( views != null )
					{ 
						if( views.length > 0 )
						{
							var viewHTML = "";
							for( var x = 0; x < views.length; x++)
							{ viewHTML += '<li><a class="js-aView" href="#"><img src="' + views[x] + '" alt="" /></a></li>'; }
							$("ul", $(scope + " .js-moreViews").eq(i)).html(viewHTML);
							$(scope + " .js-moreViews").eq(i).show();
							
							/* CSS BUTTON */
							new lib.obj.button({
								hasClick: true,
					        	activeId: "js-activeView",
					        	cssButton: true,
					        	cssOff: "viewOff",
					        	cssOn: "viewActive",
					        	cssHover: "viewHover",
					        	buttonSelector: $(".js-aView", $(scope + " .js-moreViews").eq(i)),
					        	buttonCollectionSelector : $(".js-aView", $(scope + " .js-moreViews").eq(i))
							});
							/* ----------------- */
							
							/* Add Events for the alternate Views */
							$(".js-aView", $(scope + " .js-moreViews").eq(i)).bind("click.views", function(evt) {
								evt.preventDefault();
								var image = $("img", this).attr("src").split("?")[0];
								image = image.split("/");
								image = image[image.length-1];
								site.func.imageManipulation.updateViewer(viewers, image, i);
							}).eq(0).triggerHandler("click.button");
							/* -------------------- */
						}
						else
						{ $(scope + " .js-moreViews").eq(i).hide(); }
					}
					else
					{	
						/* Request From Scene7 */
						scene7.func.getMoreViews(scope, sku, i, viewers);
					}
				},
				resetColorDropdown : function(variantSelector) {
					$(variantSelector).val("").change();
				},
				updateColorDropdown : function(variantSelector, color) {
					$(variantSelector).val(color).change();
				},
				updateColorSwatch : function(swatchCollectionSelector, color) {
					$(".js-aSwatch [alt=" + color + "]", swatchCollectionSelector).parent().triggerHandler("click.button");
				},
				updateViewer : function(viewers, sku, i) {
					scene7.func.changeImage(viewers[i], sku);
				},
				updateColorName : function( scope, colorName, index ) {
					$(scope + " .js-productColorName").eq(index).text(colorName);
				},
				updateSku : function( scope, sku, i ) {
					$(scope + " .js-sku").eq(i).text(sku);
				},
				showSwatchLayer : function(colorsURL, x, y, currentColor) {
					lib.layer.create("#swatchLayer", {
						url : colorsURL,
						method : "get",
						xPos : x,
						yPos : y,
						callback : function() {
							/* Create Background Overaly */
							var overlay = new lib.obj.pageOverlay({selector : "#overlayLayer2"});
							$("#swatchLayer .js-aSwatch, #swatchLayer .js-closeLayer, #overlayLayer2").click(function(evt) {
								evt.preventDefault();
								setTimeout(function() {
									lib.layer.remove("#swatchLayer");
									overlay.removeOverlay()
								}, 250);
							});
							
							/* Setup the Swatches */
							site.func.imageManipulation.initProductImages("#swatchLayer", { justSwatches : true, defaultColor : currentColor });
						}
					});
				}
			}
		},
		obj : {
			
			
		}
	};
})($);

$(function() {
	
	/* Preload the Loading Graphic */
	lib.image.preload("/assets/images/img/img-ajaxLoader.gif");
	/* -------------------- */
	
	/* Setup Window Resizing */
	site.func.bodyBackground.setupResizing();
	/* ---------------- */
	
	
	
	/* Setup the search keyword input */
	lib.input.defaultText(".js-searchKeyword", { defaultText : "keyword or item #" });
	/* ----------- */
	
	/* Setup Recently Viewed */
	site.func.setupRecentlyViewed();
	/* ------------ */
	
	/* Setup Pagination */
	site.func.setupPagination();
	/* ------------- */
	
	/* Setup QuickLook */
	site.func.setupQuicklook();
	/* ------------- */

	/* Setup Refinements */
	site.func.setupRefinements();  
	/* ------------- */
	
	/* Setup the footer Email Subscription */
	site.func.setupFooterEmailSubscribe();
	/* --------------- */

	/* Setup left navigation Show All link */
	site.func.leftnavSetup();
	/* --------------- */
	
	/* Setup Store Locator Layer */
	$(".js-storeLocatorLink").bind("mouseenter", function() {
		var linkObj = this;
		site.data.storeLocatorLayerTimer = setTimeout(function() { 
			var layerURL = $(linkObj).attr("href").split("store_content.jsp")[0] + "store_locator_layer.jsp";
			var pos = lib.utils.getPosition(linkObj)[0];
			lib.layer.create("#genericLayer", {
				url : layerURL,
				xPos : pos[0]+150,
				yPos : pos[1]
			});
		}, 0); 
	}).bind("mouseleave", function() { 
		clearTimeout(site.data.storeLocatorLayerTimer); 
	});
	/* ---------------- */
	
	/* Setup any tooltips */
	site.func.setupTooltips();
	/* ----------------- */
	
	/* Setup any print links */
	$(".js-defaultPrint").click(function(evt) {
		evt.preventDefault();
		window.print();
	});
	/* ---------------- */
});

