/*checkout_steps = ['Shopping Cart','Delivery', 'Payment', 'Confirmation'];
current_step = 1;
*/

/*
function advanceStep(direction)
{
	if( direction > 0 )
	{
		nextStep = checkout_steps[current_step + direction];
		
		if( !validateStep() ) return; // Do not move to the next step until current step has been completed correctly
		 
		if(nextStep == 'Confirmation')
		{
		}
		else
		{
			oDiv = document.getElementById('payment');
			oDiv.style = display = 'block';
		}
	}
	else
	{
		prevStep = checkout_steps[current_step + direction];
		
		if(prevStep == 'Shopping Cart')
		{
			window.location = cart_url;
		}
		else
		{
			oDiv = document.getElementById('payment');
			oDiv.style = display = 'none';
		}
	}
}*/

function trimStr(str)
{
	var reExtraSpace = /^\s+(.*?)\s+$/; 
	
    return str.replace(reExtraSpace, '$1');
}

function isSpecial(c)
{
	if (c == 13 || c == 9 || c == 8 || c == 46 || c == 48 || c == 96 || c == 0) return true;
	
	return false;
}

function isValidNumAlpha()
{

	var c= event.keyCode;

	event.keyCode=(!((c>=65 && c<=90) 
                      ||(c>=97 && c<=122)
                      || (c==32)|| (c>=48 && c<=57) 
                      ))?0:event.keyCode;

} 


function isNumericInput(oEvent,oEntryField)
{
	if (!oEvent && window.event) oEvent = window.event;
	
	var c = oEvent.charCode != undefined ? oEvent.charCode : oEvent.keyCode;
	var num = '09';
	var code0 = num.charCodeAt(0), code9 = num.charCodeAt(1);

	if( (c < code0 || c > code9) && !isSpecial(c))
	{
		return false;
	}
	return true;
}

function isPhoneInput(oEvent,oEntryField)
{
	if (!oEvent && window.event) oEvent = window.event;
	
	var c = oEvent.charCode != undefined ? oEvent.charCode : oEvent.keyCode;
	var num = '09-+ ()';
	var code0 = num.charCodeAt(0),  code9 = num.charCodeAt(1),
	    codeminus = num.charCodeAt(2), codeplus = num.charCodeAt(3)
	    codespace = num.charCodeAt(4), code_ = num.charCodeAt(5),
		_code = num.charCodeAt(6);
	
	if( (c < code0 || c > code9) && c != codeminus && c != codeplus && c != codespace &&
		!isSpecial(c) && c != code_ && c != _code || (c == codespace && oEntryField.length == 0) )
	{
		return false;
	}
	return true;
}

function isEmailInput(oEvent,oEntryField)
{
	if (!oEvent && window.event) oEvent = window.event;
	
	var c = oEvent.charCode != undefined ? oEvent.charCode : oEvent.keyCode;
	var num = '09azAZ._-@';
	var code0 = num.charCodeAt(0), code9 = num.charCodeAt(1),
	    codea = num.charCodeAt(2), codez = num.charCodeAt(3),
		codeA = num.charCodeAt(4), codeZ = num.charCodeAt(5),
		codedot = num.charCodeAt(6), code_ = num.charCodeAt(7),
		codeminus = num.charCodeAt(8), codeat = num.charCodeAt(9);
	
	if( (c < code0 || c > code9) && (c < codea || c > codez) && 
		(c < codeA || c > codeZ) && c != codedot && c != code_ && 
		c != codeat && c != codeminus && !isSpecial(c))
	{
		return false;
	}
	return true;
}

function acceptInput(oEvent,oEntryField,type)
{
	switch(type)
	{
		case 'numeric':
			return isNumericInput(oEvent,oEntryField);
		break;
		case 'phone':
			return isPhoneInput(oEvent,oEntryField);
		break;
		case 'email':
			return isEmailInput(oEvent,oEntryField);
		break;
		default:
			return false;
	}
}

