// JavaScript Document

$(document).ready(function(){
	$("#custFAQ div:first-child a").click(function(event){
		event.preventDefault();
		$("#custFAQ div:first-child a").each( function(i){
			$(this).removeClass("selected");
		});
		$(this).addClass("selected");
		$("#custFAQ div:last-child div").each( function(i){
			$(this).hide();
			//$(this).hide("blind","fast");
		});
		$($(this).attr("href")).show();
		//$($(this).attr("href")).show("blind","fast");
		return false;
	});
	$("#orderNeedHelp").click(function(event){
		event.preventDefault();
		$("#custFAQ div:first-child a").each( function(i){
			$(this).removeClass("selected");
		});
		$("#custFAQ div:last-child div").each( function(i){
			$(this).hide();
			//$(this).hide("blind","fast");
		});
		$($("#custFAQ div:first-child a[href='#cartSupport']")).addClass("selected");
		$($(this).attr("href")).show().effect("highlight", {}, 2500);
		$.scrollTo($(this).attr("href"), "600", {axis:"y",offset:-150} );
		return false;
	});

	// track product add / remove
	if ( MivaProdCode != "" && MivaProdCode != "undefined" && MivaProdCode != null & MivaProdCode != " " & MivaProdCode != "&" ) {
		MivaProdCode = MivaProdCode.replace(/^\s+|\s+$/g, '') ;
		MivaAction = MivaAction.replace(/^\s+|\s+$/g, '') ;
		MivaProdCode = MivaProdCode.replace(/^&+|&+$/g, '') ;
		MivaAction = MivaAction.replace(/^&+|&+$/g, '') ;
		if ( MivaAction == "ADPR" ) {
			try { _gaq.push(['_trackEvent', 'Products', 'Product Added', MivaProdCode ]); } catch (error) {}
		} else {
			/* cannot track prod removals anymore since we are using the toolkit to loop through and
			* remove all checked items */
			try { _gaq.push(['_trackEvent', 'Products', 'Product Removed', MivaProdCode ]); } catch (error) {}
		}	
	}

	if ( $("#showCalcShipForm").length ) {
		//$("#calcship").css({ 'display' : 'none' });
		// this should always be true
		$("#ShipZip").keypress(function(event){
			if ( ( event.which && event.which == 13 ) || ( event.keyCode && event.keyCode == 13 ) ) {
				// they hit enter, which won't trigger a click in IE for some reason
				document.getElementById("calcShippingButton").click();
				event.preventDefault();
				return false;
			} else {
				return true;
			}
		});
		
		$("#showCalcShipForm").click(function(event){
			event.preventDefault();
			//if ( !$("#calcshipLocation").dialog( "option", "height" ) ) {
			if ( !dialogCreated( $("#calcshipLocation") ) ) {
				//var HW = getHW( $(this).attr("href") );
				$("#calcshipLocation").dialog({
					bgiframe: true,
					width: 420,
					height: 250,
					modal: true
				});
			} else {
				$("#calcshipLocation").dialog( "open" );
			}
			try { _gaq.push(['_trackEvent', 'Basket: BASK', 'Shipping Calculator Form Viewed' ]); } catch (error) {}
			return false;
		});
		
		$("#calcShippingButton").click(function(event){
			event.preventDefault();
			$("#calcShipResults").html("<img src=\"/images/misc/loadingAnimation.gif\" width=\"208\" height=\"13\" alt=\"Loading...\">").show( "blind", "fast" );
			try { _gaq.push(['_trackEvent', 'Basket: BASK', 'Shipping Calculator Results Viewed' ]); } catch (error) {}
			var rateURL = (("https:" == document.location.protocol) ? "https:" : "http:") + "//www.favorfavor.com/mm5/merchant.mvc";
			var shipZip = $.trim($("#ShipZip").val()).replace( /\s/g, "" );
			var shipState = getStateByZip( shipZip );
			if ( shipState != "CANADA" ) {
				if ( shipState != "PR" ) {
					var shipCountry = "US";
				} else {
					var shipCountry = "PR";
				}
			} else {
				shipState = "";
				shipCountry = "CA";
				shipZip = shipZip.substr( 0, 3 ) + "%20" + shipZip.substr( 3, 3 );
			}
			//$("body").append("state: " + shipState + " Zip: " + theShipZip);
			//alert("posting " + rateURL );
			// lets try GET instead of POST
			rateURL += "?ShipZip=" + shipZip;
			rateURL += "&shipcountry=" + shipCountry;
			rateURL += "&shipstate=" + shipState;
			rateURL += "&calcship=1";
			rateURL += "&Store_Code=FF";
			rateURL += "&Screen=CALCSHIPPING";
			rateURL += "&Session_ID=" + $("#miniBasketShipCalc input[name='Session_ID']").val();
			//$("#calcshipLocation").dialog( "close" );
			$("body").append("<br>" + rateURL );
			$("#calcShipResults").load( rateURL );
			return false;
		});
		
		$(".shippingRate").live("click", function(event){
			event.preventDefault();
			if ( $(this).text().indexOf("$") > -1 ){
				var estShipping = $(this).text().replace( /\$/, "" );
			} else {
				var estShipping = $(this).parent().parent().next().text().replace( /([\$,])/g, "" );
			}
			var merchSubtotal = Number($("#merchSubtotal").html().replace( /([\$,])/g, "" ));
			window.baskCharges = 0;
			if ( $(".baskCharges").length ) {
				$(".baskCharges").each(function(){
					if ( $(this).html().charAt(0) == "(" ) {
						baskCharges -= Number($(this).html().replace( /([\$,()])/g, "" ));
					} else {
						baskCharges += Number($(this).html().replace( /([\$,])/g, "" ));
					}
				});
			}
			$("#estShippingCharge").html( "$" + estShipping );
			var newTotal = (merchSubtotal + Number(estShipping) + baskCharges).toFixed(2);
			$("#estTotal").html( "$" + newTotal );
			
			var transferOptions = { to: "#estShippingCharge", className: 'ui-effects-transfer' };
			
			$("#calcshipLocation").effect( "transfer", transferOptions, 600, function(){
				$("#estTotal").effect("highlight", {}, 1500);
			});
			$("#calcshipLocation").dialog( "close" );
			
			return false;
		});
	} // if ( $("#calcship").length ) {



	//wishlist
	if ( $("#showWishList").length ) {
		$("#showWishList").click(function(event){
			jqSlideLayer ( "wishlist", "slow", 0 );
		});
		$("#hideWishList").click(function(event){
			jqSlideLayer ( "wishlist", "fast", 0 );
		});
	}
	
	if ( $("#saveBaskCreateAccount").length ) {
		$("#saveBaskCreateAccount").click(function(event){
			event.preventDefault();
			$.getScript( '/js/acad.js' );
			
			if ( !$("#createAccountDialog").length ) {
				$("body").append("<div id=\"createAccountDialog\" class=\"hideMe\" title=\"Create Account to Save Your Basket &amp; Recall Later\"></div>");
				$("#createAccountDialog").load( "/includes/ajax/acad.php", function(){
					$(document).ready(function(){
						try { _gaq.push(['_trackEvent', 'Basket', 'Save Basket: Info Viewed' ]); } catch (error) {}
						$("#accountCreate").validate({
							errorClass: "ui-state-error",
							rules: {
								Customer_Login: "required",
								Customer_PasswordEmail: {
									required: true,
									email: true
								},
								Customer_Password: "required",
								Customer_VerifyPassword: "required",
								Customer_ShipFirstName: {
									required: {
										depends: function(element) {
											return $("#addressInfo:checked").length;
										}
									}
								},
								Customer_BillLastName: {
									required: {
										depends: function(element) {
											return $("#addressInfo:checked").length;
										}
									}
								},
								Customer_BillEmail: {
									required: {
										depends: function(element) {
											return $("#addressInfo:checked").length;
										}
									}
								},
								Customer_BillPhone: {
									required: {
										depends: function(element) {
											return $("#addressInfo:checked").length;
										}
									},
       								minlength: 7,
      								digits: true
								},
								Customer_BillAddress: {
									required: {
										depends: function(element) {
											return $("#addressInfo:checked").length;
										}
									}
								},
								Customer_BillCity: {
									required: {
										depends: function(element) {
											return $("#addressInfo:checked").length;
										}
									}
								},
								Customer_BillStateSelect: {
									required: {
										depends: function(element) {
											return $("#addressInfo:checked").length;
										}
									}
								},
								Customer_BillZip: {
									required: {
										depends: function(element) {
											return $("#addressInfo:checked").length;
										}
									},
       								minlength: 5,
      								digits: true
								},
								Customer_BillCountry: {
									required: {
										depends: function(element) {
											return $("#addressInfo:checked").length;
										}
									}
								},
								Customer_ShipFirstName: {
									required: {
										depends: function(element) {
											return $("#differentShipping:checked").length;
										}
									}
								},
								Customer_ShipLastName: {
									required: {
										depends: function(element) {
											return $("#differentShipping:checked").length;
										}
									}
								},
								Customer_ShipEmail: {
									required: {
										depends: function(element) {
											return $("#differentShipping:checked").length;
										}
									},
									email: true
								},
								Customer_ShipPhone: {
									required: {
										depends: function(element) {
											return $("#differentShipping:checked").length;
										}
									},
       								minlength: 7,
      								digits: true
								},
								Customer_ShipAddress: {
									required: {
										depends: function(element) {
											return $("#differentShipping:checked").length;
										}
									}
								},
								Customer_ShipCity: {
									required: {
										depends: function(element) {
											return $("#differentShipping:checked").length;
										}
									}
								},
								Customer_ShipStateSelect: {
									required: {
										depends: function(element) {
											return $("#differentShipping:checked").length;
										}
									}
								},
								Customer_ShipZip: {
									required: {
										depends: function(element) {
											return $("#differentShipping:checked").length;
										}
									},
       								minlength: 5,
      								digits: true
								},
								Customer_ShipCountry: {
									required: {
										depends: function(element) {
											return $("#differentShipping:checked").length;
										}
									}
								}
							
							}
						});
						$("#createAccount").click(function(event){
							event.preventDefault();
							if ( $("#accountCreate").valid() ) {
								try { _gaq.push(['_trackEvent', 'Basket', 'Save Basket: Account Created, Basket Saved' ]); } catch (error) {}
								createAccount( sessionID, "bask" );
							}
							return false;
						});
						
						$("#accountLoginForm").validate({
							rules: {
								accountLoginCustomer_Login: "required",
								accountLoginCustomer_Password: "required"
							}
						});
						$("#loginAccount").live("click",function(event){
							event.preventDefault();
							if ( $("#accountLoginForm").valid() ) {
								try { _gaq.push(['_trackEvent', 'Basket', 'Save Basket: Logged In, Basket Saved' ]); } catch (error) {}
								loginAccount( sessionID, "bask" );
							}
							return false;
						});
						
						$("#whatIsThis").click(function(event){
							event.preventDefault();
							$("#whatIsThisInfo").load( "/includes/ajax/whatIsThisBask.php", function(){
								$(document).ready(function(){
									//if ( !$("#whatIsThisInfo").dialog( "option", "height" ) ) {
									if ( !dialogCreated( $("#whatIsThisInfo") ) ) {
										$("#whatIsThisInfo").dialog({
											bgiframe: true,
											height: 250,
											width: 350
										});
									} else {
										$("#whatIsThisInfo").dialog( "open" );
									}
								});
							});
							return false;
						});
					});															
				}).dialog({
					bgiframe: true,
					height: 490,
					width: 700,
					modal: true
				});
			} else {
				$("#createAccountDialog").dialog( "open" );
			}
			return false;
	   });
	} // if ( $("#saveBaskCreateAccount").length ) {

	
	/* add explanation to "sample" text */
	$("i strong").each(function(i){
		if ( $(this).html() == "SAMPLE" ) {
			$(this).append("<span style=\"font-weight: normal;\"> - <a href=\"/includes/ajax/whereDidPersGo.php\" class=\"whereDidPersGo\">where did my personalization go?</a></span>");
		}
	});
	$(".whereDidPersGo").click(function(event){
		event.preventDefault();
		if ( !$("#whereDidPersGoExplained").length ) {
			$("body").append("<div id=\"whereDidPersGoExplained\" class=\"hideMe\" title=\"Sample Order Personalization\"></div>");
			$("#whereDidPersGoExplained").dialog({
				bgiframe: true,
				height: 210,
				width: 360,
				modal: true
			}).load( $(this).attr("href") );
		} else {
			$("#whereDidPersGoExplained").dialog("open");
		}
		return false;
	});
	$(".sampleExp").click(function(event){
		event.preventDefault();
		if ( !$("#sampleExp").length ) {
			$("body").append("<div id=\"sampleExp\" class=\"hideMe\" title=\"Sample Order Personalization\"></div>");
			$("#sampleExp").dialog({
				bgiframe: true,
				height: 210,
				width: 360,
				modal: true
			}).load( $(this).attr("href") );
		} else {
			$("#sampleExp").dialog("open");
		}
		
		return false;
	});
	/* END add explanation to "sample" text */
	
	
	
	/* Editable Basket Attributes
	* these functions taken from jquery.prod.js */
	
	
	if ( $(".textBox").length ) {
		$(".textBox").keyup(function(event){
			var length = $(this).val().length ? $(this).val().length : $(this).html().length;
			$(this).next().html( length );
			
			if ( length >= $(this).attr("maxlength") ) {
				$(this).next().removeClass("green").addClass("red");
			} else {
				$(this).next().removeClass("red").addClass("green");
			}
		});
	}
	
	$(".cartTotalsLTD p").each(function(){
		var siblingHeight = $(this).parent().prev().children("p").height();
		if ( $(this).height() != siblingHeight ) {
			$(this).height( siblingHeight );
		}
	});
	
	if ( ( $.getQueryString({id:"newButtons"}) || 1 ) && $(".baskItemsLTD label.red").length ) {
		$(".baskItemsLTD label.red").button();
		rolloverLink( $(".editOptions"), "/images/buttons/bask/edit-mouse-over.png", "/images/buttons/bask/edit.png", "/images/buttons/bask/edit-mouse-click.png" );
		rolloverLink( $(".updateCart"), "/images/buttons/bask/update-mouse-over.png", "/images/buttons/bask/update.png", "/images/buttons/bask/update-mouse-click.png" );
	}
	
}); // $(document).ready(function(){

