/*********************************************************************************

	Purpose:
		Add event handlers to option fields and quantity field to call qtCalc
		so it doesn't have to be done in template file...code in 
		storefront_foot.php will call this
		
*********************************************************************************/
function qtSetup() {
	var prodOpts,prodOpt,i=0,x,changeLink;
	// bail if browser is not W3CDOM compliant
	if (!document.getElementById) return;
	
	// setup option fields
	while (prodOpts = document.getElementsByName('option_'+i)) {
		if (!prodOpts[0]) break;
		for(x=0;prodOpts[x];x++) {
			fld = prodOpts[x];
					
			if (fld.nodeName == 'SELECT') {
				addEventJS(fld,'onchange',qtCalc);
			} else if (fld.type == 'text' || fld.type == 'textarea' || fld.type == 'file') {
				// for typing
				addEventJS(fld,'onkeyup',qtCalc);
				// for pasting via mouse in IE
				addEventJS(fld,'onmouseleave',qtCalc);
				// for pasting via mouse in Moz
				addEventJS(fld,'oninput',qtCalc);
				
				if (fld.type == 'file')	addEventJS(fld,'onchange',qtCalc);				
			} else if(fld.type == 'checkbox' || fld.type == 'radio') {
				addEventJS(fld,'onclick',qtCalc);
			}
		}
		i++;
	}
	
	// setup quantity fields
	prodOpts = document.getElementsByName('quantity');
	if (prodOpts) {
		for(x=0;prodOpts[x];x++) {
			fld = prodOpts[x];

			// support a select quantity field, if customer changes it
			if (fld.nodeName == 'SELECT') {
				addEventJS(fld,'onchange',qtCalc);
			} else {
				addEventJS(fld,'onkeyup',qtCalc);				
			}
		}
	}
	
}


/******************************************************************************************************************

	Purpose:
		This function is called first when an option changes. It starts the process by calling PHP function
		qt_get_discount() via AJAX.
		

******************************************************************************************************************/
// Global var to store ref. to form element we are working with
var prodForm;
function qtCalc(evt) {
	var srcElem;

	// prodForm needs to be reset
	prodForm = null;
	
	// see if evt is actually a form element
	if (evt) {
		if (evt.nodeName == 'FORM') prodForm = evt;
	}
	
	// if here, than we need to grab form based on event that triggered the call to qtCalc()
	if (!prodForm) {
		// grab reference to evt if it wasn't sent
		evt = evt ? evt : (window.event ? event : null);
		
		// just in case
		if (!evt) return;
		
		// grab element that triggered this event
		srcElem = evt.target ? evt.target :
			evt.srcElement ? evt.srcElement : null;
			
		// just in case
		if (!srcElem) return;
		
		// in order to retain the value of srcElem, we will set a temporary var to be used
		// below to find the parent form tag
		var checkElem = srcElem;
		
		// grab reference to form tag that is parent to the src. element
		while(checkElem.nodeName != 'FORM') checkElem = checkElem.parentNode;
		prodForm = checkElem;
	}
	
	// just in case
	if (!prodForm) return;
	
	var prodRn 	= prodForm.p_rn.value;
	var discountsPresent = prodForm.discounts_present ? 1 : 0;
	
	if (!srcElem) srcElem = prodForm.quantity;
	
	// only need to check for discounts when the quantity has changed
	if (srcElem && discountsPresent) {
		if (srcElem.name == 'quantity') {
			var qty = parseInt(srcElem.value);
			if (qty) {
				x_get_discount('product',prodRn,0,0,0,0,srcElem.value,qtCalcUpdate);
				return;
			}
		}
	}
	
	// if here, than no need to check for discount info...just call qtCalcUpdate
	qtCalcUpdate();

}




