function TimeoutWindow() {
	setTimeout(function () {
		tb_show("Processing...", "/TimeoutWindow.aspx?KeepThis=true&TB_iframe=true&height=200&width=500&modal=true");
	}, 10000);
	return false;
}

function encodeXmlAttribute(c) {
	return c.replace(new RegExp('"', 'g'), '&quot;');
}

//- FindPosX -//
function FindPosX(obj) {
	var curleft = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	}
	else if (obj.x)
		curleft += obj.x;
	return curleft;
}

//- FindPosY -//
function FindPosY(obj) {
	var curtop = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	}
	else if (obj.y)
		curtop += obj.y;
	return curtop;
}

function CreateRequestObject() {
	if (navigator.appName == "Microsoft Internet Explorer") {
		return new ActiveXObject("Microsoft.XMLHTTP");
	}
	return new XMLHttpRequest();
}

//- IfEnterAction -//
function IfEnterAction(oEvent, oForm, cAction, cSelId) {
	if ((EventKeyCode(oEvent) == 13) || (EventKeyCode(oEvent) == 3)) {
		oForm.Action.value = cAction;
		oForm.SelId.value = cSelId;
		oForm.submit();
		return false;
	}
	return true;
}

//- IfEnterScript -//
function IfEnterScript(oEvent, cScript) {
	if ((EventKeyCode(oEvent) == 13) || (EventKeyCode(oEvent) == 3)) {
		eval(cScript);
		return false;
	}
	return true;
}

function IfEnterCallback(oEvent, callback) {
	if ((EventKeyCode(oEvent) == 13) || (EventKeyCode(oEvent) == 3)) {
		callback();
		return false;
	}
	return true;
}

//- EventKeyCode -//
function EventKeyCode(oEvent) {
	return ((oEvent != null) && (oEvent.which != null) ? oEvent.which : event.keyCode);
}

//- ExportZip -//
function ExportZip(cStream) {
	var cZip = cStream.replace(/\?/g, '');
	return cZip;
}

//- ExportFon -//
function ExportFon(cStream) {
	var cFon = '';
	if (cStream.length >= 10) {
		cFon = cStream.substr(0, 3) + '-' + cStream.substr(3, 3) + '-' + cStream.substr(6, 4)
		if ((cStream.length == 15) && (cStream.substr(10, 5) != '?????')) {
			cFon += ' x' + cStream.substr(10, 5).replace('?', '')
		}
	}
	return cFon;
}

//- Console_AddRemove -//
function Console_AddRemove(oFromSet, oToSet, bIsAll) {
	//+ unselect
	for (var hOption = 0; hOption < oToSet.length; hOption++) {
		oToSet.options[hOption].selected = false;
	}
	//+ move
	for (hOption = oFromSet.length; hOption != 0; hOption--) {
		if ((bIsAll == true) || (oFromSet.options[hOption - 1].selected == true)) {
			oToSet.options[oToSet.length] = new Option(oFromSet.options[hOption - 1].text, oFromSet.options[hOption - 1].value, false, true);
			oFromSet.options[hOption - 1] = null;
		}
	}
}
//- Console_Pack -//
function Console_Pack(oSet, oField) {
	var cPack = '';
	for (var hOption = 0; hOption < oSet.length; hOption++) {
		cPack += ',' + oSet.options[hOption].value;
	}
	oField.value = cPack.substring(1);
}

//- ToggleCriteriaView -//
function ToggleCriteriaView(cBlock, cFieldName, cCriteria) {
	var oElement = document.getElementById(cBlock);
	var oField = document.getElementById(cFieldName);
	var cValue = ((oField.type == 'checkbox') ? oField.checked.toString() : oField.value);
	var bIsTrue = false;
	if (cCriteria.indexOf('|') >= 0) {
		var cArray = cCriteria.split('|');
		for (i = 0; i < cArray.length; i++) {
			if ((cArray[i].length > 0) && (cArray[i].indexOf('!') >= 0)) {
				if (cValue != cArray[i].substr(1, cArray[i].length)) {
					bIsTrue = true;
					break;
				}
			} else if (cValue == cArray[i]) {
				bIsTrue = true;
				break;
			}
		}
	} else if (cCriteria.indexOf('&') >= 0) {
		var cArray = cCriteria.split('&');
		for (i = 0; i < cArray.length; i++) {
			if ((cArray[i].length > 0) && (cArray[i].indexOf('!') >= 0)) {
				if (cValue != cArray[i].substr(1, cArray[i].length)) {
					bIsTrue = true;
				} else {
					bIsTrue = false;
					break;
				}
			} else if (cValue != cArray[i]) {
				bIsTrue = true;
			} else {
				bIsTrue = false;
				break;
			}
		}
	} else {
		if (cCriteria.indexOf('!') >= 0) {
			if (cValue != cCriteria.substr(1, cCriteria.length)) {
				bIsTrue = true;
			} else {
				bIsTrue = false;
			}
		} else if (cValue == cCriteria) {
			bIsTrue = true;
		} else {
			bIsTrue = false;
		}
	}
	if (bIsTrue == true) {
		oElement.style.display = 'block';
	} else {
		oElement.style.display = 'none';
	}
}

