/*--------------------------------------------------------------------------------------------------
globalShopper();
Make our shopper variable global for the log functions
--------------------------------------------------------------------------------------------------*/
var shopper;
function globalShopper(theShopper){ 
	shopper = theShopper;
}


// JAVASCRIPT VERSION OF MY PHP stringBetweenTwoStrings function
function stringBetweenTwoStrings(string1,string2,haystack,cursor) {
	var pos1start = haystack.indexOf(string1,cursor);
	if(pos1start != -1) {
		str1length = string1.length; 								//  Find the length of string one so we can move to the end
		pos1end    = pos1start + str1length; 						//  Find the end position of the first string
		pos2start  = haystack.indexOf(string2,pos1end); 			// Find the start position of the second string
		howFarToGo = pos2start - pos1end; 							// How many characters between the end of string1 and the beginning of string2	
		return haystack.substring(pos1end,howFarToGo + pos1end);
	}
	else {
		return "not found";
	}	
}

 


/*--------------------------------------------------------------------------------------------------
changeShipMethod();
--------------------------------------------------------------------------------------------------*/
function changeShippingMethod(whichMethod,rate) {

	//userLog(shopper,"Change shipping method: " + whichMethod + " rate: " + rate); 
	
	// Store the rate in our hidden field	
	document.getElementById("shipping_hidden").value = rate;
	
	// Inject the rate into the shipping rate line
	putInShipping = "$" + rate;
	document.getElementById("shipping_results").innerHTML = putInShipping;
	
	// Save via ajax
	params[i]  = "action=changeShippingMethod"; i++;
	params[i]  = "whichMethod=" + whichMethod; i++;
	putResults = "changeShippingMethod_results";	
		
	ajaxMagic('cart_ajax.php',params,putResults,'','doNotFade','doNotLoad',calculateTotal);

}




/*-------------------------------------------------------------------------------------------------
totalUniqueItems() 
Find out how many item blocks there are in the cart
--------------------------------------------------------------------------------------------------*/
function totalUniqueItems() {
	// Get all the divs
	var divs = document.getElementsByTagName('div');
	
	// Start the count at 0
	count = 0;
	
	// Loop through all the divs
	for (var i=0;i<divs.length;i++){ 
		
		// Get the id of this div
		thisId = divs[i].id; 
		
		// If the first 4 chars of the id is item, increment our count
		if(thisId.substring(0,4) == "item") {
			count++;
		}
	} 
	return count;
}




/*--------------------------------------------------------------------------------------------------
calculateShipping();
--------------------------------------------------------------------------------------------------*/
function calculateShipping(requireZip) {

	// Turn off the gift option if it was on
	toggleGiftOptionPopup(1);
	
	// See if we have a zip
	var zip = document.getElementById("zip_input").value;
	
	//userLog(shopper,"Calculate shipping | zip: " + zip); 

	// Throw error
	if(zip == "" && requireZip == true) {
		errorField("zip",false,"Enter your zip code<br>for shipping rates",1);
	}
	else {
		errorField("zip",true);
	
		// Ajax call to fetch zipping 
		params     = new Array();i = 0;
		params[i]  = "action=calculateShipping"; i++;  
		params[i]  = "zip=" + zip; i++;
		params[i]  = "subtotal=" + document.getElementById("subtotal_hidden").value; i++;
		putResults = "calculateShipping_results";	
		
		// There's a div after the Shipping label in the shipping row, put this in there so they know it's working
		if(document.getElementById("calculatingShippingStatus").innerHTML != "(Calculating...)") { // This if prevents the message showing up twice if they call it again before its been cleared
			document.getElementById("calculatingShippingStatus").innerHTML = "(Calculating...)";
		}
		
		// Run the ajax, then use goToCheckout function to redirect the window to the checkout
		ajaxMagic('cart_ajax.php',params,putResults,'','doNotFade','doNotLoad',postCalculateShipping);	
	}

}