/*******************************************************************************************************************

	Purpose of function is to calculate the total price of an item based on quantity, options, and base charge
	
	Parameters:
		discount	(string) 	This is optional, and if set will be a string returned via AJAX from the get_discount()
								PHP function. Format is as follows:
								discount_price^^^discounted_qty^^^discounted_qty_in_cart

*******************************************************************************************************************/
function qtCalcUpdate(discount) {
	var i=0,x=0,val=0,fld,opt,prodTotal=0,opsPrice=0,pricePoint,discountPrice,discountedQty,discountedQtyInCart,isPercentage=0,percentOpts = new Array();
	// this requires that prodForm be set...if it's not, bail
	if (!prodForm) return;
	// handle discount info, if passed
	if (discount) {
		// pull vars from data returned from get_discount()
		var discountArray 	= discount.split('^^^');
		discountPrice		= discountArray[0];
		discountedQty 		= discountArray[1];
		discountedQtyInCart			= discountArray[2];
		
		// if there are discounted items...
		if (discountedQty) {
			prodForm.discount_price.value			= discountPrice;
			prodForm.discounted_qty.value			= discountedQty;
			prodForm.discounted_qty_in_cart.value 	= discountedQtyInCart;
		} else {
			prodForm.discount_price.value			= 0;
			prodForm.discounted_qty.value			= 0;
			prodForm.discounted_qty_in_cart.value 	= 0;
		}
	}

	// option fields are named incremently, like option_0, option_1, etc...
	// loop thru all of them
	while(fld = prodForm['option_'+(i++)]) {
		// cleanup for each run
		val = 0;
		isPercentage = 0;

		// saved file options have names like "saved_option_X" and will contain a value if the file was upload and item is being modified
		// this will change "fld" from the upload field to the saved readonly field as needed
		if (prodForm['saved_option_'+(i-1)] && prodForm['saved_option_'+(i-1)].value.length > 0) fld = prodForm['saved_option_'+(i-1)];
		
		// if the field is a radio option, then it won't have a nodename
		if (!fld.nodeName) {
			x=0;
			while (opt = fld[x]) {
				if (opt.checked) val = parseFloat(opt.getAttribute('price'));
				isPercentage = opt.getAttribute('percentage');
				// bail as soon as one is checked
				if (val > 0) break
				x++;
			}
		} else if (fld.nodeName == 'SELECT') {
			val = parseFloat((fld.options[fld.options.selectedIndex].getAttribute('price')));
			isPercentage = fld.options[fld.options.selectedIndex].getAttribute('percentage');
		} else if (
			(
				(fld.type == 'text' || fld.type == 'textarea' || fld.type == 'file') && fld.value.length > 0
			)
			||
			(
				fld.type == 'checkbox' && fld.checked			
			)
		) {
			val = parseFloat(fld.getAttribute('price'));
			isPercentage = fld.getAttribute('percentage');
			
		} else {
			val = 0;
			isPercentage = 0;
		}

		// if options above aren't selected, val could be NaN...this fixes that
		if (!val) val = 0;
		
		// handle per character charges
		pricePoint = fld.getAttribute('price_point');
		
		if (pricePoint == 'char' || pricePoint == 'char_spaces') {
			if (pricePoint == 'char_spaces') {
				val *= fld.value.length;
			} else if (pricePoint == 'char') {
				// strip spaces
				val *= fld.value.replace(/\s/g,'').length;
			}
		}

		// we can't add the cost of the item to the total if it is a percentage type option
		if (isPercentage == '1') {
			percentOpts[percentOpts.length] = val;
		} else {
			opsPrice += val;
		}
	}

	// grab base price, and remove commas
	var basePrice = parseFloat(prodForm.b_price.value.replace(',',''));
	var qty = parseFloat(prodForm.quantity.value);
	
	discountedQty = parseInt(prodForm.discounted_qty.value);
	
	if (discountedQty) {
		discountPrice 	= parseFloat(prodForm.discount_price.value);
		discountedQtyInCart		= parseInt(prodForm.discounted_qty_in_cart.value);

		// of the current qty entered on the form, the number we can discount
		// will be the discountedQty - discountedQtyInCart
		discountedQty	-= discountedQtyInCart;
		regPriceQty		= qty - discountedQty;
		
		// total cost of all discounted units
		var discountedTotal = (opsPrice + discountPrice)*discountedQty;
		// total cost of all NON discounted units
		var regTotal 		= (opsPrice + basePrice)*regPriceQty;
		// total cost of the 2 above
		prodTotal = discountedTotal + regTotal;
	} else {
		// add base price
		prodTotal = basePrice + opsPrice;
		
		// multiply by quantity IF it's a number
		if (qty) {
			prodTotal *= qty;
		} else {
			prodTotal = 0;
		}
	}
	
	// check for a base_charge field, which is a one time charge
	if (prodForm.base_charge) prodTotal += parseFloat(prodForm.base_charge.value);
	
	// handle adding percentage options
	var x,percentTotal=0;
	for(x in percentOpts) {
		percentTotal += prodTotal * (percentOpts[x] / 100);
	}
	prodTotal += percentTotal;
	
	// grab the product record number
	var prodRn = prodForm.p_rn.value;
	
	// grab the tag that will receive the product total
	var prodTotalTag = document.getElementById('quick_total_' + prodRn);
	
	// parent tag surrounding the total
	var prodTotalDiv = prodTotalTag.parentNode;
	
	// this breaks with large quantities...so just force prodTotal to match basePrice so it won't appear
	if (qty) {
		if (qty.toString().length > 14) prodTotal = basePrice;
	} else {
		// no qty should force prodTotal to same as basePrice so total div is hidden
		prodTotal = basePrice;
	}
	
	// if prodTotal is larger than the base price, show it, else hide it
	prodTotalDiv.style.display = prodTotal != basePrice ? 'block' : 'none';
	
	// format with commas and 
	prodTotal = formatCurrency(prodTotal);

	// update item total on product page
	prodTotalTag.innerHTML = '$' + prodTotal;
}