(function($) {
	var site = window.site = function() {
		return {
			data : {
				searchFieldText : "Enter keyword or item #",
				fieldHighlightClass : "FieldHighlightColor",
				fieldErrorClass: "FieldErrorHighlight",
				globalErrorClass: "ErrorText",
				menuShowTimer : null,
				menuHideTimer : null,
				menuDropdownDelay : 100,
				menuImagesOn : [],
				menuImagesOff : [],
				menuDividerClass : [],
				refinementFormName : "sortItemsForm",
				resizeInterval : null,
				resizeCounter : 0
			},
			func : {
				bookmark : function( settings ) {
					if (window.sidebar)  // Mozilla Firefox Bookmark
					{ window.sidebar.addPanel(settings.title, settings.url,""); } 
					else if( window.external ) // IE Favorite
					{ window.external.AddFavorite( settings.url, settings.title); }
					else if(window.opera && window.print) // Opera Hotlist
					{ return true; }
				},
				emailSubscribeFooter : function() {
					$("#WidgetFooterSubscribe").unbind("click").click(function(evt) {
						evt.preventDefault();
						var url = $(this).attr("href");
                  $.post( url, { isAjaxCall : "true", rid : lib.utils.timestamp(), unSubscribe : false, dateOfBirth : $("input[@name=dateOfBirthEntry]").val(), userEmail : $("input[@name=subscribeEmailAddress]").val() }, function(data) {
                      $("#FooterEmailSignup *").remove();
                      $("#FooterEmailSignup").html("");
                      $("#FooterEmailSignup").append(data);
                      site.func.emailSubscribeFooter();
                  });
					});
				},
				fieldErrors : function(selector) {
					$(selector + " ." + site.data.globalErrorClass).each(function() {
						$(this).parent().addClass( site.data.fieldErrorClass );
					});
				},
				fieldHighlight : function(selector) {
					var inputs = "input, select, textarea";
					$(inputs, $(selector)).bind("focus.fields", function(evt) {
						if( (!$(evt.target).is("input[@type=image]")) && (!$(evt.target).is("input[@type=radio]")) )
						{ $(evt.target).addClass( site.data.fieldHighlightClass ); }
					});
					$(inputs, $(selector)).bind("blur.fields", function(evt) {
						$(evt.target).removeClass( site.data.fieldHighlightClass );
					});
					$("select", $(selector)).mousedown(function(evt) {
						$(evt.target).addClass( site.data.fieldHighlightClass );
					});
				},
				genericHoverHighlight : function(selector, newclass) {
					$(selector).hover(
						function() { $(this).addClass(newclass); },
						function() { $(this).removeClass(newclass); }
				  	); 
				},
				showGlobalDropdown : function(thisMenu, index) {
					$(".WidgetSectionButton", $(thisMenu)).attr("src", site.data.menuImagesOn[index]);
					$(".SectionNavDivider").eq(index-1).addClass("SectionNavDividerOn");
					$(".SectionNavDivider").eq(index).addClass("SectionNavDividerOn");
					site.data.menuShowTimer = setTimeout(function() {
						$("ul", $(".SectionNavButton")).hide();
						$("ul", $(thisMenu)).show();
						
					}, site.data.menuDropdownDelay);
				},
				hideGlobalDropdown : function(thisMenu, index) {
					$(".WidgetSectionButton", $(thisMenu)).attr("src", site.data.menuImagesOff[index]);
					$(".SectionNavDivider").eq(index-1).attr("class", site.data.menuDividerClass[index-1]);
					$(".SectionNavDivider").eq(index).attr("class", site.data.menuDividerClass[index]);
					site.data.menuHideTimer = setTimeout(function() {
						$("ul", $(thisMenu)).hide();
					}, site.data.menuDropdownDelay);
				},
				pwrOpenProductPage : function(url, type) {
					var fullURL = ( type == "r" ) ? url + "?readReview=1" : url + "?writeReview=1";
					window.location = fullURL;
				},
				pwrReadReview : function() {
					productTabs.activateTab("ratings");
					$(".ProdTabContent[@name=ratings] .ProdReviewContent").eq(0).show();
					$(".ProdTabContent[@name=ratings] .ProdReviewContent").eq(1).hide();
				},
				pwrWriteReview : function(pageId, merchantId, cssOverride) {
					productTabs.activateTab("ratings");
					$(".ProdTabContent[@name=ratings] .ProdReviewContent").eq(0).hide();
					$(".ProdTabContent[@name=ratings] .ProdReviewContent").eq(1).show();
					$("*", $(".ProdTabContent[@name=ratings] .ProdReviewContent").eq(1)).remove(); 
					$(".ProdTabContent[@name=ratings] .ProdReviewContent").eq(1).html("<span id='WidgetPWRLoading'>Loading <br /> Loading <br /> Loading <br /></span>");
					$(".ProdTabContent[@name=ratings] .ProdReviewContent").eq(1).show();
					
					var iframeHTML = '<iframe onLoad="site.func.pwrStopLoad()" name="PWRReviewsIframe" id="PWRReviewsIframe" src="http://services.powerreviews.com/SubmitReview.do?pageId=' + pageId + '&merchantId=' + merchantId + '&source=web&merchantUserId=' + merchantId + '&cssOverride=' + cssOverride + '" frameborder="0"></iframe>';
					$(".ProdTabContent[@name=ratings] .ProdReviewContent").eq(1).append( iframeHTML );
					setTimeout( function() { window.location = "#tabs"; }, 100);
				},
				pwrStopLoad : function() {
				  $("#WidgetPWRLoading").remove();
				  $("#PWRReviewsIframe").show();
				},
				setupRefinements : function() {
					if( $(".WidgetRefinementSelected").size() > 0 )
					{ $("#RefinementsClearAll").show(); }
				
					$(".RefinementEntry select").change(function() {
						$("form[@name=" + site.data.refinementFormName + "]").submit();
					});
				
					$(".RefinementsLarge a").click(function(evt) {
						evt.preventDefault();
						$("input", $(this).parent().parent().parent()).val($(this).attr("href").split("#")[1]);
						$("form[@name=" + site.data.refinementFormName + "]").submit();
					});
				
					$(".RefinementsLargeSearch input").keyup(function() {
						var currentText = $(this).val().toLowerCase();
						
						//if price need to pre-pend a '$'
						if( $(this).is(".isPriceRefinement") && (currentText.indexOf("$") != 0) )
						{ 
							currentText = "$" + currentText;
							$(this).val( currentText );
						}
						
						var currentRefinement = "";
						if( currentText != "" )
						{
							$(".RefinementsLarge li a", $(this).parent().parent()).each(function(i) {
								currentRefinement = $(this).text().toLowerCase();
								if(currentRefinement.indexOf(currentText) == 0)
								{ $(this).parent().show(); }
								else
								{ $(this).parent().hide(); }
							});
						}
						else
						{ $(".RefinementsLarge li", $(this).parent().parent()).show(); }
					});
					$(".RefinementsLargeSearch input").keyup();
					
					$(".WidgetClearRefinement").click(function(evt) {
						evt.preventDefault();
						$("input", $(this).parent()).val("");
						$("form[@name=" + site.data.refinementFormName + "]").submit();
					});
				},
				iframeShim : function( elementToShimSelector, shimIdSelector, action ) {
					if((action=="r")) {
						$("#recentlyViewedDiv").css("visibility","visible");
					}
					else {
						$("#recentlyViewedDiv").css("visibility","hidden");
					}
					if(lib.utils.isIE6())
					{
						var exists = $(shimIdSelector).size() > 0 ? true : false;
						
						if((action == "r") && exists)
						{ $(shimIdSelector).remove(); }
						else if(action == "a" && !exists)
						{
							fixHTML = '<div id="' + shimIdSelector.split("#")[1] + '"><iframe width="100%" height="100%" frameborder="0" src="/blank.gif"><!-- --></iframe></div>';
							$(elementToShimSelector).parent().append(fixHTML);
							exists = $(shimIdSelector).size() > 0 ? true : false;
						}
						
						if((action == "a" || "u") && exists)
						{
							$(shimIdSelector).css("position", $(elementToShimSelector).css("position"));
							$(shimIdSelector).css("height", $(elementToShimSelector).height());
							$(shimIdSelector).css("width", $(elementToShimSelector).width());
							$(shimIdSelector).css("margin-left", $(elementToShimSelector).css("margin-left"));
							$(shimIdSelector).css("margin-right", $(elementToShimSelector).css("margin-right"));
							$(shimIdSelector).css("margin-top", $(elementToShimSelector).css("margin-top"));
							$(shimIdSelector).css("margin-bottom", $(elementToShimSelector).css("margin-bottom"));
							$(shimIdSelector).css("top", $(elementToShimSelector).css("top"));
							$(shimIdSelector).css("left", $(elementToShimSelector).css("left"));
							$(shimIdSelector).css("z-index", $(elementToShimSelector).css("z-index")-1);
						}
					}	
				},
				openPopup : function( url, settings ) {
					$("body").append('<a style="display: none;" id="js-instantlink" href="' + url + '"></a>');
					lib.link.popupWindow("#js-instantlink", settings);	
					$("#js-instantlink").triggerHandler("click");
					$("#js-instantlink").remove();
				}
			},
			obj : {
				swatch : function(settings) {
					if(arguments.length > 0)
					{ this.init(settings); }	
				}
			}
		};
	}($)
})($);