// To do after done calculateShipping
function postCalculateShipping() {

	// Get rid of the "(Calculating...)" line next to shipping
	document.getElementById("calculatingShippingStatus").innerHTML = ""; 
	
	// Gather the rate from the hidden field and inject it into the shipping line
	var rate = document.getElementById("shipping_hidden").value;
	document.getElementById("shipping_results").innerHTML = "$" + rate;
	
	//userLog(shopper,"New shipping value: $" + rate); 
	
	// What did the ajax return?
	var calculateShipping_results = document.getElementById("calculateShipping_results").innerHTML;
	
	// If what the ajax returned included "Could not find" it was an errror - so throw the zip flag
	if(calculateShipping_results.indexOf("Could not calculate") >= 0) {
		
		//userLog(shopper,"Could not calculate shipping, throw error."); 
		
		// Figure out if we should call it a zip or postal code
		var country = document.getElementById("country_input").value;
		var zipOrPostal = "postal";
		if(country == "US") {
			zipOrPostal = "zip";
		}
		
		// Throw the error
		errorField("zip",false,"Please check<br>your " + zipOrPostal + " code.",1);
	}
	
	calculateTotal();
}




 
/*-------------------------------------------------------------------------------------------------
proceedToCheckout();
-------------------------------------------------------------------------------------------------*/
function proceedToCheckout(paymentMethod) {

	////userLog(shopper,"Save totals then proceed to checkout");

	// Before we go to the checkout we have fetch and store some variables about the totals
 
	// calculateTotal will return an array with total values 
	totals 			= calculateTotal();	
	subtotal 		= totals['subtotal'];
	total 		    = totals['total'];
	shipping 		= totals['shipping'];
	deduct  		= totals['deduct'];
	
	if(total <= 0) {
		paymentMethod = "coupon";
	}

	// Save some variables that we'll need in IPN
	params     = new Array();i = 0;
	params[i]  = "action=proceedToCheckout"; i++;
	params[i]  = "paymentMethod=" + paymentMethod; i++;
	params[i]  = "subtotal=" + subtotal; i++;
	params[i]  = "total=" + total;    i++;
	params[i]  = "shipping=" + shipping; i++;
	params[i]  = "deduct="   + deduct;   i++;
	putResults = "proceedToCheckout_results";	
	
	// Run the ajax, then use goToCheckout function to redirect the window to the checkout
	ajaxMagic('cart_ajax.php',params,putResults,'','doNotFade','doNotLoad',goToCheckout); 
	
}




/*-------------------------------------------------------------------------------------------------
goToCheckout();
-------------------------------------------------------------------------------------------------*/
function goToCheckout() {
	window.location = "https://" + location.host + "/store/checkout/checkout.php";
}



/*-------------------------------------------------------------------------------------------------
checkCoupon();
STEP 1 OF 2 - sends to ajax
called by onBlur from the id='coupon_input' text input
-------------------------------------------------------------------------------------------------*/
function checkCoupon() {
	
	// What code are we testing? Grab it from the input field
	couponCode = document.getElementById("coupon_input").value;
	
	// Don't c
	if(couponCode.indexOf("moo") != -1 && (document.getElementById("zip_error").style.display != "none" || document.getElementById("zip_input").value == "")) {
		calculateShipping(true);
	}
	
	// Only do this if they actually entered a code
	else if(couponCode != "") {
		
		params = new Array(); i = 0;
		params[i]  = "action=checkCoupon";       i++;	
		params[i]  = "couponCode=" + couponCode; i++;

		putResults = "coupon_results"; 
	
		// Do the ajax to check the coupon then call checkCouponResults to process the results
		ajaxMagic('/store/cart/cart_ajax.php',params,putResults,'','doNotFade','doNotLoad',checkCouponResults);	
	}
	else {
		// Clear the error
		errorField("coupon",true);
	}

}

// V 

/*-------------------------------------------------------------------------------------------------
checkCouponResults();  
STEP 2 of 2 - fetches ajax results
Parses and reads an ajax result created by checkCoupon
-------------------------------------------------------------------------------------------------*/
function checkCouponResults() {

	
	// Fresh slate? Not sure if this is necessary, but leaving it anyway.
	document.getElementById("coupon_error").style.display = "none";

	// The result is put in a hidden input by ajax - grab it
	result     = document.getElementById("coupon_hidden").value; 
	couponType = document.getElementById("couponType_hidden").value;
	
	// BAD COUPON: A failing coupon will have Drats as part of the result
	if(result.search(/Drats/) != -1) { // Means we found drats
			
		// Hide the discount row
		document.getElementById("discount_row").style.display = 'none'; 
		
		// Throw error! Do this after hiding discount row because error tab is going to autolocate
		// Only throw error if the coupon is turned on. This check is in place so it doesn't throw an error when they hit the back button to come back to the page and the coupon is off
		if(document.getElementById("coupon_container").style.display == "block") {
			//errorField(id,pass,newError,background,autolocate)
			errorField("coupon",false,result,1,true);
		}
	}
	// GOOD COUPON
	else {
		
		// Clear an error if its there
		errorField("coupon",true);
		
		// Label the discount
		if(couponType == "giftCert") {
			couponType = "Gift Card";
		}
		else {
			couponType = "Coupon";
		}
	
		document.getElementById("discountLabel").innerHTML = couponType;
	
		// Show the discount row
		
		var displayMethod = browserDisposal("table-row","table-row","block","table-row");
		
		document.getElementById("discount_row").style.display = displayMethod; // For all normal browsers set it to blank so the row will show and be aligned right. For IE, set it to block otherwise it won't show	
			
	}
	
	// Recalculate our totals - this will refresh the prices as well as do the job of saving the deduction in the database
	calculateShipping(true);
	calculateTotal();

}

// V 

