// JavaScript Document

function showToolTip(toolTip){
	$(toolTip).removeClassName('toolTipHide');
	$(toolTip).addClassName('toolTipShow');
}
function hideToolTip(toolTip){
	$(toolTip).removeClassName('toolTipShow');
	$(toolTip).addClassName('toolTipHide');
}

function stopRKey(evt) {
  var evt = (evt) ? evt : ((event) ? event : null);
  var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
  if ((evt.keyCode == 13) && (node.type=="text"))  {return false;}
}

document.onkeypress = stopRKey; 


var doNothing = function(e) {
	if (!e) var e = window.event;
	e.cancelBubble = true;
	if (e.stopPropagation) e.stopPropagation();
}

function miniCartToggle() {
	Effect.toggle($('miniCartItems'),'blind',{duration:0.4});
	var isVisible = $('miniCartItems').visible();
	if (isVisible) {
		$('plusMinus').innerHTML = '<IMG SRC="/graphics/common/minicartplus.gif">';
	} else {
		$('plusMinus').innerHTML = '<IMG SRC="/graphics/common/minicartminus.gif">';
	}
}

var clearCart = function() {
	var ws = new webStore();
	ws.setCallbackHandler(populateBothCarts);
	ws.setErrorHandler(myErrorHandler);
	ws.clearCart();	
}
var addItemToCart = function(productId, formObj) {
	if ($('itemQuantity')) {
		var re = /^\d+$/
		if (!$F('itemQuantity').match(re) || $F('itemQuantity') == 0) { alert('Invalid quantity.'); return false; }	
	}
	
	if($('addToCartButton')) {
		 tempFunc = $('addToCartButton').onclick;
		 $('addToCartButton').onclick = doNothing;
		 $('addToCartButton').setOpacity(0.25);
	}
	var ws = new webStore();
	ws.setCallbackHandler(populateMiniCartItems);
	ws.setErrorHandler(myErrorHandler);
	ws.addItemToCart(productId, formObj);
}

var updateQuantity = function(arrayIndex,newQuantity,elem) {
	var re = /^\d+$/
	if (!newQuantity.match(re)) { alert('Invalid quantity.'); $(elem).activate(); return false; }	
	
	if ($('cartListingTable')) {
		$('cartListingTable').setOpacity(0.5);
		$$('#cartListingTable INPUT').each(function(elem, index) { elem.disabled = true; } )
	}
	if ($('scrollingDiv')) {
		$('scrollingDiv').setOpacity(0.5);
		$$('#scrollingDiv INPUT').each(function(elem, index) { elem.disabled = true; } )
	}
	var ws = new webStore();
	ws.setCallbackHandler(populateBothCarts);
	ws.setErrorHandler(myErrorHandler);
	ws.updateQuantity(arrayIndex,newQuantity);
}

var removeItemFromCart = function(arrayIndex) {
	if (confirm('Are you sure you want to remove this item entirely from your shopping cart?')) {
		var ws = new webStore();
		ws.setCallbackHandler(populateBothCarts);
		ws.setErrorHandler(myErrorHandler);
		ws.removeItemFromCart(arrayIndex);
	}
}

var removeItemFromCartWithRefresh = function(arrayIndex) {
	if (confirm('Are you sure you want to remove this item entirely from your shopping cart?')) {
		var ws = new webStore();
		ws.setCallbackHandler(function(res) { location.reload(); });
		ws.setErrorHandler(myErrorHandler);
		ws.removeItemFromCart(arrayIndex);
	}
}

var getMiniCartItems = function() {
	var ws = new webStore();
	ws.setCallbackHandler(populateMiniCart);
	ws.setErrorHandler(myErrorHandler);
	ws.getMiniCartItems();
}
var populateBothCarts = function(res) {
	if ($('cartListingTable')) {
		$('cartListingTable').setOpacity(1);
		populateMainCartItems(res.mainCartRes);
	}
	if ($('scrollingDiv')) {
		//alert('test');
		$('scrollingDiv').setOpacity(1);
		populateMiniCartItems(res.miniCartRes);
	}
}
var populateMiniCartItems = function(res) {
	Element.update($('scrollingDiv'),res);
}
var populateMainCartItems = function(res) {
	Element.update($('cartListingContainer'),res);	
}
var populateMiniCart = function(res) {
		newElem = Element.insert($('scrollingDiv'),{top:res});
}
var myErrorHandler = function(statusCode, statusMsg)
	{
		alert('Status: ' + statusCode + ', ' + statusMsg);
	}
	
