var theForm = '';
var theField = '';

function sameAsBilling(theForm) {
	var flds = Array('firstName', 'lastName', 'email', 'company', 'address', 'address2', 'city', 'state', 'country', 'postalCode', 'phone', 'phone2');
	for (var i=0; i<flds.length; i++)
		if (theForm['B' + flds[i]] && theForm['S' + flds[i]])
			theForm['S' + flds[i]].value = theForm['B' + flds[i]].value
}

function confirmContinue(theForm) {
	window.location='/shop/';
}

function proceedToCheckout(theForm) {
	var res = false;
	if (Summit.Form.ValidateForm(theForm)) {
		res = true;
	}
	return res;
}

function expressCheckout(theForm) {
	var res = false;
	if (Summit.Form.ValidateForm(theForm)) {
		send(AJAX_URL + '?do=validateEmail&' + $('expressCheckoutFrm').serialize(), 'expressCheckoutResponse');
	}
	return res;
}

function expressCheckoutResponse() {
	if (XmlHttp.readyState==4){
		result = XmlHttp.responseText;
		XmlHttp=null;
		if (result==1) {
			window.location = '/actions/continueWithoutLogin/' + document.forms['expressCheckoutFrm']['email'].value + '/';
		} else {
			$('expressCheckoutEmailUsed').show();
		}
	}
}

function membersCheckout(theForm) {
	var res = false;
	if (Summit.Form.ValidateForm(theForm)) {
		send(AJAX_URL + '?do=validateMember&' + $('membersCheckoutFrm').serialize(), 'membersCheckoutResponse');
	}
	return res;
}

function membersCheckoutResponse() {
	if (XmlHttp.readyState==4){
		result = XmlHttp.responseText;
		XmlHttp=null;
		if (result==1) {
			window.location = '/order/cart/';
		} else {
			$('membersCheckoutUserNotFound').show();
		}
	}
}

function doSignup(theForm) {
	if (!$('signUpForm')) return false;
	if (Summit.Form.ValidateForm(theForm)) {
		if (theForm['password'].value!=theForm['passwordConf'].value) {
			alert('Confirmation password is incorrect');
		} else {
			send(AJAX_URL + '?do=shopSignup&' + $('signUpForm').serialize(), 'signupResponse');
		}
	}
}

function signupResponse() {
	if (XmlHttp.readyState==4){
		result = XmlHttp.responseText;
		XmlHttp=null;
		if (result==1) {
			window.location = '/order/cart/';
		} else {
			alert('Error: unable to create an account.');
		}
	}
}

function validateEmail(el) {
	if (!el.value) return true;
	if (!$('validateEmailResponse')) return false; 
	theForm = el.form;
	theField = el.name;
	send(AJAX_URL + '?do=validateEmail&email=' + el.value, 'validateEmailResponse');
}

function validateEmailResponse() {
	if (XmlHttp.readyState==4){
		result = XmlHttp.responseText;
		XmlHttp=null;
		if (result==1) {
			$('validateEmailResponse').hide();
		} else {
			$('validateEmailResponse').show();
		}
	}
}

function recalculateOrder(el) {
	var theForm = document.forms['orderFrm'];
	if (!theForm) return false;
	var subTotal = theForm['subTotal'].value*1;
	var sShipping = 'N/A'; var sTax1 = 'N/A'; var sDuty = 'N/A'; var sTax2 = 'N/A'; var sTotal = 'N/A';
	var vShipping = 0; var vDuty = theForm['duty'].value*1; var vTax1 = 0; var vTax2 = 0; var vTotal = 0;
	var vDiscount = theForm['discount'].value*1;
	var sShipTypeText = '';
	var shipRadio = validateRadioButton(theForm['shippingType']);
	$('sShippingTypeText').update('');
	if (shipRadio>0) {
		if (shipRadio==99) {// one radio button
			vShipping = theForm['shippingType'].getAttribute('shipPrice')*1;
			sShipTypeText = theForm['shippingType'].getAttribute('shipType');
		} else {
			shipRadio--;
			sShipTypeText = theForm['shippingType'][shipRadio].getAttribute('shipType');
			vShipping = theForm['shippingType'][shipRadio].getAttribute('shipPrice')*1;
		}
		if (vShipping===0)
			sShipping = (gE('freeTextWord')) ? gE('freeTextWord').innerHTML : 'FREE';
		else
			sShipping = CURRENCY_SYMB + vShipping;
	}
	if (vShipping>=0) {
		vTotal = subTotal - vDiscount + vShipping + vDuty;
		if (theForm['tax1prcnt']) {
			if ((theForm['tax1prcnt'].value*1)>0) {
				vTax1 = vTotal * (theForm['tax1prcnt'].value*1) / 100;
				vTax1 = number_format(vTax1, 2, '.', '');
				sTax1 = CURRENCY_SYMB + vTax1;
				if (theForm['tax2prcnt']) {
					if ((theForm['tax2prcnt'].value*1)) {
						if (theForm['taxado'].value*1) {
							vTax2 = (vTotal + vTax1*1) * (theForm['tax2prcnt'].value*1) / 100;
						} else {
							vTax2 = vTotal * (theForm['tax2prcnt'].value*1) / 100;
						}
						vTax2 = number_format(vTax2, 2, '.', ''); //Summit.Form.MakeCurrency(vTax2)*1;
						sTax2 = CURRENCY_SYMB + vTax2;
					}
				}
			}
		}
		vTotal += vTax1*1; vTotal += vTax2*1;
		vTotal = Summit.Form.MakeCurrency(vTotal);
		sTotal = CURRENCY_SYMB + vTotal;
		theForm['shipping'].value = vShipping;
		if (theForm['tax1']) theForm['tax1'].value = vTax1;
		if (theForm['tax2']) theForm['tax2'].value = vTax2;
		theForm['total'].value = vTotal;
	}
	if ($('sShippingTypeText')) {
		if (sShipTypeText)
			sShipTypeText = '(' + sShipTypeText + ')';
		$('sShippingTypeText').update(sShipTypeText);
	}
	if ($('sShipping')) $('sShipping').update(sShipping);
	if ($('sTax1')) $('sTax1').update(sTax1);
	if ($('sTax2')) $('sTax2').update(sTax2);
	if ($('sTotal')) $('sTotal').update(sTotal);
}