/*-------------------------------------------------------------------------------------------------
toggleCoupon();
-------------------------------------------------------------------------------------------------*/
function toggleCoupon() {

	if(document.getElementById("coupon_container").style.display == "none") {
		document.getElementById("coupon_container").style.display = "block";	
	}
	else {
		document.getElementById("coupon_container").style.display = "none";
		
		// Turn off error if it exists
		errorField("coupon",true);
	}
	
	toggleGiftOptionPopup(1);
	
	
}



/*-------------------------------------------------------------------------------------------------
toggleGiftOptionPopup();
-------------------------------------------------------------------------------------------------*/
function toggleGiftOptionPopup(off) {
	
	// Find out where the gift options button is to line it up with that
	var posY = findPosY(document.getElementById('giftOptionsButton'));	
	
	var posYOffset = browserDisposal(275,275,275,275); // macFirefox,safari,ie,winFirefox
	document.getElementById("giftMessagePopup").style.top = posY - posYOffset;
	

	if(off == 1) {
		document.getElementById("giftMessagePopup").style.display = "none";	
	}
	else {
		if(document.getElementById("giftMessagePopup").style.display == "block") {
			document.getElementById("giftMessagePopup").style.display = "none";	
		}
		else {
			document.getElementById("giftMessagePopup").style.display = "block";
		}
	}
}




/*-------------------------------------------------------------------------------------------------
toggleGiftHidePrices();
This is called from the gift message checkbox. If gift messag = yes then gift hide prices also has to be yes
-------------------------------------------------------------------------------------------------*/
function toggleGiftHidePrices(forceOn) {

	// Figure out what we're toggling to
	var giftUseMessage = document.getElementById("giftUseMessage_checkbox").checked;
	
	if(giftUseMessage == true || forceOn == 1) {
		// Disabling of the price supression section
		document.getElementById("giftHidePrices_checkbox").disabled  = true;
		document.getElementById("giftHidePrices_checkbox").checked   = true;
		document.getElementById("giftHidePricesMsg").innerHTML = "Required for gift message";
		document.getElementById("giftHidePricesPrice").style.color   = "#CCCCCC";
		document.getElementById("giftHidePricesDesc").style.color    = "#CCCCCC";
		document.getElementById("giftHidePricesMsg").style.color     = "#CCCCCC";
	}
	else {
		document.getElementById("giftHidePrices_checkbox").disabled  = false;
		document.getElementById("giftHidePricesMsg").innerHTML = "We'll leave off the prices";
		document.getElementById("giftHidePricesPrice").style.color   = "#000000";
		document.getElementById("giftHidePricesDesc").style.color    = "#000000";
		document.getElementById("giftHidePricesMsg").style.color     = "#909090";
	}

}




/*-------------------------------------------------------------------------------------------------
toggleGiftOptionCheckbox();
Called by div that surrounds "Use a gift packing slip" so that we can make that turn the check on / off
-------------------------------------------------------------------------------------------------*/
function toggleGiftOptionCheckbox(shopper) {
	var theCheck = document.getElementById("giftHidePrices_checkbox");

	var theCheckValue = document.getElementById("giftHidePrices_checkbox").checked;
	
	if(theCheckValue == true) {
		
		theCheck.checked = false;
	}
	else {
		
		theCheck.checked = true;
		saveGiftOption(shopper);
	}	


}


/*-------------------------------------------------------------------------------------------------
saveGiftOption();
-------------------------------------------------------------------------------------------------*/
function saveGiftOption(shopper) {

	// Tabula rasa
	var pass = true;
	
	// Variables
	var giftHidePrices = document.getElementById("giftHidePrices_checkbox").checked;
	var giftWrap       = document.getElementById("giftWrap_checkbox").checked;
	var giftUseMessage = document.getElementById("giftUseMessage_checkbox").checked;
	var giftMessage    = document.getElementById("giftMessage").value;
	
	// If gift message is checked, the gift message can't be blank or default value
	if(giftUseMessage == true && (giftMessage == "" || giftMessage == document.getElementById("defaultGiftMessageHolder").value)) {
		pass = false;
		document.getElementById("giftMessage").style.backgroundImage = "url(/store/checkout/images/field-status-pink.jpg)";
	}
	
	// Send to ajax to save
	if(pass) {

		// Toggle the gift wrap line item		
		document.getElementById("giftWrapLineItem").style.display = (giftWrap == true) ? "block" : "none";
		
		calculateSubtotal();
		calculateTotal();
		toggleGiftOptionPopup();
		toggleProceedToCheckoutButton();
		params     = new Array();i = 0;
		params[i]  = "action=saveGiftOptions"; i++;	
		params[i]  = "giftHidePrices="  + giftHidePrices; i++;
		params[i]  = "giftWrap="        + giftWrap; i++;
		params[i]  = "giftUseMessage="  + giftUseMessage; i++;
		params[i]  = "giftMessage="     + encodeURIComponent(giftMessage); i++;
		params[i]  = "shopper="         + shopper; i++;
		putResults = "saveGiftOptions_results";	
		ajaxMagic('cart_ajax.php',params,putResults,'','doNotFade','doNotLoad',toggleProceedToCheckoutButton);
	}
}