function isValidEmail(email)
{
	var regEmail = /^((\w+\.)*(\w+-)*)*(\w+)@((\w+\.)*(\w+-)*)*(\w+\.)+(\w+)$/;
	
	return regEmail.test(email);
}

function isValidNumeric(entry)
{
	var regNumber = /^\d+$/;
	
	return regNumber.test(entry);
}

function isValidEntry(entry,type)
{
	switch(type)
	{
		case 'numeric':
			return isValidNumeric(entry);
		break;
		case 'email':
			return isValidEmail(entry);
		break;
		default:
			return false;
		
	}
}

function updateRecipientInfo(cb)
{
	details_fields = ['first_name',
	'last_name',
	'email',
	'phone',
	'address_line1',
	'address_line2',
	'suburb',
	'state',
	'postcode',
	'country'];

	form = document.checkout_form;
	
	if(cb.checked)
	{
		cb.value = "1";
		for(i = 0; i < details_fields.length; i++)
		{
			field = eval('form.recipient_'+ details_fields[i]);
			
			if(details_fields[i] != 'country')
			{
				value = eval('form.'+ details_fields[i] + '.value');
				field.value = value;
			}
			else
			{
				selection = eval('form.'+ details_fields[i] + '.selectedIndex');
				field.selectedIndex = selection;
			}
		}
	}
	else // Clear all the fields so that the recipient's details can be entered
	{
		cb.value = "0";
		for(i = 0; i < details_fields.length; i++)
		{
			field = eval('form.recipient_'+ details_fields[i]);
			
			if(details_fields[i] != 'country')
			{
				value = eval('form.'+ details_fields[i] + '.value');
				// To avoid clearing information the user may have already entered
				if(value ==  field.value) field.value = '';
			}
			else
			{
				selection = eval('form.'+ details_fields[i] + '.selectedIndex');
				// To avoid overriding a selection the user may have already made
				if(selection == field.selectedIndex && field.value != 'Australia')
				{
					j = 0;
					while(field.options[j].value != 'Australia' ){ j++; } 
					field.selectedIndex = j;  // Australia as default country
				}
			}
		}
	}
}

function deliverToChange()
{
	form = document.checkout_form;
	oDiv = document.getElementById('recipient');
	
	if( form.deliver_to.selectedIndex == 2) {
		oDiv.style.display = 'block';
	} else {
		oDiv.style.display = 'none';
	}

	// Deliver to myself 
	if(form.deliver_to.selectedIndex == 1) {
//		form.purchaser_is_recipient.value = "1";
		updateRecipientInfo(form.purchaser_is_recipient);
	} else {
//		form.purchaser_is_recipient.value = "0";
		updateRecipientInfo(form.purchaser_is_recipient);
	}
}

function addMessage(showEntryField)
{
	oDiv = document.getElementById('message_holder');
	if(showEntryField) oDiv.style.display = 'block';
	else oDiv.style.display = 'none';
}