site.obj.swatch.prototype.init = function(settings) {
	settings = jQuery.extend({
		swatchImageURL : "#",
		mainImageURL : "#",
		colorName : "Color Name",
		colorDropdownSelector : "#_null"
	}, settings );
	
	this.swatchImageURL = settings.swatchImageURL;
	this.mainImageURL = settings.mainImageURL;
	this.colorName = settings.colorName;
	this.colorDropdownSelector = settings.colorDropdownSelector;
};

$(function() {
	
	/* size the footer to be full page if needed */
	site.data.resizeInterval = setInterval( function() {
		if( lib.image.isComplete("img") || (site.data.resizeCounter == 20) ) // all image loaded or waited 5 seconds
		{
			clearInterval(site.data.resizeInterval);
			var dif = lib.screen.size()[1] - $("body").height();
			if( dif > 0  )
			{ $("#FooterBottom").css("padding-bottom",  (parseInt($("#FooterBottom").css("padding-bottom")) + dif) + "px"); } 
		}
		site.data.resizeCounter++;
	}, 250);
	
	/* Setup the Global Nav */
	$(".SectionNavButton").each(function(i) {
		// 1. Build out the Images Paths
		site.data.menuImagesOff[i] = $("a .WidgetSectionButton", $(this)).attr("src");
		site.data.menuImagesOn[i] = $("a .WidgetSectionButton", $(this)).attr("src").split("but-nav")[0] + "but-nav-" + $("a .WidgetSectionButton", $(this)).attr("name") + "-on.gif";
		lib.image.preload(site.data.menuImagesOn[i]);
		
		// 2. Setup the Dropdown Functionality
		$(this).hover(
			function() { 
				site.func.showGlobalDropdown( $(this), i );
				site.func.iframeShim( $(".SectionNavLevel1",this), "#dropdown-iframe", "a" ); 
			},
			function() {
				if( typeof site.data.menuShowTimer != "undefined" ){ 
					site.func.iframeShim( $(".SectionNavLevel1",this), "#dropdown-iframe", "r" ); 
					clearTimeout(site.data.menuShowTimer); 
				}
				site.func.hideGlobalDropdown( $(this), i );
			}
		);
		$("ul", $(this)).hover(
			function() {
				if( typeof site.data.menuHideTimer != "undefined" )
				{ clearTimeout(site.data.menuHideTimer); }
			},
			function() { site.func.hideGlobalDropdown( $(this), i ); }
		);
	});
	$(".SectionNavDivider").each(function(i) { site.data.menuDividerClass[i] = $(this).attr("class"); });
	/* ------------------- */

	/* setup the search input field functionality. */
	lib.input.defaultText( "#HeaderSearchKeyword", { defaultText : site.data.searchFieldText });
	$("#searchForm").submit(function() {
		searchVal = $("#HeaderSearchKeyword").val();
		if( (searchVal == site.data.searchFieldText) || (searchVal == "") )
		{
			alert("Please enter a search term and try your search again");
			return false;
		}
	});
	/* ---------------------- */
	
	/* setup the newletter input field functionality. */
	lib.input.defaultText( "#FooterEmailSignup #emailAddress", { defaultText : "your e-mail address"});
	/* ---------------------- */
	
	/* Run Refinement setup */
	setTimeout(function() {
		if ( $("#Refinements").size() > 0 )
		{ site.func.setupRefinements(); }
	},50);
	/* --------------- */
	
	/* Popups (global) */
		//Online Catalog
		lib.link.popupWindow(".WidgetOnlineCatalog", {
      	width: 800,
			height: 500,
			scrollbars: 1
		});
	
		// Check Gift Card Balance
		lib.link.popupWindow("#WidgetCheckGiftCardBalance", {
      	width: 450,
			height: 250,
			scrollbars: 1
		});
		
		// Contact Us
		lib.link.popupWindow("#WidgetContactus", {
     		width: 550,
			height: 330,
			scrollbars: 1
     	});
	/* ----------------------------- */
	
	/* Leftnavigation Rollovers */
	$("#PosLeftNav li span").each(function() {
		if( !$(this).is(".active") )
		{
			$(this).hover(
				function() {
					$(this).addClass("active");
				},
				function() {
					$(this).removeClass("active");
				}
			);
		}
	});
	/* ---------------- */
	
	/* Setup the Email Subscription */
	site.func.emailSubscribeFooter();
});