/*-------------------------------------------------------------------------------------------------
styleMagic()
whichDiv = the div you want to apply some magic too
style    = ex: top, left, width height
amount   = how much to change it
absOrRel = Is the amount a absolute value, ie move to position top:50px. Or is it relative, ie, move up 50px.
-------------------------------------------------------------------------------------------------*/
function styleMagic(whichDiv,whichStyle,amount,absOrRel,instantOrAnimated) {
	
	if(absOrRel == "rel") {
		
		// Two possible solutions for passing in a dynamic style choise
		// 		document.getElementById(whichDiv).style[whichStyle] = value + "px";
		//		eval("document.getElementById(whichDiv).style." + whichStyle + " = value + 'px';");
		// previousValue = parseInt(document.getElementById(whichDiv).style.top);// working
		
		previousValue  = eval("document.getElementById(whichDiv).style." + whichStyle); // b/c whichStyle is a variable, we have to use eval
		previousValue  = parseInt(previousValue);
		amount 		   = parseInt(previousValue) + parseInt(amount);
		
	}
	
	// Do it instantly
	if(instantOrAnimated == 'instant') {
		eval("document.getElementById(whichDiv).style." + whichStyle + " = amount + 'px'");	// b/c whichStyle is a variable, we have to use eval
	}
	// Do it with animation	
	else {
		var targetDiv = new Fx.Style($(whichDiv),
		whichStyle, {duration: 500}).addEvent('onComplete', function() {
			// function is done
		});
		targetDiv.start(amount);
	}	
	
	
}





/*-------------------------------------------------------------------------------------------------
getCookie():
name = the name of the cookie
Javascript way to grab a cookie
--------------------------------------------------------------------------------------------------*/
function getCookie(name) {
	var start = document.cookie.indexOf( name + "=" );
	var len = start + name.length + 1;
	if ( ( !start ) && ( name != document.cookie.substring( 0, name.length ) ) ) {
		return null;
	}
	if ( start == -1 ) return null;
	var end = document.cookie.indexOf( ';', len );
	if ( end == -1 ) end = document.cookie.length;
	return unescape( document.cookie.substring( len, end ) );
}




/*-------------------------------------------------------------------------------------------------
deleteInCart();
Fade out product in shopping cart, then move the rest up
--------------------------------------------------------------------------------------------------*/
function deleteInCart(optionId,customId) {

	if(customId != "") {
		var optionId_customId = optionId + "_" + customId;
	}
	else {
		var optionId_customId = optionId;
	}
	
	// Find out how many items are in the cart
	totalItems = totalUniqueItems();
	
	// Delete it from the cart 
	changeQuantity(optionId,customId,0,"cart");
  
	// The position is stored in a hidden field with id of "positionHolder_Whatever-The-Sku-Is"
	itemPosition = parseInt(document.getElementById("positionHolder_" + optionId_customId).value);
	
	// Fade this item out
	styleMagic("item" + itemPosition,"opacity",0,"abs");
	
	// move all the products after that product up by the height of the products.
	for(i = itemPosition + 1; i < totalItems; i++ ) {
		styleMagic("item" + i,"top",-115,"rel");
	}
	
	checkCoupon(); 
	
} 




/*-------------------------------------------------------------------------------------------------
addInCart();
Move cart contents down, then fade in product
--------------------------------------------------------------------------------------------------*/
function addInCart() {

}




/*-------------------------------------------------------------------------------------------------
updateStockMessage()
Called from ajax changeQuantity image loader
--------------------------------------------------------------------------------------------------*/
function updateStockMessage(optionId,available) {
	
	if(available == 1) {
		document.getElementById("stockMsg_" + optionId).innerHTML = "In stock. Ships in 24 hours.";
	}
	else {
		document.getElementById("stockMsg_" + optionId).innerHTML = "Ships in a week!";
	}
	
}




