/* ***********************************
* Envoy v4.0 Checkout Functions
* (c)2005 Embryonex Multimedia Ltd
* 15th May 2005 (AM)
* *********************************** */

// postage
var pp_vars = {
	id:			 0,
	name:		 1,
	group:		 2,
	discount:	 3,
	type:		 4,
	order:		 5,
	del_dates:	 6,
	cutoff_time: 7
}

// postage rules
var pp_rules_enum = {
	id:					0,
	rule_id:			1,
	val1:				2,
	from:				3,
	to:					4,
	price:				5,
	incl_discount:		6,
	tax:				7,
	discount_id:		8,
	recursive:			9,
	recursive_limit:	10,
	recursive_price:	11
}

var offer_enum = {
	id:			0,
	name:		1,
	val1:		2,
	val2:		3,
	val3:		4,
	display_id:	5,
	group_id:	6,
	amount:		7,
	desc:		8,
	type_id:	9
}


// address
var addr_vals = {
	_null:		0,
	id:			1,
	acc_id:		2,
	name:		3,
	title:		4,
	fname:		5,
	lname:		6,
	addr1:		7,
	addr2:		8,
	town:		9,
	county:		10,
	state:		11,
	postcode:	12,
	country:	13,
	telephone:	14,
	fax:		15,
	mobile:		16,
	email:		17
}

// card subscripts - NB: generator code misses out site_id and order columns
var cc_vars = {
	id:				0,
	value:			1,
	name:			2,
	num_length:		3,
	first_char:		4,
	req_issue_no:	5,
	req_sec_code:	6
}

var acc_cc = {
	subs:				0,
	id:					1,
	obs_num:			2,
	card_type:			3,
	card_name:			4,
	card_start_month:	5,
	card_start_year:	6,
	card_expiry_month:	7,
	card_expiry_year:	8,
	issue_number:		9,
	security_code:		10
}