function getStateByZip( incomingZip ) {
	// v2, returns 'CANADA' if zip appears to be in canada
	//incomingZip = incomingZip.trim();
	var result = "";
	
	/* first we have to figure out if it's a canada zip code
	* these have letters so that's the first test
	*/
	if ( !isNaN(incomingZip) ) {
		incomingZip = incomingZip.replace(/^\s+|\s+$/g, '');
		allStates = new Array();
		allStates["AK"] = "9950099929";
		allStates["AL"] = "3500036999";
		allStates["AR"] = "71600729997550275505";
		allStates["AZ"] = "8500086599";
		allStates["CA"] = "9000096199";
		allStates["CO"] = "8000081699";
		allStates["CT"] = "0600006999";
		allStates["DC"] = "20000200992020020599";
		allStates["DE"] = "1970019999";
		allStates["FL"] = "32000339993410034999";
		allStates["GA"] = "3000031999";
		allStates["HI"] = "96700967989680096899";
		allStates["IA"] = "5000052999";
		allStates["ID"] = "8320083899";
		allStates["IL"] = "6000062999";
		allStates["IN"] = "4600047999";
		allStates["KS"] = "6600067999";
		allStates["KY"] = "40000427994527545275";
		allStates["LA"] = "70000714997174971749";
		allStates["MA"] = "0100002799";
		allStates["MD"] = "20331203312060021999";
		allStates["ME"] = "038010380103804038040390004999";
		allStates["MI"] = "4800049999";
		allStates["MN"] = "5500056799";
		allStates["MO"] = "6300065899";
		allStates["MS"] = "3860039799";
		allStates["MT"] = "5900059999";
		allStates["NC"] = "2700028999";
		allStates["ND"] = "5800058899";
		allStates["NE"] = "6800069399";
		allStates["NH"] = "03000038030380903899";
		allStates["NJ"] = "0700008999";
		allStates["NM"] = "8700088499";
		allStates["NV"] = "8900089899";
		allStates["NY"] = "004000059906390063900900014999";
		allStates["OH"] = "4300045999";
		allStates["OK"] = "73000731997340074999";
		allStates["OR"] = "9700097999";
		allStates["PA"] = "1500019699";
		//allStates["PR"] = "0060000729";
		allStates["PR"] = "0060000988";
		allStates["RI"] = "02800029990637906379";
		allStates["SC"] = "2900029999";
		allStates["SD"] = "5700057799";
		allStates["TN"] = "37000385997239572395";
		allStates["TX"] = "7330073399739497394975000799998850188599";
		allStates["UT"] = "8400084799";
		allStates["VA"] = "2010520199203012030120370203702200024699";
		allStates["VT"] = "0500005999";
		allStates["WA"] = "9800099499";
		allStates["WI"] = "49936499365300054999";
		allStates["WV"] = "2470026899";
		allStates["WY"] = "8200083199";
		var zipLength;
		var segments;
		for( var i in allStates ) {
			zipLength = String( allStates[i].length );
			//$("body").append("<br>zip length: " + zipLength + "<br>");
			// the zips will be 10, 20, 30, or 40 in length
			segments = new Array();
			switch (zipLength) {
			case "10":
				segments[0] = allStates[i].substring( 0, 5 );
				segments[1] = allStates[i].substring( 5, 10 );
				break;
			case "20":
				segments[0] = allStates[i].substring( 0, 5 );
				segments[1] = allStates[i].substring( 5, 10 );
				segments[2] = allStates[i].substring( 10, 15 );
				segments[3] = allStates[i].substring( 15, 20 );
				break;
			case "30":
				segments[0] = allStates[i].substring( 0, 5 );
				segments[1] = allStates[i].substring( 5, 10 );
				segments[2] = allStates[i].substring( 10, 15 );
				segments[3] = allStates[i].substring( 15, 20 );
				segments[4] = allStates[i].substring( 20, 25 );
				segments[5] = allStates[i].substring( 25, 30 );
				break;
			case "40":
				segments[0] = allStates[i].substring( 0, 5 );
				segments[1] = allStates[i].substring( 5, 10 );
				segments[2] = allStates[i].substring( 10, 15 );
				segments[3] = allStates[i].substring( 15, 20 );
				segments[4] = allStates[i].substring( 20, 25 );
				segments[5] = allStates[i].substring( 25, 30 );
				segments[6] = allStates[i].substring( 30, 35 );
				segments[7] = allStates[i].substring( 35, 40 );
				break;
			}
			/*if ( segments[0] ) {
				$("body").append("<br>segment 1: " + segments[0] + "<br>");
			}
			if ( segments[1] ) {
				$("body").append("<br>segment 2: " + segments[1] + "<br>");
			}
			if ( segments[2] ) {
				$("body").append("<br>segment 3: " + segments[2] + "<br>");
			}
			if ( segments[3] ) {
				$("body").append("<br>segment 4: " + segments[3] + "<br>");
			}
			if ( segments[4] ) {
				$("body").append("<br>segment 5: " + segments[4] + "<br>");
			}
			if ( segments[5] ) {
				$("body").append("<br>segment 6: " + segments[5] + "<br>");
			}
			if ( segments[6] ) {
				$("body").append("<br>segment 7: " + segments[6] + "<br>");
			}
			if ( segments[7] ) {
				$("body").append("<br>segment 8: " + segments[7] + "<br>");
			}*/
			
			totalSegments = segments.length;
			for ( var j = 0; j <= totalSegments; j += 2 ) {
				if ( incomingZip >= segments[j] && incomingZip <= segments[j+1] ) {
					result = i;
					//$("body").append("<br>State Match Found: " + i + "<br>");
				}
			}
		}
	} else {
		/* it's likely that this is canadian
		* or that the user entered a letter by mistake
		*/
		// now use regex
		if ( incomingZip.match( /[a-z]\d[a-z]\d[a-z]\d/i ).length ) {
			// looks like it's canada
			//$("body").append("<br><br><br><br><br><br><br><br><br>ca zip found");
			result = "CANADA";
		}
	}
	return result;
}
