//*********************************************
//* Filename    : SinglePageCheckout.js
//* Author      : Kennon Brown
//* Create Date : 06/25/2009
//* Description : client-side validation for  SinglePageCheckout.php
//* Change Log  :
//*    06/30/2009 - Created File
//*********************************************/

// Extended Tooltip Javascript
// copyright 9th August 2002, 3rd July 2005, 24th August 2008
// by Stephen Chapman, Felgall Pty Ltd

// permission is granted to use this javascript provided that the below code is not altered
function pw() {return window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth}; function mouseX(evt) {return evt.clientX ? evt.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft) : evt.pageX;} function mouseY(evt) {return evt.clientY ? evt.clientY + (document.documentElement.scrollTop || document.body.scrollTop) : evt.pageY} function popUp(evt,oi) {if (document.getElementById) {var wp = pw(); dm = document.getElementById(oi); ds = dm.style; st = ds.visibility; if (dm.offsetWidth) ew = dm.offsetWidth; else if (dm.clip.width) ew = dm.clip.width; if (st == "visible" || st == "show") { ds.visibility = "hidden"; } else {tv = mouseY(evt) - 30; lv = mouseX(evt) + (ew/6); if (lv < 2) lv = 2; else if (lv + ew > wp) lv -= ew/2; lv += 'px';tv += 'px';  ds.left = lv; ds.top = tv; ds.visibility = "visible";}}}
//
//*********************************************/
 
function showError(errTxt,errColor)
{
	if (errColor == undefined) errColor = '#FF0000';
	if($('error_messages'))
	{
		$('error_messages').innerHTML = "<span style=\"color:"+errColor+"\";>"+errTxt+"</span>";
		new Effect.Highlight("error_messages");
		if($('error_messages2'))
		{
			$('error_messages2').innerHTML = "<span style=\"color:"+errColor+"\";>"+errTxt+"</span>";
			new Effect.Highlight("error_messages2");
		}
	}
	else
	{
		alert(errTxt);
	}
	return false;
}
function validateForm()
{
	var errorTxt = '';
	var birthDate = $('DOB');
	if(birthDate) if(($('DOB').value.length < 1)||($('DOB').value.length < 1))
		errorTxt += 'Please enter the Recipient\'s date of birth.<br/>';
	if(($('billing_FirstName').value.length < 1)||($('billing_LastName').value.length < 1))
		errorTxt += 'Please enter a first name and a last name.<br/>';
	var billingAddress = ($('billing_Address1').value.replace(/^\s+|\s+$/g,'').length + 
		$('billing_Address2').value.replace(/^\s+|\s+$/g,'').length);
	//if(billingAddress > 20)
	//	errorTxt += 'Your address is too long (max 20).<br/>';
	if(billingAddress < 1)
		errorTxt += 'Please enter a billing address.<br/>';
	if($('billing_City').value.length < 1)
		errorTxt += 'Please enter a billing city.<br/>';
	if(($('billing_ZipCode').value.length != 5)&&($('billing_ZipCode').value.length != 9))
		errorTxt += 'Please enter a five or seven digit postal code.<br/>';
	$('billing_FaxAreaCode').value = $('billing_FaxAreaCode').value.replace(/\D/g,"").substr('0','3');
	$('billing_Fax').value = $('billing_Fax').value.replace(/\D/g,"").substr('0','7');
	$('billing_AreaCode').value = $('billing_AreaCode').value.replace(/\D/g,"").substr('0','3');
	$('billing_Phone').value = $('billing_Phone').value.replace(/\D/g,"").substr('0','7');
	if(($('billing_AreaCode').value.length != 3)||
		($('billing_Phone').value.length != 7))
		errorTxt += 'Please enter an area code and phone number.<br/>';
	if($('SameAsShipping').checked != true)
	{
		if(($('shipping_FirstName').value.length < 1)||($('shipping_LastName').value.length < 1))
			errorTxt += 'Please provide your First and Last names for the shipping label.<br/>';
		var shippingAddress = ($('shipping_Address1').value.replace(/^\s+|\s+$/g,'').length + 
			$('shipping_Address2').value.replace(/^\s+|\s+$/g,'').length);
		//if(shippingAddress > 20)
		//	errorTxt += 'Your address is too long (max 20).<br/>';
		if(shippingAddress < 1)
			errorTxt += 'Please enter a shipping address.<br/>';
		if($('shipping_City').value.length < 1)
			errorTxt += 'Please enter a shipping City.<br/>';
		if(($('shipping_ZipCode').value.length != 5)&&($('shipping_ZipCode').value.length != 9))
			errorTxt += 'Please enter a five or nine digit shipping zip code.<br/>';
		$('shipping_AreaCode').value = $('shipping_AreaCode').value.replace(/\D/g,"").substr('0','3');
		$('shipping_Phone').value = $('shipping_Phone').value.replace(/\D/g,"").substr('0','7');
		if(($('shipping_AreaCode').value.length != 3)||
			($('shipping_Phone').value.length != 7))
			errorTxt += 'Please enter an area code and phone number for Shipping.<br/>';
	}
	if(errorTxt)
	{ return(showError(errorTxt));}
	else return true;
}
function toggleShipping(shipLabel,shipInput,chkbox) 
{ 
	var ctrl = $(chkbox); 
	var labels = $$('.'+shipLabel); 
	var inputs = $$('.'+shipInput); 
	if((ctrl === null) ) return false;
	if (!$(chkbox).checked) 
	{ 
		//labels.each(function (d) { alert(d);}); 
		labels.each(function (d) { $(d).style.display = '';}); 
		inputs.each(function (d) { $(d).enable(); $(d).style.display = '';}); 
		inputs.each(function (d) { $(d).enable();}); 
	}
	else 
	{ 
		//labels.each(function (d) { alert(d);}); 
		labels.each(function (d) { $(d).style.display = 'none';}); 
		inputs.each(function (d) { $(d).disable(); $(d).style.display = 'none';}); 
		inputs.each(function (d) { $(d).disable(); }); 
	} 
} 
function selectOption(selectID,optionValue)
{
	var select = $(selectID);
	for(var i = 0; i < select.options.length; i++)
	{
		if(select.options[i].value == optionValue)
			select.options[i].selected = true;
		else
			select.options[i].selected = false;
	}
}
Event.observe(window, 'load', init, false);function init()
{  
	$('cmd').value = 'UpdateCart'; 
	//$('shippinginfo').style.display = 'none'; 
	toggleShipping('shippinginfo','shippingInput','SameAsShipping'); 
	//updateSubtotals();
	$('CouponCode').observe('blur',function () { updateSubtotals();});
	$("billing_ZipCode").observe('change',function () { updateSubtotals();});
	$('billing_State').observe('change',function () { updateSubtotals();});
	$('shipping_ZipCode').observe('change',function () { updateSubtotals();});
	$('shipping_State').observe('change',function () { updateSubtotals();});
	$$("td.showDesc").each(function(a){
	//	Event.observe(a, 'mouseover', function(){alert("mouseOver");});
	//	Event.observe(a, 'mouseout', function(){alert("mouseOut");});
	});		
}
Event.observe(window, 'load', catchenter, false);function catchenter() {
        $('CartForm').observe('keydown', function (e) {
                if ( e.keyCode == 13 ) {
						$('cmd').value = 'Continue';
						return false;
                }
        });

}; 
//update tax amount
function settax(tx)
{
	$('tax').value = tx.toFixed(2);
}
//update shipping amount
function setshipping(shipping)
{
	$('shipping').value = shipping.toFixed(2);
}
//form input handling functions
function updateCCName()
{
	var fName = $('billing_FirstName'); if(!fName) return;
	var lName = $('billing_LastName'); if(!lName) return;
	var ccName = $('CCName'); if(!ccName) return;
	ccName.value = fName.value.trim()+' '+lName.value.trim();
}
// force quantity to whole numbers and 
// update item subtotal and call updateSubtotals()
function updateItem(id)
{
	$('cmd').value = 'UpdateCart';
	var unitPrice = $('item_price_'+id);  if(!unitPrice) return;
	var quantity = $('ProductQuantity_'+id);  if(!quantity) return;
	quantity.value = (quantity.value*1).toFixed(0);
	var totalPrice = $('item_subtotal_'+id); if(!totalPrice) return;
	totalPrice.value = (unitPrice.value * quantity.value).toFixed(2);
	updateSubtotals();
}