// Checkout object
function checkout(frm_id) {

	this.frm_id = frm_id;
	this.frm = '';
	this.cc_sel = ''
	this.checkout_type = '';
	this.bill_fields = new Array('sc_fname', 'sc_lname', 'sc_address1','sc_town','sc_postcode','sc_telephone','sc_email');
	this.bill_descs = new Array('first name', 'last name', 'first address line', 'town', 'post code', 'telephone number', 'email address');
	this.del_fields = new Array('sc_delfname', 'sc_dellname', 'sc_deladdress1','sc_deltown','sc_delpostcode');
	this.cc_fields = new Array('pay_card_name', 'pay_card_number', 'pay_card_expiry_month', 'pay_card_expiry_year');
	this.cc_descs = new Array('billing name', 'number', 'expiry month', 'expiry year');

	// ************************************************************* COMMON functions

	this.check_form = function()
	{
		if(this.check_text_input())
		{
			return this.check_cc();
		}
		else
			return false;
	}

	// checks the text input - address and name values
	this.check_text_input = function()
	{
		var i;
		for(i = 0; i < this.bill_fields.length; i++)
		{
			if(trim(this.frm[this.bill_fields[i]].value) == '')
				return showError(this.frm[this.bill_fields[i]], ('Your ' + this.bill_descs[i] + ' is missing'));
		}

		if (trim(this.frm.sc_email.value) != trim(this.frm.sc_email_confirm.value))		{
			return showError(this.frm.sc_email_confirm, 'Your email addresses do not match');
		}

		// check country
		if(this.frm.sc_country.options[this.frm.sc_country.selectedIndex].value == 'x')
			return showError(this.frm.sc_country, 'Please select a country');

		// if delivery address is selected check the values
		if(this.frm.del_chk.checked)
		{
			for(i = 0; i < this.del_fields.length; i++)
			{
				if(trim(this.frm[this.del_fields[i]].value) == '')
					return showError(this.frm[this.del_fields[i]], ('The ' + this.bill_descs[i] + ' on your delivery address is missing'));
			}
			// check country
			if(this.frm.sc_delcountry.options[this.frm.sc_delcountry.selectedIndex].value == 'x')
				return showError(this.frm.sc_delcountry, 'Please select a delivery country');
		}

		// specific check for a valid email address format
		if(!isEmailFormatCorrect(this.frm.sc_email.value))
			return showError(this.frm.sc_email, 'The email address you have entered is not in a valid format');

		if(this.frm.post_option_sel.options[this.frm.post_option_sel.selectedIndex].value == -1)  {
			return showError(this.frm.post_option_sel, 'Please select a delivery method');
		}
		
		return true;

	};

	// check the credit card input
	this.check_cc = function()	{
		if(this.frm.pay_cc_card.options[this.frm.pay_cc_card.selectedIndex].value == -1) {
			return showError(this.frm.pay_cc_card, 'Please select a payment method');
		}

		var card_id = this.get_selected_card_id();

		for(var i = 0; i < this.cc_fields.length; i++)	{
			if(trim(this.frm[this.cc_fields[i]].value) == '') {
				return showError(this.frm[this.cc_fields[i]], ('Please enter your card\'s ' + this.cc_descs[i]));
			}
		}
		
		if(card_id > -1)	{
			var card_name = this.get_selected_card_name();
			var card_no = this.frm.pay_card_number.value;
			
			//alert(card_name);
			if (!checkCreditCard(card_no, card_name))	{
				return showError(this.frm.pay_card_number, ccErrors[ccErrorNo]);
			}
			
			if(card_id == 2)	{
				if( ((removeSpaces(this.frm.pay_card_number.value).length == 18) || (removeSpaces(this.frm.pay_card_number.value).length == 19)) && (trim(this.frm.pay_card_issue_number.value) == ''))
					return showError(this.frm.pay_card_issue_number, 'Please enter an issue number');
			}
	
			if((ccs[card_id][cc_vars.req_sec_code] == 'y') && (trim(this.frm.pay_card_security_code.value) == ''))  {
				return showError(this.frm.pay_card_security_code, 'Please enter your card\'s security code');
			}

			var cardsec = /^([0-9]{3,4})$/;
			if (!cardsec.exec(trim(this.frm.pay_card_security_code.value)))  {
				return showError(this.frm.pay_card_security_code, 'Please enter a valid security code');
			}
		
			return checkDates(this.frm.pay_card_start_month, this.frm.pay_card_start_year, this.frm.pay_card_expiry_month, this.frm.pay_card_expiry_year, card_id, removeSpaces(this.frm.pay_card_number.value).length);
		}
		else	{
			return showError(this.frm.pay_cc_card, 'Please select a payment method');
		}
		return true;
	};


	// removes spaces from a credit card number
	function removeSpaces(s)	{
		var new_s = '';
		for(var i = 0; i < s.length; i++)	{
			if(s.charAt(i) != ' ')
				new_s += s.charAt(i);
		}
		return new_s;
	}


	// get the subscript in the ccs array of the selected card type
	// needed because the <select>'s value is the card's text value not it's id.
	this.get_selected_card_id = function()	{	
		var selected_cc = this.frm.pay_cc_card.options[this.frm.pay_cc_card.selectedIndex].value;

		for(var i = 0; i < ccs.length; i++) {
			if(ccs[i][cc_vars.value] == selected_cc)
				return i;
		}
		return -1;
	}

	// get the subscript in the ccs array of the selected card type
	// needed because the <select>'s value is the card's text value not it's id.
	this.get_selected_card_name = function()  {	
		var selected_cc = this.frm.pay_cc_card.options[this.frm.pay_cc_card.selectedIndex].value;

		for(var i = 0; i < ccs.length; i++)	 {
			if(ccs[i][cc_vars.value] == selected_cc) {
				return ccs[i][cc_vars.name];
			}
		}
		return -1;
	}

	// ************************************************************* Retail Customer Functions
	
	// initialise the ratil customer's form
	this.init_retail_form = function()
	{
		this.checkout_type = 'retail';
		this.frm = document.getElementById(this.frm_id);
		this.populate_cards();
		this.pp_init();
	};

	// populate the credit card <select>
	this.populate_cards = function()
	{
		this.cc_sel = document.getElementById('pay-cc-card');
		for(var i = 0; i < ccs.length; i++)
			this.cc_sel.options[this.cc_sel.options.length] = new Option(ccs[i][cc_vars.name], ccs[i][cc_vars.value], false, false);
	};


	// ************************************************************** Account Holder Functions

	// initialise the account holder's checkout
	this.init_account_holder_form = function()
	{
		this.checkout_type = 'account';
		this.frm = document.getElementById(this.frm_id);
		this.populate_cards();
		this.populate_payment_methods();
		this.populate_addresses();
		//this.pp_calc(false);
	};


	// populate the account holder's list of credit cards using the pays[] array
	this.populate_payment_methods = function()
	{
		var p = document.getElementById('pay-sel-cc-card');
		for(var i = 0; i < pays.length; i++)
			p.options[p.options.length] = new Option(pays[i][acc_cc.obs_num], pays[i][acc_cc.subs], false, false);
	};

	// when user selects the card - hidden fields must be completed
	this.acc_populate_card = function()
	{
		var cc = this.frm.pay_sel_cc_card.options[this.frm.pay_sel_cc_card.selectedIndex].value;
		if(cc > -1)
		{
			this.frm.pay_cc_card.value				= pays[cc][acc_cc.card_type];
			this.frm.pay_card_id.value				= pays[cc][acc_cc.id];
			this.frm.pay_card_name.value			= pays[cc][acc_cc.card_name];
			this.frm.pay_card_number.value			= pays[cc][acc_cc.obs_num];
			this.frm.pay_card_start_month.value		= pays[cc][acc_cc.card_start_month];
			this.frm.pay_card_start_year.value		= pays[cc][acc_cc.card_start_year];
			this.frm.pay_card_expiry_month.value	= pays[cc][acc_cc.card_expiry_month];
			this.frm.pay_card_expiry_year.value		= pays[cc][acc_cc.card_expiry_year];
			this.frm.pay_card_issue_number.value	= pays[cc][acc_cc.issue_number];
			this.frm.pay_card_security_code.value	= pays[cc][acc_cc.security_code];
		}
		else if(cc == -2)
		{
			this.frm.pay_cc_card.selectedIndex		= 0;
			this.frm.pay_card_id.value				= '';
			this.frm.pay_card_name.value			= '';
			this.frm.pay_card_number.value			= '';
			this.frm.pay_card_start_month.value		= '';
			this.frm.pay_card_start_year.value		= '';
			this.frm.pay_card_expiry_month.value	= '';
			this.frm.pay_card_expiry_year.value		= '';
			this.frm.pay_card_issue_number.value	= '';
			this.frm.pay_card_security_code.value	= '';
		}

	};

	// populate the account holder's addresses drop down with a list of address names using the addr[] array
	this.populate_addresses = function()
	{
		var i;
		for(i = 0; i < addr.length; i++)
		{
			this.frm.addr_sel.options[this.frm.addr_sel.options.length] = new Option(addr[i][3], i, false, false);
			this.frm.addr_del.options[this.frm.addr_del.options.length] = new Option(addr[i][3], i, false, false);
		}
	};

	// populate the account holder's address fields after they have selected an address from the <select>
	// the value of each option in the select corresponds to a row in the addr array
	this.get_account_address = function(obj)
	{
		var pfx = '';
		var i = obj.value;
		if(obj.name == 'addr_del')
			pfx = 'del';
		if(i > -1)
		{
			this.frm['sc_' + pfx + 'title'].value = addr[i][addr_vals.title];
			this.frm['sc_' + pfx + 'fname'].value = addr[i][addr_vals.fname];
			this.frm['sc_' + pfx + 'lname'].value = addr[i][addr_vals.lname];
			this.frm['sc_' + pfx + 'address1'].value = addr[i][addr_vals.addr1];
			this.frm['sc_' + pfx + 'address2'].value = addr[i][addr_vals.addr2];
			this.frm['sc_' + pfx + 'town'].value = addr[i][addr_vals.town];
			this.frm['sc_' + pfx + 'county'].value = addr[i][addr_vals.county];
			this.frm['sc_' + pfx + 'state'].value = addr[i][addr_vals.state];
			this.frm['sc_' + pfx + 'postcode'].value = addr[i][addr_vals.postcode];
			this.frm['sc_' + pfx + 'country'].value = addr[i][addr_vals.country];
			this.frm['sc_' + pfx + 'telephone'].value = addr[i][addr_vals.telephone];
			this.frm['sc_' + pfx + 'fax'].value = addr[i][addr_vals.fax];
			this.frm['sc_' + pfx + 'mobile'].value = addr[i][addr_vals.mobile];
			this.frm['sc_' + pfx + 'email'].value = addr[i][addr_vals.email];
		}
		else
		{
			this.frm['sc_' + pfx + 'title'].value = '';
			this.frm['sc_' + pfx + 'fname'].value = '';
			this.frm['sc_' + pfx + 'lname'].value = '';
			this.frm['sc_' + pfx + 'address1'].value = '';
			this.frm['sc_' + pfx + 'address2'].value = '';
			this.frm['sc_' + pfx + 'town'].value = '';
			this.frm['sc_' + pfx + 'county'].value = '';
			this.frm['sc_' + pfx + 'state'].value = '';
			this.frm['sc_' + pfx + 'postcode'].value = '';
			this.frm['sc_' + pfx + 'country'].value = 'UK Mainland';
			this.frm['sc_' + pfx + 'telephone'].value = '';
			this.frm['sc_' + pfx + 'fax'].value = '';
			this.frm['sc_' + pfx + 'mobile'].value = '';
			this.frm['sc_' + pfx + 'email'].value = '';
		}
	};

	// Postage Functions *************************************************************************

		// check which country has been selected and display a message if delivery is outside the UK or 
		// a null value is selected (indicated by x
		this.pp_init = function()
		{
			var deladdress = document.getElementById('del-chk');
			var country_grp;
			var bill_country = document.getElementById('sc-country').value;
			var delivery_country = document.getElementById('sc-delcountry').value;
			var country;

			if(bill_country == 'x')
			{
				alert('Please select a billing country');
				return false;
			}

			if((delivery_country == 'x') && (deladdress.value == 'y'))
			{
				alert('Please select a delivery country');
				return false;
			}

			if(deladdress.value == 'y')
				country = delivery_country;
			else
				country = bill_country;
			
			country_grp = this.get_ctry_group(country);
			this.populate_pp(country_grp);
			
		};
		
		this.pp_calc = function() 
		{
			var sTmp;
			var sMultiplier;
			var iRuleID = document.getElementById('post-option-sel');
			var post_element = document.getElementById('postage-total-cell-amt');
			var order_total = document.getElementById('order-total-amt-cell');
			var pp_amt = 0;
			var pp_discount_id;

			pp_discount_id = this.get_discount(iRuleID.value);

			if (iRuleID.value != -1)	{
				for (var i = 0;i < pp_rules.length;i++)
				{
					if (pp_rules[i][pp_rules_enum.rule_id] == iRuleID.value)	{
						if (pp_value >= pp_rules[i][pp_rules_enum.from] && pp_value <= pp_rules[i][pp_rules_enum.to])	{
							pp_amt = pp_rules[i][pp_rules_enum.price];
							
							if (pp_rules[i][pp_rules_enum.recursive] > 0)	{
								pp_recursion = basket_items / pp_rules[i][pp_rules_enum.recursive]
								pp_recursion = Math.ceil(pp_recursion);

								if (pp_recursion > pp_rules[i][pp_rules_enum.recursive_limit])	{
									pp_recursion = pp_rules[i][pp_rules_enum.recursive_limit]
								}

								pp_amt += pp_recursion * pp_rules[i][pp_rules_enum.recursive_price]
							}

							pp_amt = this.pp_discount(basket_total, pp_amt, i, pp_discount_id);
							
							if (pp_amt < 0) 	{
								pp_amt = 0;
							}
							
							if (pp_extra_charge > 0)
								pp_amt += pp_extra_charge;

							pp_amt = Number(pp_amt).toFixed(2);

							pp_total = pp_amt;
							post_element.innerHTML = '&pound;' + pp_total;

							order_total.innerHTML = '&pound;' + Number(Number(basket_total) + Number(pp_total)).toFixed(2);
						}
					}
				}
			}
			else {
				order_total.innerHTML = '&pound;' + Number(basket_total).toFixed(2);
				post_element.innerHTML = 'Please Select';
			}
			return false;
		};

		this.pp_discount = function(bask_amt, amt, pp_rule_id, pp_discount_id)
		{	
			var sTmp;
			var iOfferID = pp_rules[pp_rule_id][pp_rules_enum.discount_id];
			var pp_the_discount_id = 0;

			for (var i = 0;i < offers.length;i++)
			{
				if (pp_discount_id > -1)	{
					pp_the_discount_id = pp_discount_id;
				}
				
				if (pp_the_discount_id == 0 )	{
					if (iOfferID > 0)	{
						pp_the_discount_id = iOfferID;
					}
				}
				//alert(pp_the_discount_id);
				if (offers[i][offer_enum.group_id] == 3 && offers[i][offer_enum.id] == pp_the_discount_id)	{
					if (bask_amt >= offers[i][offer_enum.val1] && bask_amt <= offers[i][offer_enum.val2])		{
						switch (offers[i][offer_enum.type_id])	{
							case 1: sTmp = offers[i][offer_enum.val3];
									break;
							case 2: sTmp = amt / offers[i][offer_enum.val3];
									break;
							case 3: sTmp = amt - offers[i][offer_enum.val3];
									break;
							// case 4 is not required in postage rules
						}
						return sTmp;
					}
				}
			}
			return amt;
		};
			
		this.get_ctry_group = function(sMatch)
		{
			var sTmp;
			var sMultiplier;
			sTmp = sMatch.split(',');
			for (var i = 0;i < pp.length;i++)
			{
				if (pp[i][pp_vars.group] == sTmp[1])	{
					return (pp[i][pp_vars.group]);
				}
			}
			return -1;
		};

		this.get_discount = function(iPostID)
		{
			var sTmp;
			for (var i = 0;i < pp.length;i++)
			{
				if (pp[i][pp_vars.id] == iPostID)  {
					return (pp[i][pp_vars.discount]);
				}
			}
			return -1;
		};

		this.populate_pp = function(iGroupID)
		{
			var sTmp;
			var now = new Date(order_time);
			var hour = now.getHours();
			var minute = now.getMinutes();		
			var post_element = document.getElementById('postage-total-cell-amt')
			var order_total = document.getElementById('order-total-amt-cell');

			post_element.innerHTML = 'Please Select';
			order_total.innerHTML = '&pound;' + Number(basket_total).toFixed(2);
			pp_total = 0;

			this.post_sel = document.getElementById('post-option-sel');
			this.post_sel.options.length = 0;
			this.post_sel.options[this.post_sel.options.length] = new Option('-- Please Select --', -1, false, false);
						
			this.post_sel = document.getElementById('post-option-sel');

			for(var i = 0; i < pp.length; i++)   {
				if (iGroupID == pp[i][pp_vars.group])	{
					if (pp[i][pp_vars.cutoff_time] != '')		{
						sTmp = pp[i][pp_vars.cutoff_time].split(':');
						if (hour <= sTmp[0])   {
							if (minute < sTmp[1])	{
								this.post_sel.options[this.post_sel.options.length] = new Option(pp[i][pp_vars.name], pp[i][pp_vars.id], false, false);
							}
						}
					}
					else {
						this.post_sel.options[this.post_sel.options.length] = new Option(pp[i][pp_vars.name], pp[i][pp_vars.id], false, false);
					}	
					
				}
			}
		};

		this.apply_discounts = function(iDiscountCode)
		{
			var sTmp;
			var sDiscount;
			var ord_total = document.getElementById('bask-grand-total');
			var discount_total = document.getElementById('discount-amt-cell');
			for (var i = 0;i < analysis_codes.length;i++)
			{
				if (analysis_codes[i][2] == iDiscountCode)
				{
					if (analysis_codes[i][7] == 1)	{
					
						//alert(analysis_codes[i][6]);
						sDiscount = Number((analysis_codes[i][6] / 100) * Number(this.frm['frm-PreDiscountTotal'].value)).toFixed(2);
						//alert(sDiscount);
						this.frm['frm-DiscountAmount'].value = sDiscount;
						this.frm['frm-AfterDiscountTotal'].value = Number((this.frm['frm-PreDiscountTotal'].value - sDiscount) + Number(this.frm['frmPPVal'].value)).toFixed(2);
						discount_total.innerHTML = '&pound;' + Number(sDiscount).toFixed(2) + ' &nbsp;';
						ord_total.innerHTML = '&pound;' + this.frm['frm-AfterDiscountTotal'].value + ' &nbsp;';
					} 
					else if (analysis_codes[i][7] == 2)
					{
						sDiscount = Number(analysis_codes[i][6]).toFixed(2);
						this.frm['frm-DiscountAmount'].value = sDiscount;
						discount_total.innerHTML = '&pound;' + Number(sDiscount).toFixed(2) + ' &nbsp;';
						this.frm['frm-AfterDiscountTotal'].value = Number((this.frm['frm-PreDiscountTotal'].value - sDiscount) + Number(this.frm['frmPPVal'].value)).toFixed(2);
						ord_total.innerHTML = '&pound;' + this.frm['frm-AfterDiscountTotal'].value + ' &nbsp;';
					}
					else
					{
						this.frm['frm-DiscountAmount'].value = '0';
						discount_total.innerHTML = '&pound;0.00 &nbsp;';
						this.frm['frm-AfterDiscountTotal'].value = Number(Number(this.frm['frm-PreDiscountTotal'].value) + Number(this.frm['frmPPVal'].value)).toFixed(2);
						ord_total.innerHTML = '&pound;' + this.frm['frm-AfterDiscountTotal'].value + ' &nbsp;';
					}
				}
			}

			if (sDiscount > 0)	{
				document.getElementById('discount-row').style.display = '';
			}
			else {
				document.getElementById('discount-row').style.display = 'none';
			}
			return true;
		};
}