function submitLoginForm() {
	var ws = new webStore();
	ws.setCallbackHandler(processLoginResult);
	ws.setErrorHandler(myErrorHandler);
	ws.processLogin($('loginForm').serialize(true));
	return false;
}

function submitShippingForm(goTo) {
	var errorText = '';
	
	if ($('useSavedAddress_false')) {
		
		if ($('useSavedAddress_false').checked) {
			
			if ($F('firstName') == '') errorText += 'Please specify your first name.\r\n';
		
			if ($F('lastName') == '') errorText += 'Please specify your last name.\r\n';
			if ($F('address1') == '') errorText += 'Please specify your address.\r\n';

			if ($F('city') == '') errorText += 'Please specify your city.\r\n';
				
			if ($F('state') == '') errorText += 'Please specify your state.\r\n';
			if ($F('zipCode') == '') errorText += 'Please specify your zip.\r\n';
		}
	}
	if (errorText != "") {
		alert(errorText);
		return false;
	}
	var ws = new webStore();
	ws.setCallbackHandler(processResultScripts);
	ws.setErrorHandler(myErrorHandler);
	ws.processShippingInfo($('shippingInfoForm').serialize(true),goTo);
	return false;
}

function submitBillingPaymentForm(goTo) {
	
	var errorText = '';

	if ($('billingAddressChoice_new')) { 
		if ($('billingAddressChoice_new').checked) {
			if ($F('firstName') == '') errorText += 'Please specify your first name.\r\n';
			if ($F('lastName') == '') errorText += 'Please specify your last name.\r\n';
			if ($F('address1') == '') errorText += 'Please specify your address.\r\n';
			//if ($F('address2') == '') errorText += 'Please specify your address 2.\r\n';
			if ($F('city') == '') errorText += 'Please specify your city.\r\n';
			if ($F('state') == '') errorText += 'Please specify your state.\r\n';
			if ($F('zipCode') == '') errorText += 'Please specify your zip.\r\n';
		}
	}
	
	if ($('useSavedCard_false')) { 
		if ($('useSavedCard_false').checked) {
			if ($F('creditCardName') == '') errorText += 'Please enter the name on your credit card.\r\n';
			if ($F('creditCardType') == '') errorText += 'Please specify your credit card type.\r\n';
			if (
				$F('creditCardNumber') == ''
				|| 
				!validateCreditCardNumber($F('creditCardNumber'),$F('creditCardType'))
				) {		errorText += 'Please enter a valid credit card number.\r\n'; }
			if ($F('creditCardExpDateMonth') == '') errorText += 'Please specify the expiration date month on your credit card.\r\n';
			if ($F('creditCardExpDateYear') == '') errorText += 'Please specify the expiration date year on your credit card.\r\n';
			if (!checkCCExpDateNoBlanks()) errorText += 'The expiration date on your credit card has passed. Please check the expiration date and try again or use a different card.\r\n';
			if ($F('creditCardSecurityCode') == '') errorText += 'Please enter the security code from your credit card.\r\n';
			else if ( 
					 (($F('creditCardType') == 'Visa' || $F('creditCardType') == 'MasterCard' || $F('creditCardType') == 'Discover') && ($F('creditCardSecurityCode').length <= 2 || $F('creditCardSecurityCode').length >= 4)) ||
					 (($F('creditCardType') == 'American Express') && ($F('creditCardSecurityCode').length <= 3 || $F('creditCardSecurityCode').length >= 5))
					 ) errorText += 'Please enter a valid security code from your credit card.\r\n';
		} else if ($('useSavedCard_true').checked) {
			if ($F('creditCardSecurityCode_saved') == '') errorText += 'Please enter the security code from your credit card.\r\n';
				else if ( 
					 ((savedType  == 'Visa' || savedType  == 'MasterCard' || savedType  == 'Discover') && ($F('creditCardSecurityCode_saved').length <= 2 || $F('creditCardSecurityCode_saved').length >= 4)) ||
					 ((savedType  == 'American Express') && ($F('creditCardSecurityCode_saved').length <= 3 || $F('creditCardSecurityCode_saved').length >= 5))
					 ) errorText += 'Please enter a valid security code from your credit card.\r\n';
			if (!checkCCExpDateCurrent()) errorText += 'The expiration date on your credit card has passed. Please check the expiration date and try again or use a different card.\r\n';
		}
	}	
	
	if (errorText != '') {
		alert(errorText);
		return false;
	}
	
	var ws = new webStore();
	ws.setCallbackHandler(processResultScripts);
	ws.setErrorHandler(myErrorHandler);
	ws.processBillingPaymentInfo($('billingPaymentForm').serialize(true),goTo);
	return false;
}
function checkCCExpDateNoBlanks() {
	var today = new Date(); // get today's date
    var thisYear = today.getFullYear();
    var thisMonth = 1 + today.getMonth();
	
	var selMonth = $F('creditCardExpDateMonth');
	var selYear = $F('creditCardExpDateYear');
		
	if (selYear == thisYear) {
		if (selMonth < thisMonth) {
			return false;	
		}
	}
	return true;
}
var processResultScripts = function(res) {
	res.evalScripts();	
}