/*-------------------------------------------------------------------------------------------------
changeQuantity(optionId,qty,fromWhere,id) AJAX
sku = sku of the product
qty = how many 
fromWhere = this is either from the product page ("product") or the cart ("cartText" or "cart". 
Seperate because the results go in two different divs. cart is further differentiated because the 
qty needs to be calculated differently if from the input ("cartText") since its not just adding or 
removing 1. But after that calculation is done we change it back to "cart" because we still want
the results put in that div.

Used on the product pages and the cart page
This function is put in the code that is generated by the printCart 
Called from the buy now buttons which are built in product_functions.php
-------------------------------------------------------------------------------------------------*/
// We need to pass the qty down to the toggleProceedToCheckoutButton function which calls refreshCartWidget. 
// This is important for the first add to cart upon creating a new shopper, because we manually have to inject the qty into the cart
// since the cart itself won't be accesible yet.
// Has to be globalQty and not just qty, because
var qty;
function changeQuantity(optionId,customId,theqty,fromWhere,resultPosition) {
							
		// Make sure it's a number
		if(isNaN(theqty)) {	
			document.getElementById("qty" + optionId).value = 1;
			return false;
		} 
		
		if(customId != "") {
			var optionId_customId = optionId + "_" + customId;
		}
		else {
			var optionId_customId = optionId;
		}
		
		// While we're doing this, disable to proceed to checkout button. Show the bogus button with no functions.
		// Only do this if the proceed to checkout button exists (ie, on the cart, not product pages)
		toggleProceedToCheckoutButton();
		
		qty = theqty; // qty is global. make it whatever the passed in qty was
				
		var changed = true;
		
		// This only applies to the input text way of changing the quantity, not the "add x" button
		if(fromWhere == "cartText") { 
			
			// They just entered the same value --- set the changed variable to false so we won't actually do any changes
			if(qty == oldQuantity) {
				changed = false;
			}
			
			// The user put a zero (or a negative number) in the qty input box -- deleteInCart! to fade it out and move the rest up
			if(qty == 0 || qty < 0) {
				deleteInCart(optionId,customId);
				qty = -oldQuantity;
			}
			else {
				// changeQuantity ajax wants not the final value, but the difference in the value. So when getting the value from the qty input box, we have to calculate the difference from what it previously was
				qty = qty - oldQuantity; 
			}
			fromWhere = "cart"; // done doing our special stuff for the input text, can set it as cart now
		}
		
	
		params = new Array(); i = 0;
		params[i]  = "action=changeQuantity";    i++;
		params[i]  = "qty=" + qty;				 i++;
		params[i]  = "fromWhere=" + fromWhere;   i++;
		params[i]  = "optionId=" + optionId;	 i++;
		params[i]  = "customId=" + customId;     i++;
				
		//  The results is put in the div that holds a text input created for each product by printCart
		if(fromWhere == "cart") {
			fadeOrNot = 'doNotFade'
			putResults = "changeQuantity_results_" + optionId_customId;	 
		}
		else if(fromWhere == "product") { 
			fadeOrNot = 'doNotFade';
			putResults = "results_addToCart_" + resultPosition;
		}	
		
		
		if(changed == true) {
			ajaxMagic('/store/cart/cart_ajax.php',params,putResults,'',fadeOrNot,'doNotLoad',toggleProceedToCheckoutButton);	
			// Don't need to do any subtotal or shipping calculations after this because changeQuantity trigers the item 
			// to load its hidden onload image which calls calculateSubtotal which then calls calculateShipping
		}
		else {
			toggleProceedToCheckoutButton();
		}
			
	    return true;
	
}




/*--------------------------------------------------------------------------------------------------
 toggleProceedToCheckoutButton() 
--------------------------------------------------------------------------------------------------*/
function toggleProceedToCheckoutButton() {

	// GIFT CARD : To forward to cart or not?
	
    var resultsObj  = document.getElementById("results_addToCart_giftCardPA"); // This is where the ajax from the last step goes
	var resultsHTML = (resultsObj) ? resultsObj.innerHTML : "";				   // This is the html in that ajax
	
	
	// First make sure it's there (ie, we're on gift card page) and it's not blank (ie, this function is being from after the ajax, not before)
	if(resultsObj && resultsObj.innerHTML != "") {

		// If a new shopper was created (indicated by the presence of cookieViaIframe) 
		// let that do the forwarding. This assures it gets to finish it's cookie setting before we redirect away.
		// Otherwise, that iframe is not loaded so we need to do the forwarding here
		if(resultsHTML.indexOf("cookieViaIframe.php") == -1) {
			window.location = "/store/cart/";
		}
	}
	
	
	
	// Note: Proceed to checkout button is also played around with in calculateTotal
	
	// Call this per the request of changeQuantity above. Do it here because we know calculations are done.
	refreshCartWidget(qty); // qty is global and set by above function
	
	// Only do this if the proceed to checkout button actually exists (ie, on the cart page and not the product page.
	if(document.getElementById('proceedToCheckoutButton_container')) {
		
		// It's off, turn it back on
		if(document.getElementById('proceedToCheckoutButton_container').style.display == "none") {	
			
			// Switch the main PTC button
			document.getElementById('proceedToCheckoutButton_container').style.display 	     = "block";
			document.getElementById('proceedToCheckoutButton_container_bogus').style.display = "none";
			
			// Turn the cover on over the Credit, PP, BT logos
			document.getElementById('paymentButtons_cover').style.display = "none";
	
			
		}
		// It's on, turn it off
		else {
		
			// Switch the main PTC button
			document.getElementById('proceedToCheckoutButton_container').style.display 	     = "none";
			document.getElementById('proceedToCheckoutButton_container_bogus').style.display = "block";
			
			// Turn the cover off over the Credit, PP, BT Logos
			document.getElementById('paymentButtons_cover').style.display = "block";
		}
	}
		
}