// check dates -------------------
function checkDates(startM, startY, endM, endYear, iCardID, iCardLength)
{
	var d = new Date();
	var v1;
	var v2;

	// start month and year
	v1 = startM;
	v2 = startY;
	
	//alert(iCardID);
	//alert(iCardLength);

	var cardname = chkout.get_selected_card_name();

// 	if( ((cardname != 'Switch') && (iCardLength != 18)) || ((cardname == 'Switch') && (iCardLength == 16)) ) {
		
	//if( cardname == 'Maestro' )
	//{
	//	if((v1.value < 1) || (v1.value > 12))
	//		return showError(v1, 'The credit card start month has not been selected!');
	//	if((v2.value == ''))
	//		return showError(v2, 'The credit card start year has not been selected!');
	//	if(v2.value > d.getFullYear())
	//		return showError(v2, 'Your credit card start year is in the future!');
	//	if((v2.value == d.getFullYear()) && (v1.value > (d.getMonth() + 1)))
	//		return showError(v1, 'Your credit card start month is in the future!');
	//}

	// expiry month and year
	v1 = endM;
	v2 = endYear;

	if((v1.value < 1) || (v1.value > 12))
		return showError(v1, 'The credit card expiry month has not been selected!');
	if((v2.value == ''))
		return showError(v2, 'The credit card expiry year has not been selected!');
	if(v2.value < d.getFullYear())
		return showError(v2, 'Your credit card expiry year indicates that your card has expired!');
	if((v2.value == d.getFullYear()) && (v1.value < (d.getMonth() + 1)))
		return showError(v1, 'Your credit card expiry month indicates that your card has expired!');

	document.getElementById('frmTotalValue').value = Number(Number(basket_total) + Number(pp_total)).toFixed(2);
	document.getElementById('frmPPValue').value = Number(pp_total).toFixed(2);

}


function submitProdForm(formid)
{
	var formId = 'cr-product-form' + formid;
	document.getElementById(formId).submit();
	return false;
}