//- ToggleView -//
function ToggleView(cBlock) {
	var oElement = document.getElementById(cBlock);
	if (oElement.style.display == 'none') {
		oElement.style.display = 'block';
	} else {
		oElement.style.display = 'none';
	}
}

//- ShowItemField -// 
function ShowItemField(cKey, bIsShow) {
	var cRowStyleType = 'table-row';
	if (navigator.appName == 'Microsoft Internet Explorer') {
		cRowStyleType = 'block';
	}
	if (bIsShow == true) {
		document.getElementById(cKey).style.display = cRowStyleType;
	} else {
		document.getElementById(cKey).style.display = 'none';
	}
}

function PNGTransparent(cId, cClass) {
	var arVersion = navigator.appVersion.split("MSIE");
	var version = parseFloat(arVersion[1]);
	if ((version >= 5.5) && (version < 7.0)) {
		document.getElementById(cId).style.background = 'none';
		document.getElementById(cId).className = cClass;
	}
}

//-
function OpenWhatIsQuickBuy() {
	var h = window.open('/Product/WhatIsQuickBuy.asp', 'Product_Wnd', 'width=500,height=275,resizable=yes')
}
//-
function OpenNutrition(cIds, cId) {
	var h = window.open('/Product/Nutrition.asp?Ids=' + cIds + '&ProductGroupKey=' + cId + '&~=', 'Nutrition_Wnd', 'width=600,height=525,scrollbars=1;resizable=yes');
	h.focus();
}
//-
function OpenShippingDetail(cIds) {
	var h = window.open('/Cart/ShippingDetail.asp?Ids=' + cIds, 'ShippingDetail', 'width=500,height=500,scrollbars=1,resizable=yes,scrollbars=1')
}
//-
function OpenPriorityCodeExplanation(cIds) {
	var h = window.open('/Cart/PriorityCode.asp?Ids=' + cIds, 'PriorityCode', 'width=500,height=275,resizable=yes,scrollbars=1')
}

function OpenCommercialAddressExplanation(cIds) {
	var h = window.open('/Cart/CommercialAddress.asp?Ids=' + cIds, 'PriorityCode', 'width=500,height=275,resizable=yes,scrollbars=1')
}

//-
function OpenAddressBookImport(cIds, cId) {
	var h = window.open('/Cart/AddressBookImport.asp?Ids=' + cIds + '&~=', 'Nutrition_Wnd', 'width=600,height=525,resizable=yes,scrollbars=1');
	h.focus();
}

//-
function OpenWhatIsGiftList(cIds) {
	var h = window.open('/Cart/WhatIsGiftList.asp?Ids=' + cIds + '&~=', 'WhatIsGiftList_Wnd', 'width=600,height=525,resizable=yes,scrollbars=1');
	h.focus();
}

//-
function OpenWhatIsCVV2(cIds) {
	var h = window.open('/Cart/WhatIsCVV2.asp?Ids=' + cIds + '&~=', 'WhatIsCVV2_Wnd', 'width=600,height=525,resizable=yes,scrollbars=1');
	h.focus();
}

//-
function OpenWhyRecipientEmail(cIds) {
	var h = window.open('/Cart/WhyRecipientEmail.asp?Ids=' + cIds + '&~=', 'WhyRecipientEmail_Wnd', 'width=600,height=325,resizable=yes,scrollbars=1');
	h.focus();
}

//-
function OpenWhatIsGiftList2(cIds) {
	var h = window.open('/GiftList/WhatIsGiftList.asp?Ids=' + cIds + '&~=', 'WhatIsGiftList_Wnd', 'width=600,height=525,resizable=yes,scrollbars=1');
	h.focus();
}

