// GOOGLE ANALYTICS
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-3435371-1']);
_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);
})();

$(document).ready(function() {

// GET CURRENT DOMAIN
// we need the current domain for specific info to be used later
var currentDomain = document.domain;
var omnitureSuite = "hlthtruehealthdev";
/*
if (currentDomain[0] == "s") {
	omnitureSuite = "hlthtruehealthdev";
} else if (currentDomain[0] == "w") {
	omnitureSuite = "hlthtruehealthprod";
}
*/

// ZIP CODE LOOK UP
// grab zip code and ask aspx page for result
$("#ctl00_PageContent_ctrlBillingAddress_Zip").keyup(function() {
	// on each keyup get the current value
	var zipCode = $(this).val();
	// when value reaches 5 characters continue
	if (zipCode.length == 5) {
		// check the country, if supported country continue
		var billingCountry = $("#ctl00_PageContent_ctrlBillingAddress_Country").val();
		if (billingCountry == "UNITED STATES") {
			$.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);
					}
				},
				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() {
	var zipCode = $(this).val();
	if (zipCode.length == 5) {
		var zipCode = $(this).val();
		var shippingCountry = $("#ctl00_PageContent_ctrlShippingAddress_Country").val();
		if (shippingCountry == "UNITED STATES") {
			$.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);
					}
				},
				error: function() {
					
				}
			});
		}
	}
});

// SEARCH FIELD, LEFT COLUMN
// set the value of the search input and make it clear on focus
$(".search input[id*='SearchText']").val("Search").addClass("clearField");

// DROPDOWN MENU FOR RED NAV BAR
$(".dropdown").each(function () {
	$(this).parent().eq(0).hover(function () {
		$(".dropdown:eq(0)", this).show();
		//$(".dropdown:eq(0)", this).slideDown(250);
	}, function () {
		$(".dropdown:eq(0)", this).hide();
		//$(".dropdown:eq(0)", this).slideUp(250);
	});
});

