$(document).ready(function(){
	var currentProtocol = (("https:" == document.location.protocol) ? "https:" : "http:");

	/* heartBullet was for redesign v2, not v3
	* selected links are bolded in the leftnav by jquery.all.js
	*/
	/*if ( $(".subcategories:visible").length ) {
		$(".subcategories:visible").prev().css("color",$(".subcategories a").css("color"));
		var currentLocation = window.location.toString().split('/');
    	currentLocation = currentLocation[currentLocation.length - 1];
		if ( currentLocation ) {
			// if homepage, loc will be blank. for some reason IE8 will match on this, and 
			// all links get underlined. hence the test
			var linkSelector = "#logobar li a[href$='"+currentLocation+"']";
    		$(".subcategories:visible a[href$='"+currentLocation+"']").addClass("heartBullet");
		}
	}*/

	if ( $(".pgntLeft").length ) {
		$(".pgntLeft").hover(function(){
			//alert("hover in detected, src = " + $("img",this).attr("src") + "\r\nchanging to" + );
			$("img",this).attr("src",$("img",this).attr("src").replace( /\.png/g, "on.png"));
		},function(){
			//alert("hover out detected");
			$("img",this).attr("src",$("img",this).attr("src").replace( /on\.png/g, ".png"));
		});
	}

	if ( $(".pgntRight").length ) {
		$(".pgntRight").hover(function(){
			//alert("hover in detected, src = " + $("img",this).attr("src") + "\r\nchanging to" + );
			$("img",this).attr("src",$("img",this).attr("src").replace( /\.png/g, "on.png"));
		},function(){
			//alert("hover out detected");
			$("img",this).attr("src",$("img",this).attr("src").replace( /on\.png/g, ".png"));
		});
	}


	$("#ctgySortBy input[type='button']").hide();
	$("#sortBy").change(function(){
		window.location = $(this).val();
	});
	
	/* recently viewed items
	* this is present on PROD and CTGY */
	if ( $("#toggleSuggestedItemHistory").length ) {
		$("#toggleSuggestedItemHistory").click(function(event){
			event.preventDefault(); // this isn't a link so there should be no default action but whatever
			$("#suggestedItemHistory").toggle();
			return false;
		});
	}
	
	
	/* fairy tale exit survey */
	/*if ( ctgyCode == "FairyTale" ) {
		var theReferrer = document.referrer;
		if ( theReferrer && theReferrer.indexOf("yahoo.com") != -1 ) {
			var engineFlag = "yahoo";
		} else if ( theReferrer && theReferrer.indexOf("google.com") != -1 ) {
			var engineFlag = "google";
		} else {
			var engineFlag = "unknown";
		}
		
		if ( engineFlag != "unknown" ) {
			var exit = true;
			$("a").bind("click", function(){ exit = false; });
			$("form").bind("submit", function(){ exit = false; });
			$("body").append(engineFlag);
			$(window).bind("unload", function(){
								if ( exit ) {
									//alert("exiting");
									var surveyURL = "http://www.favorfavor.com/includes/surveys/exitSurvey.php";
									var height = "550";
									var width = "450";
									var windowName = "FavorFavorExitSurvey";
									var settings = "toolbar=0,directories=0,menubar=0,scrollbars=1,resizable=1,width="+width+",height="+height;
									//alert("exiting");
									window.open( surveyURL, windowName, settings );
									//alert("done exiting");
								}
			});
		}
	}*/
	/* end fairy tale exit survey */
	
	/* clicktale stuff */
	if ( $.getQueryString({id:"gclid", defaultvalue:""}) != "" ) {
		var WRInitTime=(new Date()).getTime();
		$("body").append("<div id=\"ClickTaleDiv\" style=\"display: none;\"></div>");
		if ( currentProtocol != "https:" ) {
			$("body").append(unescape("%3Cscript src='http://s.clicktale.net/WRb.js' type='text/javascript'%3E%3C/script%3E"));
			window.callCT;
			$(document).ready(function(){
				callCT = setInterval(
					function(){
						if(typeof ClickTale=='function') {
							ClickTale(11564,1,"www02");
							callCT = clearInterval(callCT);
						}
					}, 100 );
			});
		}
	}
	/* end clicktale */
	
	/* hide the favor finder */
	if ( $("#favorFinder").length ) { // should always be true
		$("#favorFinder").before("<p id=\"showFavorFinder\" class=\"nomarg ui-state-default ui-corner-all\" style=\"text-align: center;\">Having trouble finding the perfect favor? Try filtering this category using our handy Favor Finder!<br><span class=\"fLeft ui-icon ui-icon-arrowstop-1-s\"></span><span class=\"fRight ui-icon ui-icon-arrowstop-1-s\"></span><br class=\"clear\"></p>");
		/*$("p#showFavorFinder").hover(function(){
			$(this).addClass("ui-state-hover").removeClass("ui-state-default");
		},function(){
			$(this).addClass("ui-state-default").removeClass("ui-state-hover");
		});
		$("#showFavorFinder").live("click", function(event){
			event.preventDefault();
			$("#favorFinder").toggle("blind",600);
			return false;
		}).css( "cursor", "pointer" );*/
	}
	
	if ( $("div.scrollable").length ) {
		// allow some categories to override the scrollable size
		//$("body").append("<br>getting scrollable size");
		var scrollableSize = $("div.scrollable").data("scrollableSize");
		if ( typeof(scrollableSize) == "undefined" ) { scrollableSize = 5; }
		//$("body").append("<br>scrollable size = " + scrollableSize );
		$("div.scrollable").scrollable({
			clickable: false,
			keyboard: false,
			size: scrollableSize,
			speed: 600,
			nextPage: ".scrollableNextPage",
			prevPage: ".scrollablePrevPage",
			onSeek: function(){
				try { _gaq.push(['_trackEvent', 'Dept Page', 'Subcategory Slider Used' ]); } catch (error) {}
			}
		}).navigator()/*.autoscroll({
			autoplay: true,
			autopause: true,
			interval: 5000,
			steps: 1
		})*/;
		$("p.ctgyScrollableLink a").hover(function(){
			$(this).addClass("ui-state-hover").removeClass("ui-state-default");
		},function(){
			$(this).addClass("ui-state-default").removeClass("ui-state-hover");
		});
	}
	
	if ( $("#ffbLink").length ) {
		$("#ffbLink").dialog({
			bgiframe: true,
			height: 550,
			width: 550,
			modal: true
		});
	}
	
	/* design testing */
	//$(".product a").addClass("hoverUL");


	if ( $.getQueryString({id:"ss"}) == "1" ) {
		//$(".subCatLink p a img").attr("height","123").attr("width","123");
		//$(".subCatLink").css("width","128px");
		//$(".subCatLink p:first-child").css("font-size",".7em");
		//$(".navi").css("height","15px");
		//$("p.ctgyScrollableLink").css("height","123px");
		//$("p.ctgyScrollableLink a span").css("margin-top","33px");
		//$("div.scrollable").css("height","160px");
		/*var api = $("div.scrollable").scrollable({api: true});
		api.getConf().size = 5;
		api.reload();*/
	} // if ( $.getQueryString({id:"ss"}) == "1" ) {

	if ( $.getQueryString({id:"xmlLoad"}) == "1" ) {
		$("body").data("totalLoadRequests", 0);
		$("#showMoreItems").button({ icons: {primary:'ui-icon-arrowthick-1-s',secondary:'ui-icon-arrowthick-1-s'} }).show().click(function(event){
			event.preventDefault();
			if ( $("body").data("xmlLoading") != 1 ) {
				if ( $("body").data("totalLoadRequests") != 0 ) {
					$("body").data("totalLoadRequests", $("body").data("totalLoadRequests") + 1);
				} else {
					$("body").data("totalLoadRequests", 1);
				}
				
				if ( $("body").data("totalLoadRequests") < ctgyTotalPages ) {
					$("body").data("xmlLoading", 1);
					
					if ( $("body").data("totalLoadRequests") == 1 ) {
						$("#lpLoadAnim").html("<img src='/images/misc/loadingAnimation.gif' height='13' width='208' alt='Loading...'>").css("text-align", "center");
					} else {
						$("#lpLoadAnim img").show();
					}
					
					//$("#pList").css({ "overflow": "hidden", "height" : $("#pList").height() + "px" });
					
					if ( ctgyOffset == "" ) {
						ctgyOffset = 32;
					} else {
						ctgyOffset += 32;
					}
					var requestURL = "/mm5/merchant.mvc?Screen=CTGYXML&Category_Code=" + ctgyCode + "&Offset=" + ctgyOffset;
					if ( ctgySortBy != "" ) {
						requestURL += "&SortBy=" + ctgySortBy;
					}
					//$("body").append("<br>getting '" + requestURL + "'");
					$.get(requestURL, function(data, status, jqXHR) {
						$(data).find("product").each(function(){
							//$("body").append("<br>loading an item" );
							//$("body").append(", name = " + $("name",this).text() );
							$("<p class='product hideMe'><a href='" + $("url",this).text() + "'><img src='" + $("thumbnail",this).text() + "' alt='" + $("name",this).text() + "' height='160' width='160'><br>" + $("name",this).text() + "<br><span class='price'>" + $("price",this).text() + "</span></a></p>").insertAfter(".product:last").fadeIn(1200);
						});
						$("#lpLoadAnim img").hide();
						$("body").data("xmlLoading",0);
						if ( $("body").data("totalLoadRequests") == (ctgyTotalPages - 1) ) {
							$("#showMoreItems").hide();
							$("#showAllItems").hide();
						}
					});
				}
			}
			return false;
		});
		
		$("#showAllItems").button({ icons: {primary:'ui-icon-arrowthick-1-s',secondary:'ui-icon-arrowthick-1-s'} }).show().click(function(event){
			event.preventDefault();
			if ( $("body").data("xmlLoading") != 1 ) {
				if ( $("body").data("totalLoadRequests") != 0 ) {
					$("body").data("totalLoadRequests", $("body").data("totalLoadRequests") + 1);
				} else {
					$("body").data("totalLoadRequests", 1);
				}
				
				if ( $("body").data("totalLoadRequests") < ctgyTotalPages ) {
					$("body").data("xmlLoading", 1);
					
					if ( $("body").data("totalLoadRequests") == 1 ) {
						$("#lpLoadAnim").html("<img src='/images/misc/loadingAnimation.gif' height='13' width='208' alt='Loading...'>").css("text-align", "center");
					} else {
						$("#lpLoadAnim img").show();
					}
					
					var requestURL = "/mm5/merchant.mvc?Screen=CTGYXML&Category_Code=" + ctgyCode + "&Offset=" + $("p.product").length + "&show=" + ctgyTotalItems;
					if ( ctgySortBy != "" ) {
						requestURL += "&SortBy=" + ctgySortBy;
					}
					$.get(requestURL, function(data, status, jqXHR) {
						$(data).find("product").each(function(){
							//$("body").append("<br>loading an item" );
							//$("body").append(", name = " + $("name",this).text() );
							$("<p class='product hideMe'><a href='" + $("url",this).text() + "'><img src='" + $("thumbnail",this).text() + "' alt='" + $("name",this).text() + "' height='160' width='160'><br>" + $("name",this).text() + "<br><span class='price'>" + $("price",this).text() + "</span></a></p>").insertAfter(".product:last").fadeIn(1200);
						});
						$("#lpLoadAnim img").hide();
						$("body").data("xmlLoading",0);
						
						/* at this point all items are loaded, there's no need
						* for the 'show more xxxxx' type buttons
						*/
						$("#showMoreItems").hide();
						$("#showAllItems").hide();
					});
				}
			}
			return false;
		});
		
		
		
		
		/*$(window).scroll(function() {
			if ( isTopVisible( $("#ctgySortB") ) && 0 ) {
				//alert("element is visible");
				
				if ( $("body").data("xmlLoading") != 1 ) {
					// step 1: load and show the loading animation
					//$("body").append("<br>total load requests = " + $("body").data("totalLoadRequests") );
					if ( $("body").data("totalLoadRequests") != 0 ) {
						//$("body").append("<br>totalLoadRequests is != 0, I will add 1");
						$("body").data("totalLoadRequests", $("body").data("totalLoadRequests") + 1);
					} else {
						//$("body").append("<br>load requests is 0, I will set it to 1");
						$("body").data("totalLoadRequests", 1);
					}
					
					if ( $("body").data("totalLoadRequests") < ctgyTotalPages ) {
						$("body").data("xmlLoading",1);
						//$("body").append("<br>requesting items");
						$("#lpLoadAnim").html("<img src='/images/misc/loadingAnimation.gif' height='13' width='208' alt='Loading...'>").show().css("text-align", "center");
						//$("body").append("<br>type of offset = " + typeof( ctgyOffset ) );
						//$("body").append("<br>type of offset (parsed) = " + typeof( parseInt(ctgyOffset) ) );
						//$("body").append("<br>type of offset (Number) = " + typeof( Number(ctgyOffset) ) );
						if ( ctgyOffset == "" ) {
							ctgyOffset = 32;
						} else {
							ctgyOffset += 32;
						}
						var requestURL = "/page/FF/CTGY/" + ctgyCode + "?xmlOutput=1&Offset=" + ctgyOffset;
						
						//$("body").append(", URL = " + requestURL);
						$.get(requestURL, function(data, status, jqXHR) {
							
							//$("body").append("<br>" + data);
							
							//$("body").append("<br>product length = " + $(data).find("product").length );
							$(data).find("product").each(function(){
								//$("body").append("<br>loading an item" );
								//$("body").append(", name = " + $("name",this).text() );
								$("<p class='product'><a href='" + $("url",this).text() + "'><img src='" + $("thumbnail",this).text() + "' alt='" + $("name",this).text() + "' height='160' width='160'><br>" + $("name",this).text() + "<br><span class='price'>" + $("price",this).text() + "</span></a></p>").insertBefore("#lpLoadAnim");
							});
							
							$("#lpLoadAnim").hide();
							$("body").data("xmlLoading","0");
						});
					} else {
						//$("body").append("<br>too many load requests..." + $("body").data("totalLoadRequests") );
					}
				}
				
			}
		});*/
	}
	
	
	
	/************ HANDLE NEW SUB-CTGY SCROLLERS **************/
	
	//rolloverLink( el, off, over, clicked );
	// set up rollovers for all thumbnails
	/*rolloverLink( $(".scrollable .items div:eq(0) p:eq(0) img"), "/images/misc/categories/subCatTh/PersonalizedWeddingFavors/glass.png", "/images/misc/categories/subCatTh/PersonalizedWeddingFavors/glass-mouseover.png", "/images/misc/categories/subCatTh/PersonalizedWeddingFavors/glass-click.png" );
	rolloverLink( $(".scrollable .items div:eq(0) p:eq(1) img"), "/images/misc/categories/subCatTh/PersonalizedWeddingFavors/mint.png", "/images/misc/categories/subCatTh/PersonalizedWeddingFavors/mint-mouseover.png", "/images/misc/categories/subCatTh/PersonalizedWeddingFavors/mint-click.png" );
	rolloverLink( $(".scrollable .items div:eq(1) p:eq(0) img"), "/images/misc/categories/subCatTh/PersonalizedWeddingFavors/chocolate.png", "/images/misc/categories/subCatTh/PersonalizedWeddingFavors/chocolate-mouseover.png", "/images/misc/categories/subCatTh/PersonalizedWeddingFavors/chocolate-click.png" );
	rolloverLink( $(".scrollable .items div:eq(1) p:eq(1) img"), "/images/misc/categories/subCatTh/PersonalizedWeddingFavors/express.png", "/images/misc/categories/subCatTh/PersonalizedWeddingFavors/express-mouseover.png", "/images/misc/categories/subCatTh/PersonalizedWeddingFavors/express-click.png" );
	rolloverLink( $(".scrollable .items div:eq(2) p:eq(0) img"), "/images/misc/categories/subCatTh/PersonalizedWeddingFavors/ribbons.png", "/images/misc/categories/subCatTh/PersonalizedWeddingFavors/ribbons-mouseover.png", "/images/misc/categories/subCatTh/PersonalizedWeddingFavors/ribbons-click.png" );
	rolloverLink( $(".scrollable .items div:eq(2) p:eq(1) img"), "/images/misc/categories/subCatTh/PersonalizedWeddingFavors/lip.png", "/images/misc/categories/subCatTh/PersonalizedWeddingFavors/lip-mouseover.png", "/images/misc/categories/subCatTh/PersonalizedWeddingFavors/lip-click.png" );

	rolloverLink( $(".scrollable .items div:eq(3) p:eq(0) img"), "/images/misc/categories/subCatTh/PersonalizedWeddingFavors/pen.png", "/images/misc/categories/subCatTh/PersonalizedWeddingFavors/pen-mouseover.png", "/images/misc/categories/subCatTh/PersonalizedWeddingFavors/pen-click.png" );
	rolloverLink( $(".scrollable .items div:eq(3) p:eq(1) img"), "/images/misc/categories/subCatTh/PersonalizedWeddingFavors/napkins.png", "/images/misc/categories/subCatTh/PersonalizedWeddingFavors/napkins-mouseover.png", "/images/misc/categories/subCatTh/PersonalizedWeddingFavors/napkins-click.png" );
	rolloverLink( $(".scrollable .items div:eq(4) p:eq(0) img"), "/images/misc/categories/subCatTh/PersonalizedWeddingFavors/stickers.png", "/images/misc/categories/subCatTh/PersonalizedWeddingFavors/stickers-mouseover.png", "/images/misc/categories/subCatTh/PersonalizedWeddingFavors/stickers-click.png" );
	rolloverLink( $(".scrollable .items div:eq(4) p:eq(1) img"), "/images/misc/categories/subCatTh/PersonalizedWeddingFavors/coffee.png", "/images/misc/categories/subCatTh/PersonalizedWeddingFavors/coffee-mouseover.png", "/images/misc/categories/subCatTh/PersonalizedWeddingFavors/coffee-click.png" );
	rolloverLink( $(".scrollable .items div:eq(5) p:eq(0) img"), "/images/misc/categories/subCatTh/PersonalizedWeddingFavors/honey.png", "/images/misc/categories/subCatTh/PersonalizedWeddingFavors/honey-mouseover.png", "/images/misc/categories/subCatTh/PersonalizedWeddingFavors/honey-click.png" );
	*/
	// move scrollable navigation section, set up text etc
	$("#navHolder").detach().appendTo(".ctgyHeader").show();
	$(".navi").hide(); // no longer in use with v2 of the scrollers
	$(".scrollableStartCount").text("1");
	scrollableAPI = $("div.scrollable").data("scrollable");
	//$(".scrollableTotalCount").text( scrollableAPI.getSize()*2 );
	$(".scrollableTotalCount").text( String($(".scrollable .items div p").length) ); // this is more accurate
	if ( $(".scrollable .items div p").length > 5 ) {
		$(".scrollableEndCount").text("6");
	} else {
		$(".scrollableEndCount").text( $(".scrollable .items div p").length );
	}
	
	/* check if we need to scroll, if so set up rollovers etc
	* note that the rollovers for each subcategory are set on the main ctgy page code
	*/
	if ( Number($(".scrollableTotalCount").text()) > 6 ) {
		$("#navHolder .scrollableNextPage img").removeClass("rolloverDisabled").attr("src","/images/misc/categories/subCatTh/rightOff.png");
		rolloverLink( $("#navHolder .scrollableNextPage img"), "/images/misc/categories/subCatTh/rightOff.png", "/images/misc/categories/subCatTh/rightOver.png", "/images/misc/categories/subCatTh/rightDown.png" );

		scrollableAPI.onSeek(function(){
			var pageNumber = scrollableAPI.getIndex() / 3;
			//$("body").append("<br>seeking to " + scrollableAPI.getIndex() + " (page number " + pageNumber + ")");
			var startCount = (pageNumber * 6) + 1;
			var endCount = (pageNumber * 6) + 6;
			if ( endCount > Number( $(".scrollableTotalCount").text() ) ) {
				endCount = Number( $(".scrollableTotalCount").text() );
			}
			
			if ( startCount == "1" ) {
				$("#navHolder .scrollablePrevPage img").addClass("rolloverDisabled").attr("src", "/images/misc/categories/subCatTh/leftDisabled.png");
			} else {
				$("#navHolder .scrollablePrevPage img").removeClass("rolloverDisabled").attr("src", "/images/misc/categories/subCatTh/leftOff.png");
				if ( $("#navHolder .scrollablePrevPage img").data("rolled") != "1" ) {
					rolloverLink( $("#navHolder .scrollablePrevPage img"), "/images/misc/categories/subCatTh/leftOff.png", "/images/misc/categories/subCatTh/leftOver.png", "/images/misc/categories/subCatTh/leftDown.png" );
					$("#navHolder .scrollablePrevPage img").data("rolled","1");
				}
			}
			if ( endCount == Number( $(".scrollableTotalCount").text() ) ) {
				$("#navHolder .scrollableNextPage img").addClass("rolloverDisabled").attr("src", "/images/misc/categories/subCatTh/rightDisabled.png");
			} else {
				$("#navHolder .scrollableNextPage img").removeClass("rolloverDisabled").attr("src", "/images/misc/categories/subCatTh/rightOff.png");
			}
			
			$(".scrollableStartCount").text(startCount);
			$(".scrollableEndCount").text(endCount);
		});
		//$("div.scrollable").scrollable({ size: 5 });
	}
	
	// preserve the showPR option if it's already on
	if ( $.getQueryString({id:"showPR", defaultvalue:""}) != "" ) {
		$("#sortBy option").each(function(){
			if( $(this).val().indexOf( "?" ) != -1 ) {
				$(this).val( $(this).val() + "&showPR=1" );
			} else {
				$(this).val( $(this).val() + "?showPR=1" );
			}
		});
		
		$(".ctgyPaginate a, .scrollable .items a").each(function(){
			if( $(this).attr("href").indexOf( "?" ) != -1 ) {
				$(this).attr("href", $(this).attr("href") + "&showPR=1" );
			} else {
				$(this).attr("href", $(this).attr("href") + "?showPR=1" );
			}
		});
	}
});

function isTopVisible( el ) {
	//$("body").append( "<br>" + $(window).scrollTop() + el.height() );
	//$("body").append( "<br>--" + el.offset().top );
    return $(window).scrollTop() + $(window).height() >= el.offset().top;
}