var processLoginResult = function(res) {
	Element.update($('loginFormDiv'),res);
}

function continueAsGuest() {
	var ws = new webStore();
	ws.setCallbackHandler(processLoginResult);
	ws.setErrorHandler(myErrorHandler);
	ws.continueAsGuest($('loginForm').serialize(true));	
}

function saveMyAccountInfo() {
	showLoader();
	$('borderedContainer').setOpacity(0.25);
	var ws = new webStore();
	ws.setCallbackHandler(processMyAccountUpdateResult);
	ws.setErrorHandler(myErrorHandler);
	ws.saveMyAccountInfo($('myAccountForm').serialize(true));
	return false;
}

var processMyAccountUpdateResult = function(res) {
	hideLoader.delay(1);
	$('borderedContainer').setOpacity(1);
}

var showLoader = function() {
	var addToTop = document.viewport.getScrollOffsets().top;
	
	$('ajaxLoader').setStyle({ top: (addToTop+50) + 'px'});
	$('ajaxLoader').show();	
}

var showProcessor = function() {
	var addToTop = document.viewport.getScrollOffsets().top;
	
	$('processor').setStyle({ top: (addToTop+50) + 'px'});
	$('processor').show();	
}

var hideProcessor = function() {
	$('processor').hide();		
}

var hideLoader = function() {
	$('ajaxLoader').hide();	
}

function swapSpans(elem1, elem2) {
	$(elem1).toggle();
	$(elem2).toggle();
}

var setShippingOptionsU = function(state) {
	if ($('useSavedAddress_false')) {
		if ($('useSavedAddress_false').checked) {	
			setShippingOptions(state);
		}
	}
}

var setShippingOptions = function(location) {
	var ws = new webStore();
	ws.setCallbackHandler(processShippingOptions);
	ws.setErrorHandler(myErrorHandler);
	ws.getShippingOptions(location);
}

var processShippingOptions = function(res) {
	var i = 0;
	if ($('shippingMethod'))
	$('shippingMethod').options.length = 0;
	
	res.each(function(item) {
		$('shippingMethod').options[i] = new Option(item.OPTIONDISPLAY,item.OPTIONVALUE);
		i++;
	});
}

var confirmOrder = function(goTo) {
	tempFunc = $('completeOrderLink').onclick;
	$('completeOrderLink').onclick = doNothing;
	$('completeOrderButton').setOpacity(0.25);
	
	showProcessor();
	$('checkOutBoxContainer').setOpacity(0.25);
	var ws = new webStore();
	ws.setCallbackHandler(processOrderConfirmation);
	ws.setErrorHandler(myErrorHandler);
	ws.confirmOrder(goTo,$('orderInfo').serialize(true));
}

var processOrderConfirmation = function(res) {
	$('checkOutBoxContainer').setOpacity(1);
	hideProcessor();
	processResultScripts(res);
}

