// GOOGLE ANALYTICS
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-2782964-1']);
_gaq.push(['_setDomainName', 'none']);
_gaq.push(['_setAllowLinker', true]);
_gaq.push(['_setAllowHash', false]);
_gaq.push(['_trackPageview']);
(function() {
	var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
	ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
	var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();

// DETECT IE VERSION
var ie = (function(){
    var undef, v = 3, div = document.createElement('div');   
    while (
        div.innerHTML = '<!--[if gt IE '+(++v)+']><i></i><![endif]-->',
        div.getElementsByTagName('i')[0]
    );   
    return v> 4 ? v : undef;
}());

$(document).ready(function() {
	
// GET CURRENT DOMAIN
// we need the current domain for specific info to be used later
var currentDomain = document.domain;
var currentPage = location.pathname;
var omnitureSuite = "hlthresourcesprod";

// CANADA SHIPPING LIGHTBOX
if (currentPage.match(/checkout1.aspx/)) {
	// look for cookie
	var canadaCookie = document.cookie;
	var canadaCookieMatch = canadaCookie.match(/HRcanada=true/g);
	// if canada is chosen and cookie does not exist then carry on
	if ($("#ctl00_PageContent_ctrlShippingAddress_Country").val() == "CANADA" && !canadaCookieMatch) {
		var canadaMsg = "<h2>NOTICE!</h2><p>Health Canada restricts orders shipping into Canada to three purchased bottles of any one product. Multiple products are allowed in one order so long as they don't exceed three purchased bottles each.</p><p>If any individual product in your order exceeds three bottles of purchased product please <b><a href='/shoppingcart.aspx'>return to your shopping cart and adjust your order</a></b> at this time. If not, please proceed with checkout.</p><p>We are very sorry for any inconvenience. Questions on this policy should be directed to Health Canada.</p><p class='center' style='color: blue; text-decoration: underline; cursor: pointer;'><b>Click Anywhere to Close</b></p>";
		var canadaAlert = "NOTICE!\r\r As per Health Canada's quantity restrictions, Canadian customers can only purchase 3 bottles of each product at a time. Multiple products are allowed so long as they meet quantity restrictions. Please direct any questions or concerns to Health Canada. We are very sorry for any inconvenience.\r\r If any individual product in your order exceeds three bottles of purchased product please return to your shopping cart and adjust your order at this time. If not, please proceed with checkout.\r\r We are very sorry for any inconvenience. Questions on this policy should be directed to Health Canada.\r\r Click OK to Close";
		if (ie != 6) {
			// turn on shade
			$("#shade").width($(window).width()).height($(window).height()).css({"background-color" : "white"}).show();
			// turn on message lightbox
			$("#message").css({"width" : "400px"}).html(canadaMsg).css({
				"top" : ($(window).height() / 2) - ($("#message").height() / 2),
				"left" : ($(document).width() - $("#message").width()) / 2,
				"border" : "4px solid #A4303A",
				"background-color" : "white",
				"-moz-box-shadow" : "0px 0px 30px rgb(0, 0, 0)",
				"-o-box-shadow" : "0px 0px 30px rgb(0, 0, 0)",
				"-webkit-box-shadow" : "0px 0px 30px rgb(0, 0, 0)",
				"box-shadow" : "0px 0px 30px rgb(0, 0, 0)"
			}).show();
			// make box clickable to go away
			$("#message").click(function() {
				$(this).hide();
				$("#shade").hide();
			});
			$("#shade").click(function() {
				$(this).hide();
				$("#message").hide();
			});
		} else if (ie == 6) {
			alert(canadaAlert);
		}
		// set cookie
		document.cookie = "HRcanada=true";
	}
}

// ZIP CODE LOOK UP
if (currentPage.match(/checkout1.aspx/) || currentPage.match(/createaccount.aspx/)) {
	// states restricted to standard shipping
	var stateArray = ["AA", "AE", "AP", "AS", "FM", "GU", "MH", "MP", "PW", "PR", "VI"];
	// grab zip code and ask aspx page for result
	$("#ctl00_PageContent_ctrlBillingAddress_Zip").keyup(function(e) {
		// check the country, if supported country continue
		var billingCountry = $("#ctl00_PageContent_ctrlBillingAddress_Country").val();
		if (billingCountry == "UNITED STATES") {
			// on each keyup get the current value
			var zipCode = $(this).val();
			// check zip for letters, skip tab and backspace keypresses
			if (!/[0-9\-]/g.test(zipCode) && e.keyCode != 8 && e.keyCode != 9) {
				alert("Please enter only numbers in the Zip Code field.");
			}
			// when value reaches 5 characters continue
			if (zipCode.length == 5) {				
				$.ajax({
					type: "GET",
					url: "/CityStateFromZip.aspx",
					data: "zip=" + zipCode,
					success: function(response) {
						// grab city and state from the resulting html data
						var zipCity = $(response).find("#zipCity").html();
						var zipState = $(response).find("#zipState").html();
						// if the city/state data actually exists then insert it
						if (zipCity) {
							$("#ctl00_PageContent_ctrlBillingAddress_City").val(zipCity);
						}
						if (zipState) {
							$("#ctl00_PageContent_ctrlBillingAddress_State").val(zipState);
						}
						// check to see if shipping is same as billing, if so make change
						if ($("#ctl00_PageContent_ShippingEqualsBilling").attr("checked")) {
							if (zipCode) {
								$("#ctl00_PageContent_ctrlShippingAddress_Zip").val(zipCode);
							}
							if (zipCity) {
								$("#ctl00_PageContent_ctrlShippingAddress_City").val(zipCity);
							}
							if (zipState) {
								$("#ctl00_PageContent_ctrlShippingAddress_State").val(zipState);
								checkShippingState();
							}
						}
					},
					error: function() {
						// no error response at the moment, just here for potential future use
					}
				});
			}
		}
	});
	// see comments above, same code different input
	$("#ctl00_PageContent_ctrlShippingAddress_Zip").keyup(function(e) {
		var zipCode = $(this).val();
		var shippingCountry = $("#ctl00_PageContent_ctrlShippingAddress_Country").val();
		if (shippingCountry == "UNITED STATES") {
			if (!/[0-9\-]/g.test(zipCode) && e.keyCode != 8 && e.keyCode != 9) {
				alert("Please enter only numbers in the Zip Code field.");
			}
			if (zipCode.length == 5) {			
				$.ajax({
					type: "GET",
					url: "/CityStateFromZip.aspx",
					data: "zip=" + zipCode,
					success: function(response) {
						var zipCity = $(response).find("#zipCity").html();
						var zipState = $(response).find("#zipState").html();
						if (zipCity) {
							$("#ctl00_PageContent_ctrlShippingAddress_City").val(zipCity);
						}
						if (zipState) {
							$("#ctl00_PageContent_ctrlShippingAddress_State").val(zipState);
						}
						// check state for shipping options
						checkShippingState();
					},
					error: function() {
						// no error response at the moment, just here for potential future use
					}
				});
			}
		}
	});
}

// DROPDOWN MENU FOR RED NAV BAR
$(".dropdown").each(function () {
	$(this).parent().eq(0).hover(function () {
		$(".dropdown:eq(0)", this).show();
	}, function () {
		$(".dropdown:eq(0)", this).hide();
	});
});

// CLEAR INPUT FIELDS SECTION
// Look through all input fields for any that have "clearField" as a class name.
// If found assign the onfocus and onblur events to them.
$(".clearField").each(function() {
	$(this).data("defaultValue", $(this).val());
}).focus(function() {
	if ($(this).val() == $(this).data("defaultValue")) {
		$(this).val("");
	}
}).blur(function() {
	if (!$(this).val()) {
		$(this).val($(this).data("defaultValue"));
	}
});

// SIGNUP FORM
// Prevent default function of submit button and force submission to signup page
$("#sidebarButton").click(function() {
	var string = "SGNTYP=" + $("input[name=SGNTYP]").val() + "&SRCCOD=" + $("input[name=SRCCOD]").val() + "&SGNNAM=" + $("input[name=SGNNAM]").val() + "&EMLADR=" + $("input[name=EMLADR]").val();
	var emailRegex = /^[a-z0-9-_\.+]+@[a-z0-9-_\.]+\.[a-z]{2,4}/i;
	var sqlList = [/select\b/i, /insert\b/i, /delete\b/i, /updated\b/i, /exec\b/i, /declare\b/i, /boot\b/i, /fetch\b/i, /or\b/i, /union\b/i, /drop\b/i, /;/, /:/, /"/, /'/, /\//];
	// check name, if default change to blank			
	if ($("#sidebarName").val() == "First Name") {
		alert("Please enter your first name!");
		$("#sidebarName").focus();
		return false;
	}
	// make sure they didn't insert an email address in first name field
	if (emailRegex.test($("#sidebarName").val())) {
		alert("It appears you inserted an email address in the First Name field.");
		$("#sidebarName").focus();
		return false;
	}
	// check for SQL injection attempt
	for (var i = 0; i < sqlList.length; i++) {
		if (sqlList[i].test($("#sidebarName").val())) {
			//alert("Due to security concerns " + sqlList[i].toString().toUpperCase().replace(/(\/)(.*[a-z])(\\b\/i)/i, "$2") + " is not allowed!");
			$("#sidebarName").val($("#sidebarName").data("defaultValue"));
			$("#sidebarEmail").val($("#sidebarEmail").data("defaultValue"));
			return false;
		}
	}
	// check email
	if (!emailRegex.test($("#sidebarEmail").val())) {
		alert("Please insert a valid email address!");
		$("#sidebarEmail").focus();
		return false;
	}
	$.ajax({
		type: "GET",
		url: "http://www.healthresources.net/landing/signup/SGNUPS.aspx",
		data: string,
		beforeSend: function() {
			$("#sidebarSignup").fadeTo(200, 0.25).unbind("click");
		},
		success: function() {
			$("#sidebarSignup").fadeOut(200);
			$("#sidebarThanks").delay(200).fadeIn(200).html("<br /><b>Thank you!<br /> Your subscription<br /> has been received.</b>");
			// omniture
			var s = s_gi(omnitureSuite);
			s.linkTrackVars = "events, prop4, pageName";
			s.linkTrackEvents = "event4";
			s.events = "event4"
			s.prop4 = "newsletter:success";
			s.pageName = "newsletter:success";
			s.tl(this,"o",'newsletter-submit');
			// kenshoo
			kenshoo_conv('news','25','', currentSource, 'USD');
		},
		error: function() {
			$("#sidebarSignup").fadeOut(200);
			$("#sidebarThanks").delay(200).fadeIn(200).html("<br /><b>Sorry!<br /> There was an error,<br /> please try again later.</b>");
			// omniture
			var s = s_gi(omnitureSuite);
			s.linkTrackVars = "events, prop4, pageName";
			s.linkTrackEvents = "event4";
			s.events = "event4"
			s.prop4 = "newsletter:error";
			s.pageName = "newsletter:error";
			s.tl(this,"o",'newsletter-submit');
		}
	});
	return false;
});

// PRODUCT PAGE CONTENTS
if (currentPage.match(/\/p-/)) {
	// Makes links at top of product page more like tabs for each section
	// some defaults
	$("#pageNav-descriptionBtn").css("background-position", "0px -50px");
	$("#productPage").css("height", $("#productDescription").height() + 50);
	$("#productDescription").css({"position" : "absolute", "top" : "0px", "left" : "0px"});
	$("#productFAQ, #productLabel, #productReviews").css({"position" : "absolute", "top" : "0px", "display" : "none"});
	var productPageDefaultHeight = 1000;
	
	// tabs
	$("#pageNav-descriptionBtn").click(function() {
		$("#productDescription, #productLabel, #productFAQ, #productReviews").css("display", "none");
		$("#productDescription").css("display", "block");
		
		$("#productDescription").height() < productPageDefaultHeight ? $("#productPage").height(productPageDefaultHeight) : $("#productPage").height($("#productDescription").height() + 50);
	
		$("#pageNav-descriptionBtn, #pageNav-labelBtn, #pageNav-faqBtn, #pageNav-reviewsBtn").css("background-position", "0px 0px");
		$("#pageNav-descriptionBtn").css("background-position", "0px -50px").unbind("mouseenter").unbind("mouseleave");
		$("#pageNav-labelBtn, #pageNav-faqBtn, #pageNav-reviewsBtn").bind("mouseenter", function() { $(this).css("background-position", "0px -25px"); }).bind("mouseleave", function() { $(this).css("background-position", "0px 0px"); });
		return false;
	});
	$("#pageNav-labelBtn").click(function() {
		$("#productDescription, #productLabel, #productFAQ, #productReviews").css("display", "none");
		$("#productLabel").css("display", "block");
		
		$("#productLabel").height() < productPageDefaultHeight ? $("#productPage").height(productPageDefaultHeight) : $("#productPage").height($("#productLabel").height());
		
		$("#pageNav-descriptionBtn, #pageNav-labelBtn, #pageNav-faqBtn, #pageNav-reviewsBtn").css("background-position", "0px 0px");
		$("#pageNav-labelBtn").css("background-position", "0px -50px").unbind("mouseenter").unbind("mouseleave");
		$("#pageNav-descriptionBtn, #pageNav-faqBtn, #pageNav-reviewsBtn").bind("mouseenter", function() { $(this).css("background-position", "0px -25px"); }).bind("mouseleave", function() { $(this).css("background-position", "0px 0px"); });
		return false;
	});
	$("#pageNav-faqBtn").click(function() {
		$("#productDescription, #productLabel, #productFAQ, #productReviews").css("display", "none");
		$("#productFAQ").css("display", "block");
		
		$("#productFAQ").height() < productPageDefaultHeight ? $("#productPage").height(productPageDefaultHeight) : $("#productPage").height($("#productFAQ").height());
		
		$("#pageNav-descriptionBtn, #pageNav-labelBtn, #pageNav-faqBtn, #pageNav-reviewsBtn").css("background-position", "0px 0px");
		$("#pageNav-faqBtn").css("background-position", "0px -50px").unbind("mouseenter").unbind("mouseleave");
		$("#pageNav-descriptionBtn, #pageNav-labelBtn, #pageNav-reviewsBtn").bind("mouseenter", function() { $(this).css("background-position", "0px -25px"); }).bind("mouseleave", function() { $(this).css("background-position", "0px 0px"); });
		return false;
	});
	$("#pageNav-reviewsBtn").click(function() {
		$("#productDescription, #productLabel, #productFAQ, #productReviews").css("display", "none");
		$("#productReviews").css("display", "block");
		
		$("#productReviews").height() < productPageDefaultHeight ? $("#productPage").height(productPageDefaultHeight) : $("#productPage").height($("#productReviews").height());
		
		$("#pageNav-descriptionBtn, #pageNav-labelBtn, #pageNav-faqBtn, #pageNav-reviewsBtn").css("background-position", "0px 0px");
		$("#pageNav-reviewsBtn").css("background-position", "0px -50px").unbind("mouseenter").unbind("mouseleave");
		$("#pageNav-descriptionBtn, #pageNav-labelBtn, #pageNav-faqBtn").bind("mouseenter", function() { $(this).css("background-position", "0px -25px"); }).bind("mouseleave", function() { $(this).css("background-position", "0px 0px"); });
		return false;
	});
	// make faq label link open the label section
	$(".productPageShowLabel").click(function() { 
		$("#productDescription, #productLabel, #productFAQ, #productReviews").css("display", "none");
		$("#productLabel").css("display", "block");		
		$("#productLabel").height() < productPageDefaultHeight ? $("#productPage").height(productPageDefaultHeight) : $("#productPage").height($("#productLabel").height());		
		$("#pageNav-descriptionBtn, #pageNav-labelBtn, #pageNav-faqBtn, #pageNav-reviewsBtn").css("background-position", "0px 0px");
		$("#pageNav-labelBtn").css("background-position", "0px -50px").unbind("mouseenter").unbind("mouseleave");
		$("#pageNav-descriptionBtn, #pageNav-faqBtn, #pageNav-reviewsBtn").bind("mouseenter", function() { $(this).css("background-position", "0px -25px"); }).bind("mouseleave", function() { $(this).css("background-position", "0px 0px"); });
		$(document).scrollTop(200);
		return false;
	});
	// make label links open in new window
	$("#productLabel a, #productPageImage a, .productPageShowLabel").attr("target", "_blank");
}

// PROMOTION BOX
if (currentPage.match(/promotion.aspx/)) {
	// force upper case because it just looks better
	$("#ctl00_PageContent_SRCCOD").ready(function() {
		$("#ctl00_PageContent_SRCCOD").keyup(function() {
			var temp = $(this).val();
			$(this).val(temp.toUpperCase());
		});
	});
}

// PRODUCT PAGE BURST
// check for product page, against default offer and for specific items
if (currentPage.match(/p-/) && currentOffer != "W0WHEZ00" && !currentPage.match(/airwise/) && !currentPage.match(/breathe-better-for-life/) && !currentPage.match(/holofiber/) && !currentPage.match(/resplenish/) && !currentPage.match(/waterwise/)) {
	var noProductOfferMatch;
	// get json messages right away
	$.getJSON("jscripts/offerMessages.json", function(json) {
		// test each entry against current offer
		$.each(json, function(key, val) {
			if (key == currentOffer) {
				$(".productBurst").css("display", "block");
				$(".productBurstText").css("display", "block").html(val);
				if (ie == 7) {
					$(".productBurstText").css("padding-top", "26px");
				}
				noProductOffermatch = false;
				return false;
			} else {
				noProductOfferMatch = true;
			}
		});
		// if no offer match then look for percentage instead
		// fix this after 12/4/11!!!
		if (noProductOfferMatch) {
			var productDiscounts = $(".discountprice");
			var productBurstDiscount = $(productDiscounts[productDiscounts.length - 1]).html();
			if (productBurstDiscount && productBurstDiscount.match(/%/)) {
				// if discount display has a % then show it in burst
				$(".productBurst").css("display", "block");
				$(".productBurstText").html("<div style='font-size: 22px; padding-left: 3px;'>Up To<br /><span style='font-size: 26px;'>" + productBurstDiscount + "</span></div>").css("display", "block");
				if (ie == 7) {
					$(".productBurstText").css("padding-top", "26px");
				}
			}
		}
	});
}

// PRODUCT CATEGORY BURST
// check for category or sales page and against default offer
if (currentPage.match(/c-/) || currentPage.match(/on-sale/) && currentOffer != "W0WHEZ00") {
	var noCategoryOfferMatch;
	// get json messages
	$.getJSON("jscripts/offerMessages.json", function(json) {
		$(".categoryProduct, .saleProduct").each(function(index) {
			var currentProduct = this;
			var currentProductDesc = $(this).children(".productDesc").html();
			// look for products not needing burst
			if (!currentProductDesc.match(/airwise/) && !currentProductDesc.match(/Breathe Better/)  && !currentProductDesc.match(/holofiber/) && !currentProductDesc.match(/resplenish/) && !currentProductDesc.match(/waterwise/)) {
				$.each(json, function(key, val) {
					if (key == currentOffer) {
						$(currentProduct).children(".productImage").children(".categoryBurst").css("display", "block");
						$(currentProduct).children(".productImage").children(".categoryBurstText").css("display", "block").html(val);
						if (ie == 7) {
							$(currentProduct).children(".productImage").children(".categoryBurstText").css("padding-top", "16px");
						}
						noCategoryOffermatch = false;
						return false;
					}  else {
						noCategoryOfferMatch = true;
					}
				});
			}
		});
		// if no offer match then look for percentages instead
		if (noCategoryOfferMatch) {
			$(".categoryProduct, .saleProduct").each(function() {
				var categoryDiscounts = $(this).find(".discountprice");
				var categoryBurstDiscount = $(categoryDiscounts[categoryDiscounts.length - 1]).html();
				if (categoryBurstDiscount != null && categoryBurstDiscount.match(/%/)) {
					// if each discount display has a % then show it in bursts
					$(this).find(".categoryBurst").css("display", "block");
					$(this).find(".categoryBurstText").html("<div>Up To<br /><span>" + categoryBurstDiscount + "</span></div>").css("display", "block");
					if (ie == 7) {
						$(this).find(".categoryBurstText").css("padding-top", "16px");
					}
				}
			});
		}
	});	
}

// KENSHOO DOWNLOAD CATALOG CONVERSION
// check for catalog request page
if (currentPage.match(/catalogrequest/)) {
	// wait for click on download button
	$("#downloadCatalog").click(function() {
		kenshoo_conv('catalog','50','orderId', currentSource, 'USD');
		setTimeout(function() {
			location.href = "http://www.healthresources.net/files/HR-Catalog.pdf";
		}, 500);
		return false;
	});
}

// KENSHOO BASE FUNCTION
function kVoid() { return; }
function kenshoo_conv(type,value,orderId,promoCode,valueCurrency) {
	var hostProtocol = (("https:" == document.location.protocol) ? "https" : "http");
	var url = hostProtocol + "://105.xg4ken.com/media/redir.php?track=1&id=4ba54b91-9109-4e7b-a050-ae994fa210f9&type=" + type + "&val=" + value + "&orderId=" + orderId + "&valueCurrency=" + valueCurrency +"&promoCode=" + promoCode + "&ref=" + document.referrer;
	var a = new Image(1,1);
	a.src = url;
	a.onload = function() { kVoid(); }
}

});