function showOfferDetail(o) {
	/*
	var obj = o.offsetParent;
	var nHeight = $(o).height();
	var nWidth = $('#BannerOfferTD').width();
	var nLeft = findPos(obj).x;
	var nTop = findPos(o).y + nHeight;
	$('#OfferDetail').css({left: nLeft + 'px', top: nTop + 'px', width: nWidth + 'px'});
	*/
	$('#OfferDetail').slideDown(250, function () {
		$(document).bind("click", function () {
			if ($('#OfferDetail').css("display") != 'none') {
				$('#OfferDetail').slideUp(250);
			}
			$(document).unbind("click");
		});
	});
}

function findPos(obj) {
	var curleft = curtop = 0;
	if (obj.offsetParent) {
		curleft = obj.offsetLeft
		curtop = obj.offsetTop
		while (obj = obj.offsetParent) {
			curleft += obj.offsetLeft
			curtop += obj.offsetTop
		}
	}
	return { x: curleft, y: curtop };
}

var g_isCartSummaryVisible = false;

function ToggleCartSummary() {
	var image = document.getElementById('CartSummaryToggle');
	image.src = '/_Project/_Block/Engine/Action/' + ((g_isCartSummaryVisible == true) ? 'Expand_O.gif' : 'Contract_O.gif');
	if (g_isCartSummaryVisible == true) {
		$('#CartSummaryDiv').slideUp(250);
	} else {
		$('#CartSummaryDiv').slideDown(250);
	}
	g_isCartSummaryVisible = !g_isCartSummaryVisible;
}

function UpdateCartSummary(ids) {
	$.get('/Cart/Summary.asp', {}, function (data) {
		document.getElementById('CartSummaryDiv').innerHTML = data
	});
}

function ToggleProductCategory(uid) {
	var image = document.getElementById('ProductCategoryExpand' + uid);
	var div = document.getElementById('SubCategory' + uid);
	var bVis = ($(div).css("display") == "block") ? true : false;
	image.src = '/_Project/_Block/Engine/Action/' + ((bVis == true) ? 'Expand_O.gif' : 'Contract_O.gif');
	if (bVis == true) {
		$(div).slideUp(250);
	} else {
		$(div).slideDown(250);
	}
}

function ToggleCategoryList(path, id) {
	var div = document.getElementById(id);
	//	var image = document.getElementById('OurProductsImage');
	var bVis = ($(div).css("display") == "block") ? true : false;
	//	image.src = path + ((bVis == true) ? 'OurProducts_X.gif' : 'OurProducts_O.gif');
	if (bVis == true) {
		$(div).slideUp(250);
	} else {
		$(div).slideDown(250);
	}
}

function ShowOverlay(id, nIndex) {
	try {
		if (typeof document.body.style.maxHeight === "undefined") {//if IE 6
			/*
			$("body", "html").css({ height: "100%", width: "100%" });
			$("html").css("overflow", "hidden");
			*/
			if (document.getElementById("TB_HideSelect") === null) {//iframe to hide select elements in ie6
                $("body").append("<div id='TB_overlay' style='display: none;'></div>");
				$("#TB_overlay").click(function () { HideOverlay(id); });
			}
		} else {//all others
			if (document.getElementById("TB_overlay") === null) {
				$("body").append("<div id='TB_overlay'></div>");
				$("#TB_overlay").click(function () { HideOverlay(id); });
			}
		}
		$("#TB_overlay").css("opacity", "0");
        $("#TB_overlay").fadeTo(250, 0.25, function() { $("#TB_overlay").css("opacity", "0.25"); $("#" + id).css({ display: "block" }); setTimeout("UpdateCalendarHeader(" + nIndex + ");", 500); });
	} catch (o) {
	}
}

function UpdateCalendarHeader(nIndex) {
	if (nIndex == 0) {
		return;
	}
	var cHeader = '';
	if ($('#DeliveryType_Calendar_' + nIndex).attr('value') == 'OneDay') {
		cHeader = 'Overnight Delivery Dates';
	} else {
		cHeader = 'Standard Delivery Dates';
	}
	$('#DeliveryDateHeader_' + nIndex).html(cHeader);
}