/*-------------------------------------------------------------------------------------------------
printCart() - AJAX caller
* Called on cart index.php body load
-------------------------------------------------------------------------------------------------*/
// Called on body load
function printCart(shopper) {

	var gwoTest = (document.getElementById("GWO")) ? document.getElementById("GWO").value : "";

	params     = new Array(); i = 0;
	params[i]  = "action=printCart";      i++;	
	params[i]  = "shopper=" + shopper;    i++;
	params[i]  = "gwoTest=" + gwoTest;    i++;
	putResults = "results_printCart";	
	ajaxMagic('cart_ajax.php',params,putResults,'','doNotFade','doNotLoad');
}




/*-------------------------------------------------------------------------------------------------
storeOldQuantity() -

Called by onKeyDown in the quantity text input on the cart page. Captures what the value was 
when they enter the text field...changeQuantity is then called onKeyUp (after the value is changed) 
and it uses the value stored here (oldQuantity) to compare the difference.
-------------------------------------------------------------------------------------------------*/
var oldQuantity; 
function storeOldQuantity(quantity) {
	
	if(quantity != "") {
		oldQuantity = quantity;
	}
	
}




/*-------------------------------------------------------------------------------------------------
dontLeaveBlank() 

Called by onBlur of the quantity field. If the value is left as blank and they click off, 
then it restores what the value was
-------------------------------------------------------------------------------------------------*/
function dontLeaveBlank(quantity,whichOne) {
	if(quantity == "") {
		whichOne.value = oldQuantity;
	}
}


/*-------------------------------------------------------------------------------------------------
ShippingMethods()
-------------------------------------------------------------------------------------------------*/
function shippingMethods() {
	
	params = new Array(); i = 0;	
	params[i]  = "action=shippingMethods"; i++;		
	
	putResults = "shippingMethods_results";	 
	ajaxMagic('cart_ajax.php',params,putResults,'','doNotFade','doNotLoad');

}



/*-------------------------------------------------------------------------------------------------
calculateSubtotal() 
Calculate the running total, this is done every time invisible images in changeQuantity are loaded
-------------------------------------------------------------------------------------------------*/
function calculateSubtotal() {

	var total = 0;
	var price;
	var totalWithoutGiftCertificates = 0;

	// Figure out if we add $5 charge for gift wrap
	total = (document.getElementById("giftWrap_checkbox") && document.getElementById("giftWrap_checkbox").checked == true) ? 5 : 0;

	// Get all the images
	for (x=0; x<document.images.length; x++){
		
    	// The price is stored in the title... has _itemPrice at the end of it (at the end so parseFloat will work on it)
     	price       = document.images[x].title;
     	productName = document.images[x].alt;
     
     	
     	if(price != "" && price != "undefined" && price.indexOf("_itemPrice") > 0) {
     		// Calculate the total if this is a valid price
     		
     		total = parseFloat(total) + parseFloat(price);
     		
     		// Keep a seperate total that does not include gift certificates
     		if(productName.indexOf("Gift") < 0) {
     			totalWithoutGiftCertificates = parseFloat(totalWithoutGiftCertificates) + parseFloat(price);
     		}	
     	}
	}
		
	// Round the total
	total = Math.round(total*100)/100;
	
	params = new Array(); i = 0;	
	params[i]  = "action=calculateSubtotal"; i++;	
	params[i]  = "total=" + total;       i++;
	
	document.getElementById("subtotal_hidden").value = total;
	document.getElementById("totalWithoutGiftCertificates_hidden").value = totalWithoutGiftCertificates;
	
	if(document.getElementById("subtotal_results")) {
		document.getElementById("subtotal_results").innerHTML = "$" + formatAsMoney(total);
	}
		
	// * SPECIAL * Free ship orders > 50: Update the note on top of the cart with how much they have to add to their cart to get free ship
	if(total < 50) {
		var dollarsAway = 50 - total;
		dollarsAway = Math.round(dollarsAway*100)/100;
		document.getElementById("howMuchMoreForFreeShip").innerHTML = "Free domestic shipping on orders over $50. Add <b>$" + dollarsAway + " more</b> to ship free!";
	}
	else {
		document.getElementById("howMuchMoreForFreeShip").innerHTML = "You qualify for FREE shipping! <b>Enter your zip code to see the option.</b>";
	}
		
	return total; // Says total, is actually subtotal
	
}




/*-------------------------------------------------------------------------------------------------
checkZip
-------------------------------------------------------------------------------------------------*/
function checkZip() {
		
	// If they didn't enter a zip, don't check anything, throw an error
	if(document.getElementById("zip_input").value == "") {
		errorField("zip",false,"Enter your zip code<br>for shipping rates",1);
	}
	else {
		errorField("zip",true);
	
			
		if(document.getElementById("zip_label").innerHTML == "Zip code") {
			domOrInt = "domestic";
		}
		else {
			domOrInt = "international";
		}
		
		zip = document.getElementById("zip_input").value;
	
		// Only do the following if we actually have a zip
		if(zip != "") {	
			params = new Array(); i = 0;	
			params[i]  = "action=checkZip";      i++;	
			params[i]  = "zip=" + zip;    	    i++;
			params[i]  = "domOrInt=" + domOrInt; i++;
			
			//  The results is put in the div that holds a text input created for each product by printCart
			putResults = "checkZip_results";	 
			ajaxMagic('cart_ajax.php',params,putResults,'','doNotFade','doNotLoad',calculateShipping);
		}
	
	}
	
	
}