function validateAdminForm()
{
	required_fields = {
	"first_name" : "Your first name is required",
	"last_name" : "Your last name is required",
	"email" : "Your email is required",
	"phone" : "Your phone number is required",
	"address_line1" : "Your address is required",
	"suburb" : "Your Suburb is required",
	"state" : "Your State is required",
	"postcode" : "Your postcode is required",
	"country" : "Please select your Country",
	"postage_method" : "Please select a delivery method",
	"deliver_to" : "Please specify the recipient"
	};
	
	required_recipient_fields = {
		"recipient_first_name" : "The recipient's first name is required",
		"recipient_last_name" : "The recipient's last name is required",
		"recipient_email" : "The recipient's email is required",
		"recipient_phone" : "The recipient's phone number is required",
		"recipient_address_line1" : "The recipient's address is required",
		"recipient_suburb" : "The recipient's Suburb is required",
		"recipient_state" : "The recipient's State is required",
		"recipient_postcode" : "The recipient's postcode is required",
		"recipient_country" : "The recipient's Country is required"
	};
	
	/*
	"card_holder_name" : "The card's holder name is required",
	"card_type" : "Please select the type of card",
	"card_number_field_1" : "Please enter the credit card number",
	"card_number_field_2" : "Please enter the credit card number",
	"card_number_field_3" : "Please enter the credit card number",
	"card_number_field_4" : "Please enter the credit card number",
	"expiry_month" : "The card's expiry month is required",
	"expiry_year" : "The card's expiry year is required",
	"verification_number" : "The card's verification number is required"
	*/	
	required_formats = {
	"email" : ["email","Please enter a valid email"],
	"postcode" : ["numeric","Please enter a valid postcode"]
	};
	/*
	"card_number_field_1" : ["numeric","Please enter a valid credit card number"],
	"card_number_field_2" : ["numeric","Please enter a valid credit card number"],
	"card_number_field_3" : ["numeric","Please enter a valid credit card number"],
	"card_number_field_4" : ["numeric","Please enter a valid credit card number"],
	"expiry_month" : ["numeric","Please enter a valid expiry month for the credit card"],
	"expiry_year" : ["numeric","Please enter a valid expiry year for the credit card"],
	"verification_number" : ["numeric","Please enter a valid verification number for the credit card"]
	*/		

	form = document.checkout_form;
	error_msg = "";

	// Go through all the mandatory fields
	for(name in required_fields)
	{
		field = eval('form.'+name);

		if(name != "country" && name != "recipient_country") field.value = trimStr(field.value);
		if(field.value.length == 0)
		{
			error_msg = required_fields[name]; //+ '\n' );
			field.focus();
			
			break;
		}
		else
		{
			if(typeof required_formats[name] != 'undefined')
			{
				if( !isValidEntry(field.value, required_formats[name][0]) )
				{
					error_msg = required_formats[name][1]
					field.focus();
					break;
				}
			}
		}
	}
	
	if( document.getElementById('recipient').style.display == 'block' ) {
		// let's only check the recipient details
		// if the user has chosen to send it to a recipient
		for(recipient_name in required_recipient_fields) {
			field = eval('form.'+recipient_name);

			if(recipient_name != "country" && recipient_name != "recipient_country") field.value = trimStr(field.value);

			if(field.value.length == 0) {
				error_msg = required_recipient_fields[recipient_name]; //+ '\n' );
				field.focus();
				break;
			} else {
				if(typeof required_formats[recipient_name] != 'undefined') {
					if( !isValidEntry( field.value, required_formats[recipient_name][0] )) {
						error_msg = required_formats[recipient_name][1]
						field.focus();
						break;
					}
				}
			}
		}
	}
	
	if(error_msg == "")
	{
		var creditcard = document.getElementById( 'payment_method_creditcard' );
		if( creditcard.checked == true ) {
			creditcard = 1;
		}

		if( !form.accept.checked )
		{
			alert('You must read and agree to the Terms & and Conditions before proceeding');
			form.accept.focus();
			
			return;
		}
		if( document.getElementById('radioYes').checked && form.personal_message.value.length == 0 )
		{
			alert('Please type the personal message you would like to add to the voucher');
			form.personal_message.focus();
			
			return;
		}
		
		max_vouchers = 100;
		/*
		for(i = 1; i <= 100; i++)
		{
			qty = document.getElementById('voucher_'+i);
			
			if(typeof qty != 'undefined' && qty)
			{
				qty_val = parseInt(qty.value);
					
				if(  !isNaN(qty_val) &&  qty_val > 0 )
				{
					// Entry is valid
				}
				else
				{
					alert('Please enter a valid number of vouchers');
					qty.focus();
					return false;
				}
			}
			else break; // There are no more vouchers in the cart so break from the loop
		}
		*/
	
		delivery_method = form.postage_method.value;
		/*
		if( (form.recipient_country.value == 'Australia' && (delivery_method != "Post Within Australia (Standard)" &&
														     delivery_method != "Post Within Australia (Express)" &&
														     delivery_method != "Email/Online")) ||
		    (form.recipient_country.value != 'Australia' && (delivery_method == "Post Within Australia (Standard)" ||
														     delivery_method == "Post Within Australia (Express)"))
		  )
		{
			alert(delivery_method+' is not a valid delivery method for '+form.recipient_country.value+'. Please select an appropiate delivery method.');
			return;
		}
		*/
		if( creditcard == 1 ) {
			card_holder_name 		= form.card_holder_name;
			card_type						= form.card_type;
			card_number_field_1	= form.card_number_field_1;
			card_number_field_2	= form.card_number_field_2;
			card_number_field_3	= form.card_number_field_3;
			card_number_field_4	= form.card_number_field_4;
			verification_number = form.verification_number;

			if( card_holder_name.value.length == 0 ) {
				alert('The card\'s holder name is required');
				card_holder_name.focus();
				return false;
			}
			if( card_type.value.length == 0 ) {
				alert('Please select the type of card');
				card_type.focus();
				return false;
			}
			if( card_number_field_1.value.length == 0 ) {
				alert('Please enter the credit card number');
				card_number_field_1.focus();
				return false;
			}
			if( card_number_field_2.value.length == 0 ) {
				alert('Please enter the credit card number');
				card_number_field_2.focus();
				return false;
			}
			if( card_number_field_3.value.length == 0 ) {
				alert('Please enter the credit card number');
				card_number_field_3.focus();
				return false;
			}
			if( card_number_field_4.value.length == 0 ) {
				alert('Please enter the credit card number');
				card_number_field_4.focus();
				return false;
			}

			expiry_year_test = form.expiry_year.value;
			expiry_month_test = form.expiry_month.value;

			if(expiry_month_test > 12 || expiry_month_test.length == 0)
			{
				alert('Please enter a valid expiry month');
				form.expiry_month.focus();
				return false;
				
			}
			if(expiry_year_test < 8 || expiry_year_test.length == 0)
			{
				alert('Please enter a valid expiry year');
				form.expiry_year.focus();
				return false;
			}
			if( verification_number.value.length == 0 ) {
				alert('The card\'s verification number is required');
				verification_number.focus();
				return false;
			}			
		}

		form.submit();	
	}
	else
	{
		alert('Information incomplete:\n'+error_msg);
		
		return;
	}
}