var toggleOrderHistoryDetail = function(elem,elem2,orderId) {
	Effect.toggle(elem, 'blind', { duration: 0.6, afterFinish: function() { 
		if($(elem2).innerHTML == 'View Order Details') {
			$('orderTotalDefault_' + orderId).hide();
			$('orderTotalSwap_' + orderId).show();
			$('ohrow_' + orderId).style.height = '70px';
			$(elem2).innerHTML = 'Close Order Details';
		} else {
			$(elem2).innerHTML = 'View Order Details';
			$('ohrow_' + orderId).style.height = '45px';
			$('orderTotalSwap_' + orderId).hide();
			$('orderTotalDefault_' + orderId).show();
		}
	} });
}

var processCouponCode = function() {
	showLoader();
	var ws = new webStore();
	ws.setCallbackHandler(processCouponCodeResult);
	ws.setErrorHandler(myErrorHandler);
	ws.processCouponCode($('couponCodeForm').serialize(true));
}

var processCouponCodeResult = function(res) {
	hideLoader.delay(1);
	populateBothCarts(res);
	$('couponCodeForm').reset();
	alert(res.message);
}

var submitExpressShop = function() {
	$('expressShopContainer').setOpacity(0.25);
	showError = false;
	errorElem = "";
	var allItemsForm = $('expressShopForm');
		var allQuantitys = allItemsForm.getInputs('text');
		var fullProductId = 0;
		var total = 0;
		allQuantitys.each(function(name, index) {
			quantity = $F(name);
			if (isNaN(quantity)) { showError = true; errorElem = name; throw $break;  }
		})
	
	
	if (showError) {
		alert('Invalid quantity.'); 
		$('expressShopContainer').setOpacity(1);
		$(errorElem).focus();
		return false;
	}
	
	showLoader();
	var ws = new webStore();
	ws.setCallbackHandler(processExpressShopResult);
	ws.setErrorHandler(myErrorHandler);
	ws.processExpressShop($('expressShopForm').serialize(true));
	return false;
}

var processExpressShopResult = function(res) {
	hideLoader.delay(1);
	processResultScripts.delay(2,res);
	$('expressShopContainer').setOpacity(1);
}

var passwordsMustMatch = function (formObj,InputObj,InputObjVal) {
	if (formObj.password.value != '') {
		return (formObj.password.value == formObj.confirmPassword.value);
	} else {
		return true;
	}
}
var checkCCSecCode = function(formObj, InputObj, InputObjVal) {
	if (InputObjVal == '') {
		return false;	
	} else if (isNaN(InputObjVal)) {
		return false;	
	} else if (
			   
		   (($F('creditCardType') == 'Visa' || $F('creditCardType') == 'MasterCard' || $F('creditCardType') == 'Discover') && (InputObjVal.length <= 2 || InputObjVal.length >=4))
		   ||
		   ($F('creditCardType') == 'American Express' && (InputObjVal.length <= 3 || InputObjVal.length >= 5))
			   ) {
		return false;	
	} else {
		return true;	
	}
}
var emailsMustMatch = function (formObj,InputObj,InputObjVal) {
	if (formObj.email.value != '') {
		return (formObj.email.value == formObj.confirmEmail.value);
	} else {
		return false;
	}
}

var getZipCode = function(zipCodeField,cityField,stateField) {
	var ws = new webStore();
	ws.setCallbackHandler(processZipCodeResult);
	ws.setErrorHandler(myErrorHandler);
	ws.getCityAndStateFromZipcode($F(zipCodeField),cityField,stateField);
}

var processZipCodeResult = function(res) {
		var cityField = res.CITYFIELD;
		var stateField = res.STATEFIELD;
		$(cityField).value = res.CITY;
		$(stateField).value = res.STATE;
		if ($('shippingMethod')) setShippingOptions($F(stateField));
}
var getZipCodeU = function(zipCodeField,cityField,stateField) {
	var ws = new webStore();
	ws.setCallbackHandler(processZipCodeResultU);
	ws.setErrorHandler(myErrorHandler);
	ws.getCityAndStateFromZipcode($F(zipCodeField),cityField,stateField);
}
var processZipCodeResultU = function(res) {
		var cityField = res.CITYFIELD;
		var stateField = res.STATEFIELD;
		$(cityField).value = res.CITY;
		$(stateField).value = res.STATE;
		if ($('shippingMethod')) setShippingOptionsU($F(stateField));
}