/*-------------------------------------------------------------------------------------------------
changeCountryFromWidget() 
Fired when the user changes the country in the drop down
-------------------------------------------------------------------------------------------------*/
function changeCountryFromWidget(countryDropdown,shopper) {

	var n = countryDropdown.selectedIndex;     		// Which menu item is selected
	var whichCountry = countryDropdown[n].value;   // Return string value of menu item
	

	// International - change zip label and ship type
	if(whichCountry != "United States" && whichCountry != "US") {
		document.getElementById("zip_label").innerHTML = "Postal code";
		document.getElementById("freeShipPromoBox").style.display = "none";
	} 
	// Domestic - change zip label and ship type
	else {
		document.getElementById("zip_label").innerHTML = "Zip code";
		document.getElementById("freeShipPromoBox").style.display = "block";
	}

	// Do some ajax to update the country in the database
	params = new Array(); i = 0;	
	params[i]  = "action=changeCountry"; 	i++;	
	params[i]  = "country=" + whichCountry; i++;
	params[i]  = "shopper=" + shopper; i++;
	putResults = "changeCountry_results";	 
	
	ajaxMagic('cart_ajax.php',params,putResults,'','doNotFade','doNotLoad',postChangeCountryFromWidget);
	
}

function postChangeCountryFromWidget() {

	// Because we have to pass this false variable, we couldnt just put this post ajax, had to call this function w/p param and then have it call calculateShipping w/ param.
	calculateShipping(false); 
}




/*-------------------------------------------------------------------------------------------------
formatAsMoney()
-------------------------------------------------------------------------------------------------*/
function formatAsMoney(mnt) {
    mnt -= 0;
    mnt = (Math.round(mnt*100))/100;
    return (mnt == Math.floor(mnt)) ? mnt + '.00' 
              : ( (mnt*10 == Math.floor(mnt*10)) ? 
                       mnt + '0' : mnt);
}