function validatePlaceOrder(theForm) {
	var res = false;
	var proceed = true;
	if (validateRadioButton(theForm['shippingType'])>0) {
		if (theForm['oldPromoCode'] && theForm['promoCode']) {
			if (theForm['oldPromoCode'].value!=theForm['promoCode'].value) {
				alert('Promocode has been changed. Please upate your order using update button above.');
				proceed = false;
			}
		}
		if (proceed && Summit.Form.ValidateForm(theForm)) {
			if (theForm['total'].value*1>0) {
				res = confirm('The order will now be placed.\nContinue?');
				if (res && theForm['submitBtn']) {
					theForm['submitBtn'].value = 'please wait ...';
					theForm['submitBtn'].disabled = true;
				}
			}
		}
	} else {
		alert('Please select shipping type.')
	}
	return res;
}

function number_format(number, decimals, dec_point, thousands_sep) {
    // Formats a number with grouped thousands  
    // 
    // version: 1008.1718
    // discuss at: http://phpjs.org/functions/number_format
    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +     bugfix by: Michael White (http://getsprink.com)
    // +     bugfix by: Benjamin Lupton
    // +     bugfix by: Allan Jensen (http://www.winternet.no)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +     bugfix by: Howard Yeend
    // +    revised by: Luke Smith (http://lucassmith.name)
    // +     bugfix by: Diogo Resende
    // +     bugfix by: Rival
    // +      input by: Kheang Hok Chin (http://www.distantia.ca/)
    // +   improved by: davook
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Jay Klehr
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +      input by: Amir Habibi (http://www.residence-mixte.com/)
    // +     bugfix by: Brett Zamir (http://brett-zamir.me)
    // +   improved by: Theriault
    // *     example 1: number_format(1234.56);
    // *     returns 1: '1,235'
    // *     example 2: number_format(1234.56, 2, ',', ' ');
    // *     returns 2: '1 234,56'
    // *     example 3: number_format(1234.5678, 2, '.', '');
    // *     returns 3: '1234.57'
    // *     example 4: number_format(67, 2, ',', '.');
    // *     returns 4: '67,00'
    // *     example 5: number_format(1000);
    // *     returns 5: '1,000'
    // *     example 6: number_format(67.311, 2);
    // *     returns 6: '67.31'
    // *     example 7: number_format(1000.55, 1);
    // *     returns 7: '1,000.6'
    // *     example 8: number_format(67000, 5, ',', '.');
    // *     returns 8: '67.000,00000'
    // *     example 9: number_format(0.9, 0);
    // *     returns 9: '1'
    // *    example 10: number_format('1.20', 2);
    // *    returns 10: '1.20'
    // *    example 11: number_format('1.20', 4);
    // *    returns 11: '1.2000'
    // *    example 12: number_format('1.2000', 3);
    // *    returns 12: '1.200'
    var n = !isFinite(+number) ? 0 : +number, 
        prec = !isFinite(+decimals) ? 0 : Math.abs(decimals),
        sep = (typeof thousands_sep === 'undefined') ? ',' : thousands_sep,
        dec = (typeof dec_point === 'undefined') ? '.' : dec_point,
        s = '',
        toFixedFix = function (n, prec) {
            var k = Math.pow(10, prec);
            return '' + Math.round(n * k) / k;
        };
    // Fix for IE parseFloat(0.55).toFixed(0) = 0;
    s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.');
    if (s[0].length > 3) {
        s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep);
    }
    if ((s[1] || '').length < prec) {
        s[1] = s[1] || '';
        s[1] += new Array(prec - s[1].length + 1).join('0');
    }
    return s.join(dec);
}