var addOldOrderContents = function(orderId) {
	showLoader();
	var ws = new webStore();
	ws.setCallbackHandler(processAddOldOrderContents);
	ws.setErrorHandler(myErrorHandler);
	ws.addOldOrderContents(orderId);
}

var processAddOldOrderContents = function(res) {
	hideLoader.delay(1);
	processResultScripts(res);
}


    var anUpperCase = /[A-Z]/;
    var aLowerCase = /[a-z]/;
    var aNumber = /[0-9]/;
	var aLetter = /[A-Za-z]/;

//|| value.search(anUpperCase) == -1 || value.search (aLowerCase) == -1

    function testpasswd(form, ctrl, value) {
		if (value.length != 0) {
			if (value.length < 6  || value.search (aNumber) == -1 || value.search (aLetter) == -1) 
			{
				return (false);
			} 
			else
			{
				return (true);
			} 
		} else { return (true); }
    }
	
	 function testpasswd2(form, ctrl, value) {
		if (value.length < 6  || value.search (aNumber) == -1 || value.search (aLetter) == -1) 
		{
			return (false);
		} 
		else
		{
			return (true);
		} 
    }
	
	function checkCCFields(form, ctrl, value) {
		
		if (kitClubMember && (form.creditCardName.value.length == 0 || form.creditCardNumber.value.length == 0 || form.creditCardExpDateMonth.value.length == 0 || form.creditCardExpDateYear.value.length == 0)) {
			alert('With an HMR at Home membership you must maintain credit card information for your ongoing kit re-orders. If you wish to cancel your membership, click on Customer Service in the Manage My HMR at Home section.');
			return false;
		}
		
		
		if (form.creditCardName.value.length == 0 && form.creditCardNumber.value.length == 0 && form.creditCardExpDateMonth.value.length == 0 && form.creditCardExpDateYear.value.length == 0) {
			return true;
		}
			else if (form.creditCardName.value.length == 0 || form.creditCardNumber.value.length == 0 || form.creditCardExpDateMonth.value.length == 0 || form.creditCardExpDateYear.value.length == 0)
		{ return false; }
		else if (form.creditCardName.value.length > 0 || form.creditCardNumber.value.length > 0 || form.creditCardExpDateMonth.value.length > 0 || form.creditCardExpDateYear.value.length > 0) { return true; }
	}


function Left(str, n)
{
   if (n <= 0)
         return "";
   else if (n > String(str).length)
         return str;
   else
         return String(str).substring(0,n);
}

function validateCreditCardNumber(form, ctrl, value) {
	ccn = $F('creditCardNumber');
	cct = $F('creditCardType');
	return checkCreditCard(ccn,cct);
}

function myAccountCheckCCNo(form, ctrl, value) {
	ccn = $F('creditCardNumber');
	cct = $F('creditCardType');

	if ((ccn == origNo && cct == origType) || ccn == '') {
		return true;
	}	else {
		return checkCreditCard(ccn,cct);	
	}
}

// credit card number validation issues...
function checkCCExpDateCurrent(form, ctrl, value) {
	var today = new Date(); // get today's date
    var thisYear = today.getFullYear();
    var thisMonth = 1 + today.getMonth();

	var selMonth = savedMonth;
	var selYear = savedYear;

	if (selMonth != '' && selYear != '') {
		if (selYear == thisYear) {
			if (selMonth < thisMonth) {
				return false;	
			}
		} else if (selYear < thisYear) {
			return false;	
		}
	}
	return true;
}


function checkCCExpDate(form, ctrl, value) {
	var today = new Date(); // get today's date
    var thisYear = today.getFullYear();
    var thisMonth = 1 + today.getMonth();

	
	var selMonth = $F('creditCardExpDateMonth');
	var selYear = $F('creditCardExpDateYear');

	if (selMonth != '' && selYear != '') {
		if (selYear == thisYear) {
			if (selMonth < thisMonth) {
				return false;	
			}
		}
	}
	return true;
}

var ccErrorNo = 0;
var ccErrors = new Array ()