function HideOverlay(id) {
	try {
		$("#TB_overlay").unbind("click");
		if (typeof document.body.style.maxHeight == "undefined") {//if IE 6
			$("body", "html").css({ height: "auto", width: "auto" });
			$("html").css("overflow", "");
		}
		document.onkeydown = "";
		$("#TB_overlay").fadeTo(250, 0, function () { $('#TB_overlay,#TB_HideSelect').remove(); });
		//$("#TB_overlay").animate({opacity: "hide"}, 250, function(){$('#TB_overlay,#TB_HideSelect').remove();});
		$("#" + id).css({ display: "none" });
	} catch (o) {
	}
	RefreshShippingInfo(id.replace('DivCalendar_', ''));
}

function ShowTentativeMessage(date, parent) {
	$.get('/Cart/Data.asp?DataMethod=TentativeMessage&Date=' + date, function (data) {
		//		try {
		//var pos = findPos(document.getElementById(parent));
		document.getElementById('TentativeMessageDiv').innerHTML = data;
		//$('#TentativeMessageDiv').css({ top: pos.y + 'px', left: (pos.x + 150) + 'px' });
		var nPosX = ($(window).width() / 2) - ($('#TentativeMessageDiv').width() / 2);
		var nPosY = ($(window).height() / 2) - ($('#TentativeMessageDiv').height() / 2);
		$('#TentativeMessageDiv').css({ top: nPosY + 'px', left: nPosX + 'px' });
		ShowOverlay('TentativeMessageDiv', 0);
		//		} catch (e) {
		//		}
	});
}

function ValidateProductAdd(id) {
	if (document.getElementById('ShipToName' + id).value == '') {
		//		$('#NoRecipientSelectedErrorHref').click();
		tb_show('Oops...', $('#NoRecipientSelectedErrorHref').attr('href'), false);
		return false;
	}
	if (document.getElementById('SizePrice' + id).value == 0) {
		//		$('#NoProductSelectedErrorHref').click();
		tb_show('Please correct the errors below:', $('#NoProductSelectedErrorHref').attr('href'), false);
		return false;
	}
	return true;
}

function AddRequiredImageLeft(target, offsetTop) {
	var img = $('<img src="/_PROJECT/_Block/Frame/red-right-arrow.png" style="position:absolute;display:none" class="error_image" />');
	target.parent().append(img);
	var soffset = target.offset();
	img.css({ left: soffset.left - 50, top: soffset.top + offsetTop }).show();
	img.animate({
		left: '+=30'
	}, 500, 'swing', null);
	img.animate({
		left: '-=15'
	}, 300, 'swing', null);
	img.animate({
		left: '+=15'
	}, 300, 'swing', null);
	img.animate({
		left: '-=7'
	}, 200, 'swing', null);
	img.animate({
		left: '+=7'
	}, 200, 'swing', null);
}

function ValidateCreditCardNumber(ccnum) {
	var number = ccnum.replace(/\s+/g, '');	
	
	//reject if not 14-16 digits
	if (!number.match(/^\d{14,16}$/)) {
		return false;
	}	
	// convert to array and reverse the number	
	number = number.split('').reverse().join('');	
	// use lund10 to validate
	var digits = '';
	for (var i = 0; i < number.length; i++) {
		digits += '' + ((i % 2)
			? number.charAt(i) * 2
			: number.charAt(i));
	}	
	// add all of the single digits together	
	var sum = 0 ;	
	for (var i = 0; i < digits.length; i++){		
	sum += (digits.charAt(i) * 1) ;	}	
	//alert(sum) ;	
	// valid card numbers will be transformed into	
	// a multiple of 10	
	return (sum % 10) ? false : true ;
}