// update total items and raw subtotal price
function updateSubtotals()
{
	var st = $$(".itemQuantity");
	if(st){$("item_count").value = 0;st.each(function (d){$("item_count").value = parseInt($(d).value) + parseInt($("item_count").value);});}

	var st = $$(".itemSubtotal");
	if(st){$("subtotal").value = 0; st.each(function (d){$("subtotal").value = (parseFloat($(d).value) + parseFloat($("subtotal").value)).toFixed(2);});}
	//updateShipping();
	updateDiscount();
}
function updateDiscount(attempts)
{
	if(attempts == undefined) attempts = 0;
	if($('ajax')) $('ajax').value = 'true';
	var formdata = $('CartForm').serialize();
	if($('ajax')) $('ajax').value = 'false';
	var uriStr = 'SinglePageStore_ajax.php';//+ formdata;
	new Ajax.Request(uriStr,{
		method: 'post',
		parameters: formdata,
		onSuccess: function(transport){
			//alert(formdata);
			//alert(transport.responseText);
			//showError(transport.responseText);
			eval(transport.responseText);
			updateGrandtotals();
		}
		,
		onFailure: function(transport){
			if(!attempts)
			{
				updateDiscount(1);
			}
			else
			{
				showError(attempts+" Unable to connect to server. Please check your internet connection and try again.");
			}
		}
		});
}
function setdiscountinfo(name,mode,amount)
{
	if(amount == undefined) amount = '';
	if(name == undefined) name = '';
	if(mode == undefined) mode = ' no discount';
	if(mode == 'Dollars') amount = '$ '+amount.toFixed(2);
	if(mode == 'Percent') mode = ' % ';

	$('discname').innerHTML = name;
	$('discdetail').innerHTML = amount+' '+mode+' off of all qualifying purchases';
}
function setdiscount(discount)
{
	if(discount == undefined) discount = 0;
	
	discount = (parseFloat(Math.round(discount * 100)) / 100);
	$('discount_field').value = discount.toFixed(2);
}
// update total items and raw subtotal price
function updateGrandtotals()
{
//	$('tax').value = ($('taxrate').value/100 * $('subtotal').value).toFixed(2);
	$('total').value = (parseFloat($('shipping').value) + parseFloat($('tax').value) + parseFloat($('subtotal').value) - parseFloat($('discount_field').value)).toFixed(2);
}