ccErrors [0] = "Unknown card type";
ccErrors [1] = "No card number provided";
ccErrors [2] = "Credit card number is in invalid format";
ccErrors [3] = "Credit card number is invalid";
ccErrors [4] = "Credit card number has an inappropriate number of digits";

function checkCreditCard (cardnumber, cardname) {
  // Array to hold the permitted card characteristics
  var cards = new Array();

  // Define the cards we support. You may add addtional card types.
  
  //  Name:      As in the selection box of the form - must be same as user's
  //  Length:    List of possible valid lengths of the card number for the card
  //  prefixes:  List of possible prefixes for the card
  //  checkdigit Boolean to say whether there is a check digit
  
  cards [0] = {name: "Visa", 
               length: "13,16", 
               prefixes: "4",
               checkdigit: true};
  cards [1] = {name: "MasterCard", 
               length: "16", 
               prefixes: "51,52,53,54,55",
               checkdigit: true};
  cards [2] = {name: "DinersClub", 
               length: "14,16", 
               prefixes: "300,301,302,303,304,305,36,38,55",
               checkdigit: true};
  cards [3] = {name: "CarteBlanche", 
               length: "14", 
               prefixes: "300,301,302,303,304,305,36,38",
               checkdigit: true};
  cards [4] = {name: "American Express", 
               length: "15", 
               prefixes: "34,37",
               checkdigit: true};
  cards [5] = {name: "Discover", 
               length: "16", 
               prefixes: "6011,650",
               checkdigit: true};
  cards [6] = {name: "JCB", 
               length: "15,16", 
               prefixes: "3,1800,2131",
               checkdigit: true};
  cards [7] = {name: "enRoute", 
               length: "15", 
               prefixes: "2014,2149",
               checkdigit: true};
  cards [8] = {name: "Solo", 
               length: "16,18,19", 
               prefixes: "6334, 6767",
               checkdigit: true};
  cards [9] = {name: "Switch", 
               length: "16,18,19", 
               prefixes: "4903,4905,4911,4936,564182,633110,6333,6759",
               checkdigit: true};
  cards [10] = {name: "Maestro", 
               length: "16,18", 
               prefixes: "5020,6",
               checkdigit: true};
  cards [11] = {name: "VisaElectron", 
               length: "16", 
               prefixes: "417500,4917,4913",
               checkdigit: true};
               
  // Establish card type
  var cardType = -1;
  for (var i=0; i<cards.length; i++) {

    // See if it is this card (ignoring the case of the string)
    if (cardname.toLowerCase () == cards[i].name.toLowerCase()) {
      cardType = i;
      break;
    }
  }
  
  // If card type not found, report an error
  if (cardType == -1) {
     ccErrorNo = 0;
     return false; 
  }
   
  // Ensure that the user has provided a credit card number
  if (cardnumber.length == 0)  {
     ccErrorNo = 1;
     return false; 
  }
    
  // Now remove any spaces from the credit card number
  cardnumber = cardnumber.replace (/\s/g, "");
  
  // Check that the number is numeric
  var cardNo = cardnumber
  var cardexp = /^[0-9]{13,19}$/;
  if (!cardexp.exec(cardNo))  {
     ccErrorNo = 2;
     return false; 
  }
       
  // Now check the modulus 10 check digit - if required
  if (cards[cardType].checkdigit) {
    var checksum = 0;                                  // running checksum total
    var mychar = "";                                   // next char to process
    var j = 1;                                         // takes value of 1 or 2
  
    var calc;
    for (i = cardNo.length - 1; i >= 0; i--) {
    
      calc = Number(cardNo.charAt(i)) * j;
    
      if (calc > 9) {
        checksum = checksum + 1;
        calc = calc - 10;
      }
    
      checksum = checksum + calc;
    
      // Switch the value of j
      if (j ==1) {j = 2} else {j = 1};
    } 
  
    if (checksum % 10 != 0)  {
     ccErrorNo = 3;
     return false; 
    }
  }  

  var LengthValid = false;
  var PrefixValid = false; 
  var undefined; 

  var prefix = new Array ();
  var lengths = new Array ();
    
  prefix = cards[cardType].prefixes.split(",");
      
  for (i=0; i<prefix.length; i++) {
    var exp = new RegExp ("^" + prefix[i]);
    if (exp.test (cardNo)) PrefixValid = true;
  }
      
  if (!PrefixValid) {
     ccErrorNo = 3;
     return false; 
  }

  lengths = cards[cardType].length.split(",");
  for (j=0; j<lengths.length; j++) {
    if (cardNo.length == lengths[j]) LengthValid = true;
  }
  
  if (!LengthValid) {
     ccErrorNo = 4;
     return false; 
  };   
  
  // The credit card is in the required format.
  return true;
}