/*-------------------------------------------------------------------------------------------------
calculateTotal()
-------------------------------------------------------------------------------------------------*/
function calculateTotal() {

	// Get some variables from the page
	if(document.getElementById('shipping_hidden')) {
		var shipping   = document.getElementById('shipping_hidden').value;
	}
	if(document.getElementById("coupon_input")) {
		var couponCode = document.getElementById("coupon_input").value;
	}
	if(document.getElementById('country_input')){
		var country    = document.getElementById('country_input').value;
	}
	if(document.getElementById('subtotal_hidden')) {
		var subtotal   = document.getElementById('subtotal_hidden').value;
	}
	if(document.getElementById("checkZip_results")) {
		var cityState  = document.getElementById("checkZip_results").innerHTML;
	}
	if(document.getElementById("totalWithoutGiftCertificates_hidden")) {
		var totalWithoutGiftCertificates_hidden = document.getElementById("totalWithoutGiftCertificates_hidden").value;
	}
	
	var discount;
	if(document.getElementById("discount_results")) {
		var discount   = document.getElementById("discount_results").innerHTML;
	}

	// ::::::::::: Tax (if California)	
		// Contents of the zipBlur_results div has lots of garbage in addition to just the city state.
		// So we just want to grab the last 10 chars and see if its California. 
		var length 			= cityState.length;  			  // Because jscript wont let us do substr from the right, we have to find out how long it is, then subtract
		var maybeCalifornia = cityState.substring(length-10); // This is the last 10 characters of the cityState
		
		// Sometimes the state is California, sometimes it's alifornia. We just need to catch part of it to see if it's CA or not
		var alsoMaybeCalifornia = maybeCalifornia.search(/, CA/);
		var maybeCalifornia     = maybeCalifornia.search(/fornia/);
	
	
		if((maybeCalifornia != -1 || alsoMaybeCalifornia != -1) && document.getElementById("checkZip_results").style.display != "none" && country == "US") {
			
			// This same rule happens in checkout_functions.js under recalcTotal()
			// Also happens in manualOrder_ajax.php
			var taxable  = parseFloat(totalWithoutGiftCertificates_hidden) + parseFloat(shipping);
			var tax      = .095 * parseFloat(taxable);	 // Changed from .085 to .095 on 7/3/09 see: http://summerjojo.pbworks.com/rateChanges
			tax          = Math.round(tax*100)/100;

		}
		else {
			tax = "0.00";
		}
		
		
		if(subtotal == "" || subtotal == 0) {
			tax = "0.00";
		}
		
		document.getElementById('tax_results').innerHTML = "$" + formatAsMoney(tax);
	
	
	// ::::::::::: Discount
	// Figure out the discount - do this when calculateTotal is being called from the end of the coupon checking functions
	// Otherwise, just get the discount from the discount row if it's there
	if(document.getElementById("coupon_hidden") != "" && document.getElementById("coupon_hidden")) {
		
		// Blank slate
		var deduct     = "0.00";	
		
		// Look for the ajax results given by checkCoupons
		var discount   = document.getElementById("coupon_hidden").value; // This will either be $5 or %5 or an error such as "Drats, couldn't find this coupon
		
		// Percentage off - has a %
		if(discount.search(/%/) != -1) {
			discount   = parseFloat(discount);  				        // Get just the number
			percentage = discount / 100;								// Make it a percentage
			// var discountable = parseFloat(subtotal) + parseFloat(shipping)  + parseFloat(tax); // Old way - shouldn't discount shipping and tax! 
			var discountable = parseFloat(subtotal);

			deduct     = parseFloat(percentage) * discountable; // Calculate the percentage of the subtotal
			deduct     = deduct.toFixed(2);						        // Round the decimals				
		}
		// Dollar off - has a $
		else if(discount.search(/$/) != -1) {
			deduct   = parseFloat(discount);  // Get rid of the $ and Off
		}
		// Otherwise, it's an error - do nothing
		else {
			// Nothing! 
		}
		
		// Inject our resulting deduction into the discount line
		document.getElementById("discount_results").innerHTML = "-$" + formatAsMoney(deduct);	
	}
	// # Else, get discount from discount row
	else {
		discount = discount.replace("-$", ""); // parseFloat won't work on a string that doesn't start with a number, so get rid of that -$
		deduct   = parseFloat(discount);       // This isn't really necessary because it should just be a number now
	}
	
	// Result of a bad coupon will be NaN
	if(isNaN(deduct)) {
		deduct = "0.00";
	}
	
	
	// ::::::::::: Total	
		
		
		total = parseFloat(subtotal) + parseFloat(tax) + parseFloat(shipping) - parseFloat(deduct);
		total = Math.round(total*100)/100; // rounds?
		
		
		if(subtotal == "" || subtotal == 0) {
			total = "0.00";
		}
		
		document.getElementById('total_results').innerHTML = "$" + formatAsMoney(total);
		
		// Ok to display 'proceed to checkout button now
		document.getElementById('proceedToCheckoutButton_container').style.display = "block";
		document.getElementById('proceedToCheckoutButton_container_bogus').style.display = "none";
		
		
		// Build array of results we're going to return
		totals = new Array(); 
		totals['total'] 		= parseFloat(total);
		totals['subtotal'] 		= parseFloat(subtotal);
		totals['discount']      = parseFloat(discount);
		totals['tax']			= parseFloat(tax);
		totals['shipping'] 		= parseFloat(shipping);
		totals['deduct'] 		= parseFloat(deduct);
		totals['couponCode']    = couponCode;
		
		
		// Do ajax call to save these totals to the database
		params     = new Array();i = 0;
		params[i]  = "action=calculateTotal"; i++;	
		params[i]  = "total="      + total; i++;
		params[i]  = "subtotal="   + subtotal; i++;
		params[i]  = "tax=" 	   + tax; i++;
		params[i]  = "shipping="   + shipping; i++;
		params[i]  = "deduct="     + deduct; i++;
		//params[i]  = "couponCode=" + couponCode; i++;
		putResults = "calculateTotal_results";	
		ajaxMagic('cart_ajax.php',params,putResults,'','doNotFade');

		//userLog(shopper,"Calculate total. Total: " + total + " | Subtotal: " + subtotal + " | Tax: " + tax + " | Shipping: " + shipping + " | Deduct:" + deduct);
		
		return totals;
}




/*-------------------------------------------------------------------------------------------------
changePrice() - AJAX CALLER
-------------------------------------------------------------------------------------------------*/
function changePrice(shopper, sku, qty) {
	
	params = new Array(); i = 0;
	
	params[i]  = "action=changeQuantity"; i++;	
	params[i]  = "qty=" + qty;				 i++;
	params[i]  = "sku=" + sku;				 i++;
	params[i]  = "shopper=" + shopper;       i++;
	params[i]  = "fromWhere=" + fromWhere;   i++;
	
	//  The results is put in the div that holds a text input created for each product by printCart
	putResults = "results" + sku;	 
	 
	ajaxMagic('cart_ajax.php',params,putResults,'','doFade');
}




/*-------------------------------------------------------------------------------------------------
deleteFromCart() - AJAX CALLER 
-------------------------------------------------------------------------------------------------*/ 
function deleteFromCart(shopper,sku) {
	params = new Array(); i = 0;
	
	params[i]  = "action=deleteFromCart";    i++;	
	params[i]  = "sku=" + sku;				 i++;
	params[i]  = "shopper=" + shopper;       i++;
	
	//  The results is put in the div that holds a text input created for each product by printCart
	putResults = "item" + sku;	 
	ajaxMagic('cart_ajax.php',params,putResults,'','doFade');
}