function validateForm()
{
	required_fields = {
		"first_name" : "Your first name is required",
		"last_name" : "Your last name is required",
		"email" : "Your email is required",
		"phone" : "Your phone number is required",
		"address_line1" : "Your address is required",
		"suburb" : "Your Suburb is required",
		"state" : "Your State is required",
		"postcode" : "Your postcode is required",
		"country" : "Please select your Country",
		"postage_method" : "Please select a delivery method",
		"deliver_to" : "Please specify the recipient",
		"card_holder_name" : "The card's holder name is required",
		"card_type" : "Please select the type of card",
		"card_number_field_1" : "Please enter the credit card number",
		"card_number_field_2" : "Please enter the credit card number",
		"card_number_field_3" : "Please enter the credit card number",
		"card_number_field_4" : "Please enter the credit card number",
		"expiry_month" : "The card's expiry month is required",
		"expiry_year" : "The card's expiry year is required",
		"verification_number" : "The card's verification number is required"
	};

	required_recipient_fields = {
		"recipient_first_name" : "The recipient's first name is required",
		"recipient_last_name" : "The recipient's last name is required",
		"recipient_email" : "The recipient's email is required",
		"recipient_phone" : "The recipient's phone number is required",
		"recipient_address_line1" : "The recipient's address is required",
		"recipient_suburb" : "The recipient's Suburb is required",
		"recipient_state" : "The recipient's State is required",
		"recipient_postcode" : "The recipient's postcode is required",
		"recipient_country" : "The recipient's Country is required"
	};

	required_formats = {
		"email" : ["email","Please enter a valid email"],
		"postcode" : ["numeric","Please enter a valid postcode"],
		"recipient_email" : ["email","Please enter a valid email for the recipient"],
		"recipient_postcode" : ["numeric","Please enter a valid postcode for the recipient"],
		"card_number_field_1" : ["numeric","Please enter a valid credit card number"],
		"card_number_field_2" : ["numeric","Please enter a valid credit card number"],
		"card_number_field_3" : ["numeric","Please enter a valid credit card number"],
		"card_number_field_4" : ["numeric","Please enter a valid credit card number"],
		"expiry_month" : ["numeric","Please enter a valid expiry month for the credit card"],
		"expiry_year" : ["numeric","Please enter a valid expiry year for the credit card"],
		"verification_number" : ["numeric","Please enter a valid verification number for the credit card"]
	};

	form = document.checkout_form;
	error_msg = "";

	// Go through all the mandatory fields
	for(name in required_fields)
	{
		field = eval('form.'+name);

		if(name != "country" && name != "recipient_country") field.value = trimStr(field.value);
		if(field.value.length == 0)
		{
			error_msg = required_fields[name]; //+ '\n' );
			field.focus();
			
			break;
		}
		else
		{
			if(typeof required_formats[name] != 'undefined')
			{
				if( !isValidEntry(field.value, required_formats[name][0]) )
				{
					error_msg = required_formats[name][1]
					field.focus();
					break;
				}
			}
		}
	}

	if( document.getElementById('recipient').style.display == 'block' ) {
		// let's only check the recipient details
		// if the user has chosen to send it to a recipient
		for(recipient_name in required_recipient_fields) {
			field = eval('form.'+recipient_name);

			if(recipient_name != "country" && recipient_name != "recipient_country") field.value = trimStr(field.value);

			if(field.value.length == 0) {
				error_msg = required_recipient_fields[recipient_name]; //+ '\n' );
				field.focus();
				break;
			} else {
				if(typeof required_formats[recipient_name] != 'undefined') {
					if( !isValidEntry( field.value, required_formats[recipient_name][0] )) {
						error_msg = required_formats[recipient_name][1]
						field.focus();
						break;
					}
				}
			}
		}
	}

	if(error_msg == "")
	{
		if( !form.accept.checked )
		{
			alert('You must read and agree to the Terms & and Conditions before proceeding');
			form.accept.focus();
			
			return;
		}
		if( document.getElementById('radioYes').checked && form.personal_message.value.length == 0 )
		{
			alert('Please type the personal message you would like to add to the voucher');
			form.personal_message.focus();
			
			return;
		}
		
		max_vouchers = 100;
		
		for(i = 1; i <= 100; i++)
		{
			qty = document.getElementById('voucher_'+i);
			
			if(typeof qty != 'undefined' && qty)
			{
				qty_val = parseInt(qty.value);
					
				if(  !isNaN(qty_val) &&  qty_val > 0 )
				{
					// Entry is valid
				}
				else
				{
					alert('Please enter a valid number of vouchers');
					qty.focus();
					return false;
				}
			}
			else break; // There are no more vouchers in the cart so break from the loop
		}
		
		delivery_method = form.postage_method.value;
		
		if( (form.recipient_country.value == 'Australia' && (delivery_method != "Post Within Australia (Standard)" &&
														     delivery_method != "Post Within Australia (Express)" &&
														     delivery_method != "Email/Online")) ||
		    (form.recipient_country.value != 'Australia' && (delivery_method == "Post Within Australia (Standard)" ||
														     delivery_method == "Post Within Australia (Express)"))
		  )
		{
			alert(delivery_method+' is not a valid delivery method for '+form.recipient_country.value+'. Please select an appropiate delivery method.');
			return;
		}
		
		
		expiry_year_test = form.expiry_year.value;
		expiry_month_test = form.expiry_month.value;

		if(expiry_month_test > 12)
		{
			alert('Please enter a valid expiry month');
			expiry_month_test.focus();
			return false;
			
		}
		if(expiry_year_test < 8)
		{
			alert('Please enter a valid expiry year');
			expiry_year_test.focus();
			return false;
			
		}

		form.submit();	
	}
	else
	{
		alert('Information incomplete:\n'+error_msg);
		
		return;
	}
}