var joinKitClub = function() {
	var ws = new webStore();
	ws.setCallbackHandler(processKitClubYesResult);
	ws.setErrorHandler(myErrorHandler);
	ws.joinKitClub();
	return false;
}
var addHSKit = function() {
	var ws = new webStore();
	ws.setCallbackHandler(processKitClubYesResult);
	ws.setErrorHandler(myErrorHandler);
	ws.addHSKit();
	return false;
}
var mibRequired = false;

var startCheckout = function () {
	if (kitClubDecisionRequired) {
		if (kitClubDecision != false) {
			if (!checkMib()) { showMIBPopup(); return false;}
			setTimeout("location.href='/store/checkOut';",10);
			//return true;
		} else {
			alert("Please indicate whether or not your are interested in joining the HMR at Home Program.");
			return false;
		}
	} else if (!kitClubDecisionRequired) {
		if (!checkMib()) { showMIBPopup(); return false;}
		setTimeout("location.href='/store/checkOut';",10);
		//return true;
	}
}

// KC

var checkMib = function() {
	if (mibRequired == true) {
		if (!mibCompleted) {
			return false;
		}
	}
	return true;
}

var processRemoveKCMembership = function() {
	if ($('removeKit_yes').checked) {
		removeKCMembership();
	} else if ($('removeKit_no').checked) {
		cancelAlreadyAMemberPopup();
	} else {
		alert('Please make a selection.');	
	}
	return false;
}

var removeKCMembership = function() {
	var ws = new webStore();
	ws.setCallbackHandler(processKitClubYesResult);
	ws.setErrorHandler(myErrorHandler);
	ws.changeKitClubToKit();
}

var cancelAlreadyAMemberPopup = function() {
	location.href='/store/ShoppingCart';
	/**var ws = new webStore();
	ws.setCallbackHandler(processKitClubYesResult);
	ws.setErrorHandler(myErrorHandler);
	ws.cancelAlreadyAMemberPopup();**/
}

var showExistingKCMemberError = function(errorText) {
	if (confirm(errorText)) {
		var ws = new webStore();
		ws.setCallbackHandler(processKitClubYesResult);
		ws.setErrorHandler(myErrorHandler);
		ws.changeKitClubToKit();
	} else {
		location.href='/store/ShoppingCart';	
	}
	return false;
}

var kitClubNo = function() {
	kitClubDecision = 'no';
	new Effect.DropOut('kitClubPrompt');
}
var kitClubYes = function() {
	//mibRequired = true;
	//mibCompleted = false;
	var ws = new webStore();
	ws.setCallbackHandler(processKitClubYesResult);
	ws.setErrorHandler(myErrorHandler);
	ws.processKitClubYes();
	return false;
}
var submitKitChoice = function() {
	var ws = new webStore();
	ws.setCallbackHandler(processKitClubYesResult);
	ws.setErrorHandler(myErrorHandler);
	ws.submitKitChoice($('kitChoiceForm').serialize(true));
	return false;
}
var submitMoreIsBetterItems = function() {
	var includedItems = $('mibForm').getInputs("checkbox");
	var error = 0;
	includedItems.each(function(item) {
		if (item.checked) {
			var itemId = item.name.split("_")[1];
			var quantityValue = $F('qty_' + itemId);
			if (quantityValue.length == 0 || quantityValue == "" || quantityValue == 0 || isNaN(quantityValue)) {
				error = 1;
				alert("Please enter a valid quantity for all items you would like to add to your recurring order.");
					
			}
		}
	});
	if (!error) {
		var ws = new webStore();
		ws.setCallbackHandler(processKitClubYesResult);
		ws.setErrorHandler(myErrorHandler);
		ws.submitMoreIsBetterItems($('mibForm').serialize(true));
		return false;
	} else {
		return false;	
	}
}