// 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++) {
		var testString = "/" + sqlList[i] + "/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;
		}
		if (testString.match($("#sidebarEmail").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.truehealth.com/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');
		},
		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 PAGES THAT POINT TO LPs
//90 DAYS TO TRUE HEALTH PAGE
// build our link to carry source code
//var link90Days = "http://www.truehealth.com/landing/ordform/orderform.aspx?SRCCOD=" + $("#savingsCode #code").html() + "&INCNAM=KT90GB-8E2&DFTPTH=90days";
// build our link with hardcoded source code
var link90Days = "http://www.truehealth.com/landing/ordform/orderform.aspx?SRCCOD=TND9994&INCNAM=KT90GB-8E2&DFTPTH=90days";
// make medium image clickable and point to order form
$("#T90GB").css("cursor", "pointer").click(function() {
	location.href = link90Days;
});

// PRODUCT PAGE CONTENTS
// 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());
$("#productDescription").css({"position" : "absolute", "top" : "0px", "left" : "0px"});
$("#productFAQ, #productLabel, #productTestimonials, #productReviews").css({"position" : "absolute", "top" : "0px", "left" : "0px", "display" : "none"});
// get current url and show appropriate section
var currentSection = window.location.hash;
switch (currentSection) {
	case "#productDescription":
		pageNavClicked($("#pageNav-descriptionBtn"), $("#pageNav-labelBtn, #pageNav-faqBtn, #pageNav-testimonialsBtn"), $("#productDescription"), $("#productLabel, #productFAQ, #productTestimonials, #productReviews"));
		break;
	case "#productLabel":
		pageNavClicked($("#pageNav-labelBtn"), $("#pageNav-descriptionBtn, #pageNav-faqBtn, #pageNav-testimonialsBtn"), $("#productLabel"), $("#productDescription, #productFAQ, #productTestimonials, #productReviews"));
		break;
	case "#productFAQ":
		pageNavClicked($("#pageNav-faqBtn"), $("#pageNav-descriptionBtn, #pageNav-labelBtn, #pageNav-testimonialsBtn"), $("#productFAQ"), $("#productDescription, #productLabel, #productTestimonials, #productReviews"));
		break;
	case "#productTestimonials":
		pageNavClicked($("#pageNav-testimonialsBtn"), $("#pageNav-descriptionBtn, #pageNav-labelBtn, #pageNav-faqBtn"), $("#productTestimonials"), $("#productDescription, #productLabel, #productFAQ, #productReviews"));
		break;
	default:
		$("#pageNav-descriptionBtn").click();
}
// buttons
$("#pageNav-descriptionBtn").click(function() { pageNavClicked($(this), $("#pageNav-labelBtn, #pageNav-faqBtn, #pageNav-testimonialsBtn"), $("#productDescription"), $("#productLabel, #productFAQ, #productTestimonials, #productReviews")); return false; });
$("#pageNav-labelBtn").click(function() { pageNavClicked($(this), $("#pageNav-descriptionBtn, #pageNav-faqBtn, #pageNav-testimonialsBtn"), $("#productLabel"), $("#productDescription, #productFAQ, #productTestimonials, #productReviews")); return false; });
$("#pageNav-faqBtn").click(function() { pageNavClicked($(this), $("#pageNav-descriptionBtn, #pageNav-labelBtn, #pageNav-testimonialsBtn"), $("#productFAQ"), $("#productDescription, #productLabel, #productTestimonials, #productReviews")); return false; });
$("#pageNav-testimonialsBtn").click(function() { pageNavClicked($(this), $("#pageNav-descriptionBtn, #pageNav-labelBtn, #pageNav-faqBtn"), $("#productTestimonials"), $("#productDescription, #productLabel, #productFAQ, #productReviews")); return false; });
// function for page tabs
function pageNavClicked(button, buttons, section, sections) {
	// set clicked button and remove events to prevent rollover action
	button.unbind("mouseenter").unbind("mouseleave").css("background-position", "0px -50px");
	// set the other buttons to their default states and reset events
	buttons.css("background-position", "0px 0px").bind("mouseenter", function() { $(this).css("background-position", "0px -25px"); }).bind("mouseleave", function() { $(this).css("background-position", "0px 0px"); });
	// show section relevant to button clicked
	section.css("display", "block");
	// hide other sections
	sections.css("display", "none");
	// set height of parent div to match height of shown section
	$("#productPage").css("height", section.height());
	$(window).scrollTop(0);
}
// make faq label link open the label section
$(".productPageShowLabel").click(function() { pageNavClicked($("#pageNav-labelBtn"), $("#pageNav-descriptionBtn, #pageNav-faqBtn, #pageNav-testimonialsBtn"), $("#productLabel"), $("#productDescription, #productFAQ, #productTestimonials, #productReviews")); return false; });
// make label links open in new window
$("#productLabel a, #productPageImage a, .productPageShowLabel").attr("target", "_blank");


// PRODUCT RATING
// duplicates the product rating stars under the review section into the span underneath the bottle
if ($("#spnProdRating img:first-child").attr("src") == "App_Themes/skin_2/images/stare.gif") {
	
} else {
	$("#productPageReviewsStars").html($("#spnProdRating").html());
};
// make links for reviews/ratings show reviews section
$("#productPageReviews a").click(function() {
	$("#productReviews").css("display", "block");
	$("#productDescription, #productLabel, #productFAQ, #productTestimonials").css("display", "none");
	$("#pageNav-descriptionBtn, #pageNav-labelBtn, #pageNav-faqBtn, #pageNav-testimonialsBtn").css("background-position", "0px 0px").bind("mouseenter", function() { $(this).css("background-position", "0px -25px"); }).bind("mouseleave", function() { $(this).css("background-position", "0px 0px"); });
	$("#productPage").css("height", $("#productReviews").height());
	return false;
});


// FEATURED PRODUCTS - bottom of home page
// Make each product div clickable
$("#featuredProducts .product").css("cursor", "pointer").click(function() {
	location.href = $(this).children("a").attr("href");
});

// PRODUCT SPOTLIGHT - right column
var productSpotlight = function() {
	var fadeSpeed = 500;
	var fadeDelay = 5000;
	var rotateCount = 1;
	var featuredCount = $("#productSpotlight .product").length;
	var totalCount = 0;
	rotateSpotlight();
	var rotateInterval = setInterval(function() { rotateSpotlight() }, fadeDelay);
	function rotateSpotlight() {
		$("#productSpotlight .product:nth-child(" + rotateCount + ")").fadeOut(fadeSpeed, function() {
			rotateCount++;
			totalCount++;
			$("#productSpotlight .product:nth-child(" + rotateCount + ")").fadeIn(fadeSpeed);
		});
		if (rotateCount >= featuredCount) {
			rotateCount = 1;
		}
		if (totalCount == featuredCount * 3) {
			clearInterval(rotateInterval);
		}
	}
}();

});