// GOOGLE ANALYTICS
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-3435371-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() {
	
var currentDomain = document.domain;
var currentPage = location.pathname;
var omnitureSuite = "hlthtruehealthprod";

// 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"));
	}
});

// PRODUCT PAGE BURST
// check for product page, against default offer and for specific items
/* temp disabled 2/17
if (currentPage.match(/p-/) && !currentPage.match(/ultimate-krill-q/) && !currentPage.match(/waterwise/)) {
	var noProductOfferMatch = true;
	// get json messages right away
	$.getJSON("/template/js/offerBursts.json", function(json) {
		// test each entry against current offer
		$.each(json, function(key, val) {
			if (key === currentOffer) {
				$("#productBurst").css("display", "block").html(val);
				noProductOfferMatch = false;
				return false;
			}
		});
		// if no offer match then look for percentage instead
		if (noProductOfferMatch) {
			var productDiscounts = $(".discountprice");
			var productBurstDiscount = $(productDiscounts[productDiscounts.length - 1]).html();
			if (productBurstDiscount && productBurstDiscount.match(/%/)) {
				$("#productBurst").css("display", "block").html("<div class='productBurstPercent'>Save Up To<br /><span>" + productBurstDiscount + "!</span></div>");
			}
		}
	});
}
*/

// SIGNUP FORM
// Prevent default function of submit button and force submission to signup page
$("#signupSubmit").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 ($("#signupName").val() == "First Name") {
		alert("Please enter your first name!");
		$("#signupName").focus();
		return false;
	}
	// make sure they didn't insert an email address in first name field
	if (emailRegex.test($("#signupName").val())) {
		alert("It appears you inserted an email address in the First Name field.");
		$("#signupName").focus();
		return false;
	}
	// check for SQL injection attempt
	for (var i = 0; i < sqlList.length; i++) {
		if (sqlList[i].test($("#signupName").val())) {
			//alert("Due to security concerns " + sqlList[i].toString().toUpperCase().replace(/(\/)(.*[a-z])(\\b\/i)/i, "$2") + " is not allowed!");
			$("#signupName").val($("#signupName").data("defaultValue"));
			$("#signupEmail").val($("#signupEmail").data("defaultValue"));
			return false;
		}
	}
	// check email
	if (!emailRegex.test($("#signupEmail").val())) {
		alert("Please insert a valid email address!");
		$("#signupEmail").focus();
		return false;
	}
	$.ajax({
		type: "GET",
		url: "http://www.truehealth.com/landing/signup/SGNUPS.aspx",
		data: string,
		beforeSend: function() {
			$("#signupSignup").fadeTo(200, 0.25).unbind("click");
		},
		success: function() {
			$("#signupBox").fadeOut(200);
			$("#signupThanks").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() {
			$("#signupBox").fadeOut(200);
			$("#signupThanks").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;
});

// 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.truehealth.com/files/TH-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=283df0e6-9b63-4040-ba88-4b0a3f7c368c&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(); }
}

// COMMON LISTS TO COLUMNIZE
columnize($("#productsTab ul"), 4, 230);
columnize($("#categoriesTab ul"), 2, 460);

});

// COLUMNIZE LISTS FUNCTION
function columnize(list, columnNumber, columnWidth) {
	
	// remove float from list items
	list.children("li").css("float", "none");
	
	// how many list items per column
	var itemsNumber = Math.ceil(list.children("li").length / columnNumber);
	// natural height of list items
	var itemsHeight = parseInt(list.children("li").height());
	// top margin height of list items
	var itemsMarginHeight = parseInt(list.children("li").css("margin-top"));
	// top + bottom padding height of list items
	var itemsPaddingHeight = parseInt(list.children("li").css("padding-top")) + parseInt(list.children("li").css("padding-bottom"));
	var count = 1;
	
	// go through each list item to set position as needed
	list.children("li").each(function(i) {
		
		// find the first list item in each column and adjust margin-top to push it up to line up with top
		if (i === itemsNumber * count) {		
			$(this).css("margin-top", -((itemsHeight + itemsMarginHeight + itemsPaddingHeight) * itemsNumber));
		}
		
		// increase count as needed
		if (i > itemsNumber * count - 1) {
			count++;
		}
		
		// move each new column to right required distance
		$(this).css("margin-left", columnWidth * count - columnWidth);	
		
	});
	
	// adjust height of containing list as needed
	list.css("height", (itemsHeight + itemsMarginHeight + itemsPaddingHeight) * itemsNumber);
	
}