var displayQuantityChangeInfo = function(index) {
	jQuery('#errorDisplayBox_content').load('/store/kits/quantityChangePopup.cfm?index=' + index);
	jQuery('#errorDisplayBox').jqmShow();
}

var agreeToQuantityChange = function(index) {
	var ws = new webStore();
	ws.setCallbackHandler(processKitClubYesResult);
	ws.setErrorHandler(myErrorHandler);
	ws.agreeToQuantityChange(index);	
}

var processKitClubYesResult = function(res) {
	switch(res.TYPE)
	{
		case 'relocate':
			location.href=res.URL;
		break;
		case 'error':
			jQuery('#errorDisplayBox_content').load('/store/kits/errorPopup.cfm?et=' + escape(res.ERRORTEXT));
			//jQuery('#errorDisplayBox_content').html('<div style="background-color: white; border: 1px solid red; padding: 10px 10px 10px 10px;">' +  + "</div>");
			jQuery('#errorDisplayBox').jqmShow();
		break;
		case 'script':
			res.TEXT.evalScripts();
		break;
	}	
}

var showKitUpradeOption = function(text) {
	jQuery('#kitUpgradeOption_content').innerHTML = 'Please wait...<BR />';
	jQuery('#kitUpgradeOption').jqmShow();
	jQuery('#kitUpgradeOption_content').load('/store/kits/kitUpgradeOption.cfm');	
}

var upgradeSingleHSKit = function() {
	var ws = new webStore();
	ws.setCallbackHandler(processKitClubYesResult);
	ws.setErrorHandler(myErrorHandler);
	ws.upgradeSingleHSKit();
}

var showMIBPopup = function() {
	if ($('mibPopup')) {
		jQuery('#mibPopup_content').innerHTML = 'Please wait...<BR />';
		jQuery('#mibPopup').jqmShow();
		jQuery('#mibPopup_content').load('/store/kits/mibPopup.cfm');
	}
}

var displayHSKitsForSelection = function(text) {
	jQuery('#chooseAKit_content').innerHTML = 'Please wait...<BR />';
	jQuery('#chooseAKit').jqmShow();
	jQuery('#chooseAKit_content').load('/store/kits/chooseKitPopup.cfm');
}

var showAlreadyAMemberPopup = function(text) {
	jQuery('#alreadyAMemberPopup_content').innerHTML = 'Please wait...<BR />';
	jQuery('#alreadyAMemberPopup').jqmShow();
	jQuery('#alreadyAMemberPopup_content').load('/store/kits/alreadyAMemberPopup.cfm');
}

var doKitClubCancellation = function() {
	var ws = new webStore();
	ws.setCallbackHandler(processKitClubYesResult);
	ws.setErrorHandler(myErrorHandler);
	ws.cancelKitClub();
}
//jQuery(document).ready(function() {
Event.observe(window, 'load', function() {
  //getMiniCartItems();
  
  
  if ($('miniCart')) {
	  Event.observe('miniCart', 'click', miniCartToggle);
	  Event.observe('scrollingDiv','click',doNothing);
	  Event.observe('checkoutLink','click',doNothing);
  }
  if ($('expressShopContainer')) {
	  //window.addEventListener('unload',quitit,false);
	  
	  window.onunload=function(){return true;}
	$('expressShopContainer').setOpacity(1);
	//$('expressShopForm').reset();
  }
  if ($('kitClubPrompt')) {
	  new Effect.Appear('kitClubPrompt', { duration: 0.9 });
  }
	  runLogin();
});

var checkZip = function(elem) {
	if (elem.value.length < 5) {
		$('state').value = '';
		$('city').value = '';
	} else if (elem.value.length == 5) {
		getZipCode('zipCode','city','state');	
	} else {
		return false;	
	}
}

var checkZipU = function(elem) {
	if (elem.value.length < 5) {
		$('state').value = '';
		$('city').value = '';
	} else if (elem.value.length == 5) {
		getZipCodeU('zipCode','city','state');	
	} else {
		return false;	
	}
}