function ValidateCheckout() {
	//clear all the validation errors
	$('.error_image').remove();
	var cvv2RegEx = /^\d{3,4}$/;

	var paymentType = $('input:radio[name=AuthorizeNetPaymentProfileId]:checked').val();
	switch (paymentType) {
		case 'CreditCard':
			var cardSelect = $('#existing_card_select');
			var isExisting = cardSelect.val();
			if (isExisting) {
				var securityCode = $('#existing_security_code');
				if ($('#existing_card_select option:selected').text().indexOf('EXPIRED') >= 0) {
					alert('Credit card is expired.');
					AddRequiredImageLeft(cardSelect, 3);
					return false;
				}
				if (!securityCode.val()) {
					alert('Please complete the required fields.');
					AddRequiredImageLeft(securityCode, 3);
					return false;
				} else if (cvv2RegEx.test(securityCode.val())) {
					return true;
				} else {
					alert('Invalid security code.');
					AddRequiredImageLeft(securityCode, 3);
					return false;
				}
			} else {
				var elements = new Array();
				if (!$('#BillingCardHolder').val()) {
					elements.push($('#BillingCardHolder'));
				}
				if (!$('#BillingCardNumber').val()) {
					elements.push($('#BillingCardNumber'));
				}
				if (!$('#BillingCardCvv2').val()) {
					elements.push($('#BillingCardCvv2'));
				}
				if ($('#BillingCardExpire_Month').val() == '?' || !$('#BillingCardExpire_Year').val() == '?') {
					elements.push($('#BillingCardExpire_Month'));
				}
				if (elements.length > 0) {
					alert('Please complete the required fields.');
					$.each(elements, function (i, v) { AddRequiredImageLeft(v, 3); });
					return false;
				}

				elements = new Array();
				var pw1 = $('input:password[name=SignupPassword]');
				var pw2 = $('input:password[name=SignupVerifyPassword]');
				var checkPasswordsMatch = false;
				//pw1 exists. must be a new customer
				if (pw1.length) {
					//check if it's checked
					if ($('#IsSaveBillingCard:checked').length) {
						checkPasswordsMatch = true;
						if (!pw1.val()) {
							elements.push(pw1);
						}
						if (!pw2.val()) {
							elements.push(pw2);
						}
					}
				}
				if (elements.length > 0) {
					alert('Please fill in the password fields to create an account in order to save credit card information.');
					$.each(elements, function (i, v) { AddRequiredImageLeft(v, 3); });
					return false;
				}

				if (!cvv2RegEx.test($('#BillingCardCvv2').val())) {
					alert('Invalid security code.');
					AddRequiredImageLeft($('#BillingCardCvv2'), 3);
					return false;
				}

				var bcn = $('#BillingCardNumber');
				bcn.val(bcn.val().replace(/\s+/g, ''));
				if (!ValidateCreditCardNumber(bcn.val())) {
					alert('Invalid card number.');
					AddRequiredImageLeft(bcn, 3);
					return false;
				}

				if (checkPasswordsMatch && pw1.val() != pw2.val()) {
					alert('Passwords do no match.');
					AddRequiredImageLeft(pw1, 3);
					AddRequiredImageLeft(pw2, 3);
					return false;
				}

				return true;
			}
			break;
		case 'GiftCert':
			alert('You must select a different payment option for the remaining balance or apply more discounts.');
			//show pointers to the left of credit card or paypal
			$('input:radio[name=AuthorizeNetPaymentProfileId]:not(:checked)').each(function () { AddRequiredImageLeft($(this), 0) });
			return false;
			break;
		case 'PayPal':
			return true;
			break;
		default:
			alert('You must first select a payment option.');
			$('input:radio[name=AuthorizeNetPaymentProfileId]').each(function () { AddRequiredImageLeft($(this), 0) });
	}
	return false;
}

function DisableAddToCartButton(bDisable, cProductKey) {
	if (bDisable == true) {
		$("#AddToCartAnchor").hide();
		$("#AddToCartDisabledImg").show();
		//        $("#ProductEmailNotifyLink").html("<a href=\"#\" onclick=\"window.open('/Product/ProductNotify.asp?ProductKey=" + cProductKey + "&~=', null, 'width=550,height=280,scrollbars=yes');return false;\" style=\"position:relative;top:5px;\">Email Me</a>");
		//        $("#ProductEmailNotifyLink").css("display", "inline");
	}
	else {
		$("#AddToCartAnchor").show();
		$("#AddToCartDisabledImg").hide();
		//        $("#ProductEmailNotifyLink").html("");
		//        $("#ProductEmailNotifyLink").hide();
	}
}

function FlashCartSummary() {
	$('#CartSummaryContent').fadeIn();
	setTimeout(function () { $('#CartSummaryContent').css('display', 'none'); }, 5000);
}

function SetEngineFormAction(value) {
	var oForm = document.Form_Engine;
	if (oForm) {
		oForm.Action.value = value;
	}
}

function SetEngineFormSelId(value) {
	var oForm = document.Form_Engine;
	if (oForm) {
		oForm.SelId.value = value;
	}
}

