var xmlObj;
var check_id;

var show_valuation = 0;
var show_vin = 0;
var show_upgrade = 0;

var text_confirmation_selected = 0;
var mileage_check_selected = 0;
var cost = 0.00;
var basic_cost = 0.00;
var mileage_check_cost = 0.00;
var text_confirmation_cost = 0.00;

var elems;

function xml_setup(){

	xmlObj = null;

	if (window.XMLHttpRequest)
	{
		xmlObj = new XMLHttpRequest();
	}
	else if (window.ActiveXObject)
	{
        try
		{
			xmlObj = new ActiveXObject("Msxml2.XMLHTTP");
		}
		catch(e)
		{
			try
			{
				xmlObj = new ActiveXObject("Microsoft.XMLHTTP");
			}
			catch(e) {}
		}
	}
}

function swap_valuation(id)
{
	for (var i=0; i< ids.length; i++)
	{
		document.getElementById('valuation_' + ids[i]).style.display = "none";
	}

	document.getElementById('valuation_' + id).style.display = "block";
}

function store_valuation()
{
	var id = document.forms.valuation.valuation_store_id.value;

	if (id == 0)
	{
		return false;
	}

	document.getElementById('valuation_spinning').style.display = 'inline';

	swap_valuation(id);

	xml_setup();
	xmlObj.onreadystatechange = store_valuation_process;
	xmlObj.open('GET', base_url + '?act=store_valuation_selection&check_id=' + check_id + '&id=' + id + '&retrieve_auth=' + retrieve_auth);
	xmlObj.send(null);
}

function store_valuation_process(){

	if (xmlObj.readyState == 4)
	{
		if (xmlObj.status == 200)
		{
			document.getElementById("valuation_spinning").style.display = 'none';

			var result = 0;

			try {
				result = parseInt(xmlObj.responseXML.getElementsByTagName("result")[0].firstChild.nodeValue);
			}
			catch (e) {}

			if (result < 0)
			{
				document.getElementById("valuation_errors").style.display = 'block';
				document.getElementById("valuation_errors").innerHTML = "Sorry, we were unable to store your valuation selection at this time. Please try again later.";
				return false;
			}
			else
			{
				document.getElementById('valuation_select_submit').disabled = true;

				if (document.getElementById('valuation_prompt'))
				{
					document.getElementById('valuation_prompt').innerHTML = 'Your selection has been saved and your valuation is displayed below.';
					show_valuation = 0;
					Effect.Fade('valuation_box');
					Effect.BlindUp('valuation_box');
				}
				else
				{
					document.getElementById('valuation_form').innerHTML = "Your selection has been saved and your valuation is displayed at the bottom of this page.";
					show_valuation = 0;

					setTimeout(function() {
						Effect.Fade('valuation_box');
						Effect.BlindUp('valuation_box');
					}, 5*1000);
				}
			}
		}
	}
}

var vin_email 	= "";
var vin_vrm 	= "";
var vin_vin		= "";

function check_vin()
{
	vin_vin = document.forms.checkvin.vin.value.toUpperCase();

	/*we're only going to show an error about VIN length when the real VIN is 17 characters, but won't know until we make the request*/

	/*if (vin_vin.length > 17)
	{
		document.getElementById("checkvin_errors").innerHTML = "The maximum length of a VIN is 17 characters, the VIN you entered was longer than this.";
		return false;
	}*/

	if (vin_vin == "")
	{
		document.getElementById("checkvin_errors").innerHTML = "Please enter a VIN.";
		return false;
	}
	else
	{
		vin_vin = vin_vin.replace(/[^A-Za-z0-9]/g, "");
	}

	document.getElementById("vin_spinning").style.display = 'inline';

	xml_setup();
	xmlObj.onreadystatechange = check_vin_process;
	xmlObj.open("GET", base_url + "?act=vin_check&check_id=" + check_id + "&email=" + vin_email + "&reg_no=" + vin_vrm + "&user_vin=" + vin_vin);
	xmlObj.send(null);
}

function check_vin_process()
{
	if (xmlObj.readyState == 4)
	{
		if (xmlObj.status == 200)
		{
			document.getElementById("vin_spinning").style.display = "none";

			var error = "";
			var match = "";
			var note = "";
			var notes = new Array();
			var errorString = "";
			var user_vin_cleansed  = "";

			try {error = xmlObj.responseXML.getElementsByTagName("error")[0].firstChild.nodeValue;} catch (e) {}
			try {match = xmlObj.responseXML.getElementsByTagName("match")[0].firstChild.nodeValue;} catch (e) {match = 0;}
			try	{note = xmlObj.responseXML.getElementsByTagName("note")[0].firstChild.nodeValue;} catch (e) {}
			try {user_vin_cleansed = xmlObj.responseXML.getElementsByTagName("user_vin_cleansed")[0].firstChild.nodeValue;} catch (e) {}

			if (error != "")
			{
				document.getElementById("checkvin_errors").innerHTML = error;
				document.getElementById("checkvin_errors").style.display = "block";
				return false;
			}
			else
			{
				document.getElementById("checkvin_errors").style.display = "none";
				document.getElementById("checkvin_errors").innerHTML = "";
			}

			if (match == 1)
			{
				if (note != "")
				{
					notes = note.split("|");
					if (notes[0] == "replacement_required")
					{
						document.getElementById("checkvin_form").innerHTML = "After replacing invalid letters (I, O) with numbers (1, 0), the VIN you entered (" + vin_vin + ") matches the one we hold for this registration.";
						document.getElementById("vincheck_row" ).innerHTML = "The VIN you entered (" + user_vin_cleansed + ") matches the one we hold for this registration.";
					}
				}
				else
				{
					document.getElementById("checkvin_form").innerHTML = "The VIN you entered (" + vin_vin + ") matches the one we hold for this registration.";
					document.getElementById("vincheck_row" ).innerHTML = "The VIN you entered (" + user_vin_cleansed + ") matches the one we hold for this registration.";
				}

				show_vin = 0;
				setTimeout("hide_nextsteps_box('vin')", 18*1000);
			}
			else
			{
				if (note != "")
				{
					notes = note.split("|");
					for (var i = 0; i < notes.length; i++)
					{
						switch (notes[i])
						{
							case "exceeds_max_length":		errorString += "You entered a VIN with a length greater than 17 characters. VIN lengths must not exceed 17 characters.<br />"; break;
							case "entered_engine_number":	errorString += "You entered this vehicle's engine number, not its VIN.<br />"; break;
							case "entered_vrm":				errorString += "You entered this vehicle's registration number, not its VIN.<br />"; break;
							case "replacement_required":	errorString += "You entered invalid letters. Letters I and O are never used in VINs, please use the numbers 1 and 0 instead.<br />"; break;
						}

					}
				}

				document.getElementById("checkvin_errors").innerHTML = "Then VIN you entered (" + vin_vin + ") does not match the one we hold for this registration."

				if (errorString != "")
				{
					document.getElementById("checkvin_errors").innerHTML += "<br />" + errorString;
				}

				document.getElementById("checkvin_errors").style.display = "block";
				document.getElementById("vincheck_row"   ).innerHTML = "Then VIN you entered (" + vin_vin + ") does not match the one we hold for this registration.";
			}
		}
	}
}

function hide_nextsteps_box(box){
	if (!show_vin && !show_valuation && !show_upgrade) {
		Effect.Fade("nextsteps");
		Effect.BlindUp("nextsteps");
	} else {
		Effect.Fade(box + "_box");
		Effect.BlindUp(box + "_box");
	}
}

function update_payment_form_price(){
	cost = basic_cost;

	if (mileage_check_selected) {
		cost += mileage_check_cost;
	}

	if (text_confirmation_selected) {
		cost += text_confirmation_cost;
	}

	if (document.getElementById("charge_amount")) {
		document.getElementById("charge_amount").innerHTML = "&pound;" + cost.toFixed(2);
	}

	if (cost == 0) {
		document.getElementById('payment_form').style.display = 'none';
	} else {
		document.getElementById('payment_form').style.display = 'block';
	}
}




function ccare_update_payment_price()
{
	if (document.getElementById('classic_check_radio').checked)
	{
		var cost = classic_cost;

		if (document.getElementById('mileage_confirmation'))
		{
			cost += document.getElementById('mileage_yes').checked ? mileage_check_cost : 0;
		}

		if (document.getElementById('text_confirmation'))
		{
			cost += document.getElementById('text_yes').checked ? text_confirmation_cost : 0;
		}

		if (document.getElementById('charge_amount'))
		{
			document.getElementById('charge_amount').innerHTML = '&pound;' + cost.toFixed(2);
		}
	}
}

function classic_radio_onclick()
{
	display_mileage_confirmation(true);
	display_text_confirmation(true);

	var cost = classic_cost;

	if (document.getElementById('mileage_confirmation'))
	{
		cost += document.getElementById('mileage_yes').checked ? mileage_check_cost : 0;
	}

	if (document.getElementById('text_confirmation'))
	{
		cost += document.getElementById('text_yes').checked ? text_confirmation_cost : 0;
	}

	if (document.getElementById('charge_amount'))
	{
		document.getElementById('charge_amount').innerHTML = '&pound;' + cost.toFixed(2);
	}
}

function gold_radio_onclick()
{
	display_mileage_confirmation(false);
	display_text_confirmation(true);

	//if (document.getElementById('mileage_confirmation'))
	//{
		//document.getElementById('mileage_yes').checked = true;
	//}

	document.getElementById('charge_amount').innerHTML = '&pound;' + gold_cost.toFixed(2);
}

function platinum_radio_onclick()
{
	display_mileage_confirmation(false);
	display_text_confirmation(true);

	//if (document.getElementById('mileage_confirmation'))
	//{
		//document.getElementById('mileage_yes').checked = true;
	//}

	if (document.getElementById('charge_amount'))
	{
		document.getElementById('charge_amount').innerHTML = '&pound;' + platinum_cost.toFixed(2);
	}
}

function valuation_radio_onclick()
{
	display_mileage_confirmation(false);
	display_text_confirmation(false);

	if (document.getElementById('text_confirmation'))
	{
		document.getElementById('text_no').checked = true;
		show_mobile(false);
	}

	//if (document.getElementById('mileage_confirmation'))
	//{
		//document.getElementById('mileage_no').checked = true;
	//}

	if (document.getElementById('charge_amount'))
	{
		document.getElementById('charge_amount').innerHTML = '&pound;' + valuation_cost.toFixed(2);
	}
}

function display_text_confirmation(show)
{
	if (document.getElementById('text_confirmation'))
	{
		if (show)
		{
			document.getElementById('text_confirmation').style.display = 'block';
		}
		else
		{
			document.getElementById('text_confirmation').style.display = 'none';
		}
	}
}

function display_mileage_confirmation(show)
{
	if (document.getElementById('mileage_confirmation'))
	{
		if (show)
		{
			document.getElementById('mileage_confirmation').style.display = 'block';
		}
		else
		{
			document.getElementById('mileage_confirmation').style.display = 'none';
		}
	}
}


var pc_properties_hash = new Object();
var pc_street;
var pc_locality;
var pc_town;
var pc_postcode;

function pc_get_list(postcode, property)
{
	document.getElementById('spinning').style.display = 'inline';
	xml_setup();
	xmlObj.onreadystatechange = pc_get_list_process;
	xmlObj.open('GET', base_url + '?act=pc_address_list&postcode=' + postcode + '&property=' + property);
	xmlObj.send(null);
}

function pc_get_list_process()
{
	if (xmlObj.readyState == 4)
	{
        if (xmlObj.status == 200)
		{
            document.getElementById('spinning').style.display = 'none';
			var error = 0;
			var notspecific = 0;

			try
			{
				error = parseInt(xmlObj.responseXML.getElementsByTagName("error")[0].firstChild.nodeValue);
			}
			catch (e)
			{

			}

			if (error == 1)
			{
				document.getElementById('errors').innerHTML = 'Sorry, we couldn\'t find any information for this postcode. Please try again or <br /><a style="cursor:pointer;" onclick="pc_bypass(); return false;">click here to enter your address manually</a>';
				document.getElementById('errors').style.display = 'block';
				return false;
			}
			else
			{
				document.getElementById('errors').style.display = 'none';
				document.getElementById('errors').innerHTML = '';
			}

			try
			{
				pc_street = xmlObj.responseXML.getElementsByTagName('street')[0].firstChild.nodeValue;
			}
			catch (e)
			{
				pc_street = '';
			}

			pc_town = xmlObj.responseXML.getElementsByTagName('town')[0].firstChild.nodeValue;
			pc_postcode = xmlObj.responseXML.getElementsByTagName('postcode')[0].firstChild.nodeValue;

			try
			{
				pc_locality = xmlObj.responseXML.getElementsByTagName('locality')[0].firstChild.nodeValue;
			}
			catch (e)
			{
				pc_locality = '';
			}

			var pc_properties = xmlObj.responseXML.getElementsByTagName('property');
			pc_properties_hash = new Object();

			for (var i=0;i<pc_properties.length;i++)
			{
				pc_properties_hash[pc_properties[i].getElementsByTagName('id')[0].firstChild.nodeValue] = pc_properties[i].getElementsByTagName('name')[0].firstChild.nodeValue;
			}

			if (pc_properties.length == 1)
			{
				pc_select_property(pc_properties[0].getElementsByTagName('id')[0].firstChild.nodeValue);
				if (document.getElementById('select_address_prompt'))
				{
					document.getElementById('select_address_prompt').style.display = 'none';
				}
				return false;
			}

			document.getElementById('select_address').innerHTML =
				"<div id=\"select_address_prompt\">Please select your address from the list below. If your address is not present you can try again or <br />" +
				"<a style=\"cursor:pointer;\" onclick=\"pc_bypass(); return false;\">click here to enter your address manually</a></div>" +
				"<select id=\"properties_select\" name=\"properties_select\"></select> <input type=\"button\" value=\"Select\" onclick=\"pc_select_property(detailsform.properties_select.value);\" />" +
				"<div class=\"spacer\"></div>";

			var address = (pc_street != '' ? ' ' : '') + pc_street + (pc_locality != '' ? ', ' : ' ') + pc_locality;
			var options = document.getElementById('properties_select');

			options.length = 0;

			for (key in pc_properties_hash)
			{
				options.options[options.length] = new Option(pc_properties_hash[key] + address, key);
			}

			document.getElementById('select_address').style.display = 'block';

			return false;
		}
	}
}

/*handler for Address List select*/
function pc_select_property(property)
{
	document.getElementById('errors').style.display = 'none';
	document.detailsform.address1.value = pc_properties_hash[property] + ' ' + pc_street;
	document.detailsform.address2.value = pc_locality;
	document.detailsform.city.value = pc_town;
	document.detailsform.postcode.value = pc_postcode.toUpperCase();

	document.getElementById('property_field').style.display = 'none';
	document.getElementById('find_address').style.display = 'none';
	document.getElementById('select_address').style.display = 'none';

	document.getElementById('address').style.display = 'block';

	_blur('address1');
	_blur('city');

	document.getElementById('postcode').focus();
}

/*handler for Enter Address Manually links*/
function pc_bypass()
{
	document.detailsform.address1.value = document.detailsform.property.value;
	document.detailsform.postcode.value = document.detailsform.postcode.value.toUpperCase();

	document.getElementById('property_field').style.display = 'none';
	document.getElementById('find_address').style.display = 'none';
	document.getElementById('errors').style.display = 'none';
	document.getElementById('select_address').style.display = 'none';
	document.getElementById('address').style.display = 'block';

	_blur('address1');
	_blur('city');
}

/*handler for Country select*/
function check_country(country)
{
       
	if (parseInt(country) == 90)
	{
		hide_error('property');
		hide_error('postcode');
		hide_error('address1');
		hide_error('city');
		hide_error_foot();

		document.getElementById('property').value = '';
		document.getElementById('postcode').value = '';
		document.getElementById('address1').value = '';
		document.getElementById('city').value = '';

		/*make sure we validate propery and postcode as country is UK*/
		elems['property']['tst'] = 'not_empty';
		elems['property']['err'] = 'Please enter your building name/no.';

		elems['postcode']['tst'] = 'valid_postcode';
		elems['postcode']['err'] = 'Please enter a valid postcode';

		document.getElementById('postcode_label').innerHTML = 'Postcode *';
		document.getElementById('postcode_help').style.display = 'block';

		document.getElementById('address').style.display = 'none';
		document.getElementById('property_field').style.display = 'block';
		document.getElementById('find_address').style.display = 'block';
	}
	else
	{
		/*hide errors for property and postcode (regardless of what has been typed/not typed) and remove validators*/
		hide_error('property');
		hide_error('postcode');
		hide_error('address1');
		hide_error('city');
		hide_error_foot();

		document.getElementById('property').value = '';
		document.getElementById('postcode').value = '';
		document.getElementById('address1').value = '';
		document.getElementById('city').value = '';

		elems['property']['tst'] = '';
		elems['property']['err'] = '';

		elems['postcode']['tst'] = '';
		elems['postcode']['err'] = '';

		document.getElementById('select_address').innerHTML = '';
		document.getElementById('select_address').style.display = 'none';

		document.getElementById('postcode_label').innerHTML = 'Postal Code';
		document.getElementById('postcode_help').style.display = 'none';

		document.getElementById('property_field').style.display = 'none';
		document.getElementById('find_address').style.display = 'none';
		document.getElementById('address').style.display = 'block';
	}
}


/*handler for Card Type select*/
function toggle_issue_no()
{
	if (document.getElementById('type').value == 2 || document.getElementById('type').value == 6)
	{
		document.getElementById('issue').style.display = 'block';
	}
	else
	{
		document.getElementById('issue').style.display = 'none';
	}
}

/*handler for Text Confirmation yes radio*/
function show_mobile(mobile)
{
	hide_error('phone_no');
	var labl = document.getElementById('phone_no_label');
	var help = document.getElementById('phone_no_help');

	if (mobile)
	{
		labl.innerHTML = 'UK Mobile No. *';
		help.innerHTML = 'Must be a valid UK mobile number';
		elems['phone_no']['tst'] = 'valid_mobile';
		elems['phone_no']['err'] = 'Please enter a valid UK mobile number';

		if (document.getElementById('phone_no').value != '')
		{
			_blur('phone_no');
		}
	}
	else
	{
		labl.innerHTML = 'Telephone No. *';
		help.innerHTML = '';
		elems['phone_no']['tst'] = 'valid_phone_no';
		elems['phone_no']['err'] = 'Please enter your telephone number';
	}
}

/*handler for Find Address button*/
function find_address_click()
{
	_blur('property');
	_blur('postcode');

	if (!error_visible('property') && !error_visible('postcode'))
	{
		elems['property']['tst'] = '';
		elems['property']['err'] = '';

		pc_get_list(document.getElementById('postcode').value.replace(/[^A-Za-z0-9]/g, ''), document.getElementById('property').value);

		document.getElementById('select_address').style.color = '#000';
		document.getElementById('select_address').style.fontSize = '100%';

		if (document.getElementById('select_address').style.display != 'none')
		{
			document.getElementById('select_address').style.display = 'block';
		}
	}
}

function find_address_click_no_valiation()
{
	pc_get_list(document.getElementById('postcode').value.replace(/[^A-Za-z0-9]/g, ''), document.getElementById('property').value);
	document.getElementById("postcode").focus();
}

/*form elements to be validated with associated test functions and error msgs
 *for multiple tests use tst : not_empty|valid_mobile and err : 'not_empty error|valid_mobile error'*/
var elems = null;

/*this function is used to initialise elems - not all forms contain the same elements*/
function init_elems()
{
	if (document.getElementById('detailsform'))
	{
		
		elems =
		{
			'name':				 {'tst':'not_empty',		'err':'Please enter your name'},
			'email':			 {'tst':'valid_email',		'err':'Please enter a valid email address'},
			'phone_no':			 {'tst':'valid_phone_no',	'err':'Please enter your telephone number'},
			'address1':			 {'tst':'not_empty',		'err':'Please enter your house no. &amp; street name'},
			'property':			 {'tst':'not_empty',		'err':'Please enter your building name/no.'},
			'city':				 {'tst':'not_empty',		'err':'Please enter your town/city'},
			'postcode':			 {'tst':'valid_postcode',	'err':'Please enter a valid UK postcode'},
			'cardholder':		 {'tst':'not_empty',		'err':'Please enter the card holder\'s name'},
			'type':				 {'tst':'not_empty',		'err':'Please select the type of card'},
			'number':			 {'tst':'valid_card_number','err':'Please enter the card number'},
			'expiry_date_month': {'tst':'valid_date',		'err':'Overriden by test function'},
			'expiry_date_year':	 {'tst':'valid_date',		'err':'Overriden by test function'},
			'cv2':				 {'tst':'valid_cv2',		'err':'Please enter a valid card security code'},
			'issue_no':			 {'tst':'valid_issue_no',	'err':'Please enter a valid card issue number'},
			'tc':				 {'tst':'is_checked',		'err':'Please tick the box to declare you have read and understood our terms &amp; conditions'},
			'reason':			 {'tst':'not_empty',		'err':'Please select the charge reason'},
			'amount':			 {'tst':'valid_amount',		'err':'Please enter the amount in pounds and pence'},
                        'detail':            {'tst':'',        			'err':''},
			'company_name':		 {'tst':'not_empty',		'err':'Please enter the company name'},
			'mobile_no':		 {'tst':'valid_mobile',		'err':'Please enter a valid UK mobile number'},
			'vrm':				 {'tst':'valid_vrm',		'err':'Please enter a valid registration number'},
			'purchase_price':	 {'tst':'valid_amount',		'err':'Please enter the amount in pounds and pence'},
			'selected_payment_method_paypal': {'tst': 'validate_payment_type_selected', 'err':'Please select your preferred payment method!'},
                        'user_last_four':	 {'tst':'not_empty', 'err':'Please enter the last 4 numbers on card'}
		}
	}

	else if (document.getElementById('resend_confirmation_email') && document.getElementById('resend_confirmation_text'))
	{
		elems =
		{
			'email':			{'tst':'valid_email',		'err':'Please enter a valid email address'},
			'phone_no':			{'tst':'valid_mobile',		'err':'Please enter a valid mobile number'}
		}
	}
	else if (document.getElementById('resend_confirmation_email'))
	{
		elems =
		{
			'email':			{'tst':'valid_email',		'err':'Please enter a valid email address'}
		}
	}
	else if (document.getElementById('contact_us_form')) 
	{
		
		elems =
		{
			'name':				{'tst':'not_empty',				'err':'Please enter your name!'},
			'email':			{'tst':'valid_email',			'err':'Please enter a valid email address!'},
			'question':			{'tst':'not_empty',				'err':'Please enter your question!'}
			//,
			//'vrm'		  :		{'tst':'prev_chk_not_empty',	'err':'Please enter the vehicle registration!'},
			//'order_number':		{'tst':'prev_chk_not_empty',	'err':'Please enter the order number!'}
		}
		
	} 

	if (document.getElementById("info_source_previous") && document.getElementById("info_source_previous").checked)
	{
		toggle_forms(0);
	}
	
	if(document.getElementById('addnote_form')) {
		
		elems =
		{
			'comment':			{'tst':'not_empty',		'err':'Please enter a note/comment!'}
		}
	} 
	
}

/*handler for form onsubmit event*/
function _submit(id)
{
	var mileage = true;
	
	if (id == 'detailsform')
	{
		if (document.getElementById('find_address').style.display == 'block')
		{
			document.getElementById('select_address').innerHTML = 'Please confirm your Building Name/No. and Postcode then click Find Address.';
			document.getElementById('select_address').style.color = '#C00';
			document.getElementById('select_address').style.fontSize = '70%';
			document.getElementById('select_address').style.display = 'block';
		}

		if (document.getElementById('mileage_check_fragment'))
		{
			mileage = validate_mileage();
		}
		
	}
	
	if(id == 'upgradeform') {
		
		function get_card_source_value() {
		
			for (var i=0; i < document.upgradeform.card_to_charge.length; i++) {
		   
				if (document.upgradeform.card_to_charge[i].checked) {
		      
					var rad_val = document.upgradeform.card_to_charge[i].value;
				}
			}
		
			return rad_val;
		}

		var card_source = get_card_source_value();
//		alert(card_source);
		
	}

	/*now validate all form elements*/
	var submit = validate_all(document.getElementById(id));
	
	if ((!submit || !mileage) && document.getElementById('error_foot'))
	{
		document.getElementById('error_foot').style.display = 'block';
	}

//	alert(submit);
	return submit && mileage;
}

/*handler for onblur events*/
function _blur(id)
{
	var tst = elems[id]['tst'].split('|');
	var err = elems[id]['err'].split('|');

	for (var i = 0; i < tst.length; i++)
	{
		/*use this to catch any elements that no longer require validation (eg property) and their tst function has been set to ''*/
		if (tst[i] != '' && err[i] != '')
		{
			if (this[tst[i]](id))
			{
				hide_error(id);
			}
			else
			{
				show_error(id, err[i]);
				break;
			}
		}
	}

	hide_error_foot();
}

/*handler for onkeyup events*/
function _keyup(id)
{
	var tst = elems[id]['tst'].split('|');
	var err = elems[id]['err'].split('|');

	for (var i = 0; i < tst.length; i++)
	{
		if (tst[i] != '' && err[i] != '')
		{
			if (document.getElementById(id + '_error').innerHTML == err[i])
			{
				if (this[tst[i]](id))
				{
					hide_error(id);
				}
			}
		}
	}

	hide_error_foot();
}

/*validate all form elements*/
function validate_all(form)
{
	var flag = true;
	for (var i=0; i < form.elements.length; i++)
	{
		/*use this to skip form elements that are not required*/
		if (elems[form.elements[i].id] != undefined &&
			elems[form.elements[i].id]['tst'] != '' &&
			elems[form.elements[i].id]['err'] != '')
		{
			var tst = elems[form.elements[i].id]['tst'].split('|');
			var err = elems[form.elements[i].id]['err'].split('|');

			for (var j = 0; j < tst.length; j++)
			{
				if (!this[tst[j]](form.elements[i].id))
				{
					show_error(form.elements[i].id, err[j]);
					flag = false;
//					alert(err[j]);
					break;
				}
			}
		}
	}

	hide_error_foot();

	return flag;
}

/*helper functions for hiding/showing errors*/
function hide_error(id)
{
	/**/if (id != 'expiry_date_month' && id != 'expiry_date_year')
	{
		if (error_visible(id))
		{
			document.getElementById(id).setAttribute('class', '');
			document.getElementById(id + '_error').innerHTML = '';
		}
	}
}

function show_error(id, error)
{
	/**/if (id != 'expiry_date_month' && id != 'expiry_date_year')
	{
		if (!error_visible(id))
		{
			document.getElementById(id).setAttribute('class', 'error');
			document.getElementById(id + '_error').innerHTML = error;
		}
	}
}

function error_visible(id)
{
	return document.getElementById(id + '_error').innerHTML != '';
}

/*used to hide main error at foot of page*/
function hide_error_foot()
{
	if (document.getElementById('error_foot'))
	{
		var hide_error_foot = true;
		/*these are all fields site-wide that have a span for their error message*/
		var error_span_elem = new Array('name','email','phone_no','address1','property','city','postcode','cardholder','type','number','expiry_date','cv2','issue_no','tc','user_last_four','reason','detail','amount','vrm','mobile_no');

		for (var i in error_span_elem)
		{
			/*make sure error span element exists on whichever page we're using*/
			if (document.getElementById(error_span_elem[i] + '_error'))
			{
				if (error_visible(error_span_elem[i]))
				{
					hide_error_foot = false;
					break;
				}
			}
		}

		if (hide_error_foot)
		{
			document.getElementById('error_foot').style.display = 'none';
		}
	}
}

/**
 * used on the contact form
 * checks to see if the user has checked the 'yes' radio button for previous check'
 * and the required fields are not empty
 * 
 * @return boolean
 */ 
function prev_chk_not_empty() {
	
	if(document.getElementById('previous_check_yes').checked == true) {
		
		if(trim(document.getElementById('vrm').value) == '') {
			return false;
		}
		
		if(trim(document.getElementById('order_number').value) == '') {
			return false;
		}
	} 
	
	return true;
}

/**
 * used on the main check from (user-form.tpl)
 * checks too see that one of the radio buttons for payment options has been selected
 * 
 * @return boolean
 */
function validate_payment_type_selected() {
	
	if(document.getElementById('selected_payment_method_paypal').checked == false && document.getElementById('selected_payment_method_cc').checked == false) {
		return false;
	} else {
		return true;
	}
	
}


/*return true if element is empty/blank after trimming*/
function not_empty(id)
{
	if (trim(document.getElementById(id).value) != '')
	{
		return true;
	}
	else
	{
		document.getElementById(id).value = '';
		return false;
	}
}

/*return true if email is valid*/
function valid_email(id)
{
	//ci email regex: /^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix
	var trim_email = trim(document.getElementById(id).value);
	return trim_email.match(/^([a-z0-9_\-\.])+\@([a-z0-9_\-\.])+\.([a-z]{2,6})$/i);
}

/*return true if mobile is valid*/
function valid_mobile(id)
{
	var number = document.getElementById(id).value;

	//replace +44 with 0 and then everything but numbers with ''
	number = number.replace('+44', '0');
	number = number.replace(/[^\d]/g, '');

	return number.match(/^((00|\+)44|0)7\d{9}$/);
}

function valid_phone_no(id)
{
	var phone_no = document.getElementById(id).value.replace(/[^\d]/g, '');
	return phone_no.length > 0;
}

/*return true if postcode is valid*/
function valid_postcode(id)
{
	var postcode = document.getElementById(id).value.replace(/[^A-Za-z0-9]/g, '');
	return postcode.match(/^(GIR 0AA|[A-PR-UWYZ]([0-9]{1,2}|([A-HK-Y][0-9]|[A-HK-Y][0-9]([0-9]|[ABEHMNPRV-Y]))|[0-9][A-HJKS-UW])[0-9][ABD-HJLNP-UW-Z]{2})$/i);
}

function valid_card_number(id)
{
	var number = document.getElementById(id).value.replace(/[^\d]/g, '');
	return number.length > 0;
}

/*return true if security code is valid*/
function valid_cv2(id)
{
	return document.getElementById(id).value.match(/^[0-9]{3}$/);
}

function valid_card_last4(id)
{
	var number = document.getElementById(id).value.replace(/[^\d]/g, '');
	return number.match(/^[0-9]{4}$/);
}

/*return true if issue number is valid*/
function valid_issue_no(id)
{
	var issue = document.getElementById(id).value;
	if (issue == '')
	{
		/*allow blank because not all maestro cards have issue numbers*/
		return true;
	}
	else
	{
		/*allow 00|0 - 99*/
		return issue.match(/^[0-9]{1,2}$/);
	}
}

function valid_amount(id)
{
    var amount = document.getElementById(id).value;
    return amount.match(/^[0-9]+\.[0-9]{2}$/) && parseFloat(amount) > 0 && parseFloat(amount) <  100;
}

/*return true if checkbox is checked*/
function is_checked(id)
{
	return document.getElementById(id).checked;
}

function valid_vrm(id)
{
	//return vrm.match(/^[a-z]?[0-9]{1,3}[a-z]{3}|[a-z]{3}[0-9]{1,3}[a-z]?|[a-z]{2}5[0-9]?[a-z]{3}|[a-z]{2}0[0-9]?[a-z]{3}|[0-9]{1,4}[a-z]{1,3}|[a-z]{1,3}[0-9]{1,4}$/i);
	var vrm = document.getElementById(id).value.replace(/[^A-Za-z0-9]/g, '');

	return (vrm.match(/^[a-z]?[0-9]{1,3}[a-z]{3}$/i) ||	// A 123 BCD
			vrm.match(/^[a-z]{3}[0-9]{1,3}[a-z]?$/i) ||	// DCB 123 A
			vrm.match(/^[a-z]{2}5[0-9]?[a-z]{3}$/i) ||  // AB 51 CDE
			vrm.match(/^[a-z]{2}0[0-9]?[a-z]{3}$/i) ||  // AB 01 CDE
			vrm.match(/^[a-z]{2}6[0-9]?[a-z]{3}$/i) ||  // AB 60-69 CDE
			vrm.match(/^[a-z]{2}1[0-9]?[a-z]{3}$/i) ||  // AB 10-19 CDE
			vrm.match(/^[0-9]{1,4}[a-z]{1,3}$/i) ||  	// 1234 ABC
			vrm.match(/^[a-z]{1,3}[0-9]{1,4}$/i))		// ABC 1234
}

function validate_mileage()
{
	if (document.getElementById('mileage_yes') && document.getElementById('mileage_no'))
	{
		if (document.getElementById('mileage_yes').checked || document.getElementById('mileage_no').checked)
		{
                        if(document.getElementById('mileage_check_error')) {
                            document.getElementById('mileage_check_error').style.display = 'none';
                        }
			return true;
		}
		else
		{
			document.getElementById('mileage_check_error').style.display = 'block';
			document.getElementById('error_foot').style.display = 'block';
			return false;
		}
	}

	return true;
}

/*return true if month and year inputs are in the future (or if same as current month and year) else false for in the past
 (this function edits and displays all errors manually)*/
var yy_attempt = false;
var mm_attempt = false;
function valid_date(id)
{
	var date = new Date();
	/*inputs for expiry month and year*/
	var mm = parseInt(document.getElementById('expiry_date_month').value.replace(/[^\d]/g, ''), 10);
	var yy = parseInt(document.getElementById('expiry_date_year' ).value.replace(/[^\d]/g, ''), 10);
	/*current month and year as mm and yy*/
	var mm_now = parseInt(date.getMonth(), 10) + 1;
	var yr_str = date.getFullYear().toString();
	var yy_now = parseInt(yr_str.substring(yr_str.length, 2), 10);
	/*input and error span elements*/
	var mm_elem = document.getElementById('expiry_date_month');
	var yy_elem = document.getElementById('expiry_date_year' );
	var er_elem = document.getElementById('expiry_date_error');

	/*if this is onblur for year and no attempt to enter year has occurred yet, set year enter attempt flag to true*/
	if (id == 'expiry_date_year'  && !yy_attempt)
	{
		yy_attempt = true;
	}

	/*if this is onblur for month and no attempt to enter month has occurred yet, set month enter attempt flag to true*/
	if (id == 'expiry_date_month' && !mm_attempt)
	{
		mm_attempt = true;
	}

	/*onblur has been called on year and month already, validate both*/
	if (yy_attempt && mm_attempt)
	{
		if (!(mm > 0 && mm < 13) && !(yy > 0 && yy < 100) || (mm == '' && yy == ''))
		{
			mm_elem.setAttribute('class', 'error');
			yy_elem.setAttribute('class', 'error');
			er_elem.innerHTML = 'Please enter a valid month and year';
			return false;
		}
		else if (!(mm > 0 && mm < 13) || mm == '')
		{
			mm_elem.setAttribute('class', 'error');
			yy_elem.setAttribute('class', '');
			er_elem.innerHTML = 'Please enter a valid month';
			return false;
		}
		else if (!(yy > 0 && yy < 100) || yy == '')
		{
			mm_elem.setAttribute('class', '');
			yy_elem.setAttribute('class', 'error');
			er_elem.innerHTML = 'Please enter a valid year';
			return false;
		}
	}
	/*onblur has been called on year only, validate year*/
	else if (yy_attempt && !mm_attempt)
	{
		if (!(yy > 0 && yy < 100) || yy == '')
		{
			yy_elem.setAttribute('class', 'error');
			er_elem.innerHTML = 'Please enter a valid year';
			return false;
		}
		else
		{
			yy_elem.setAttribute('class', '');
			er_elem.innerHTML = '';
			return true;
		}
	}
	/*onblur has been called on month only, validate month*/
	else if (!yy_attempt && mm_attempt)
	{
		if (!(mm > 0 && mm < 13) || mm == '')
		{
			mm_elem.setAttribute('class', 'error');
			er_elem.innerHTML = 'Please enter a valid month';
			return false;
		}
		else
		{
			mm_elem.setAttribute('class', '');
			er_elem.innerHTML = '';
			return true;
		}
	}

	/*now check inputs to make sure both are in the future, or at least equal to current month and year*/
	if (yy < yy_now)
	{
		if (mm < mm_now)
		{
			mm_elem.setAttribute('class', 'error');
			yy_elem.setAttribute('class', 'error');
			er_elem.innerHTML = 'Please enter a month and year in the future';
			return false;
		}
		else
		{
			mm_elem.setAttribute('class', '');
			yy_elem.setAttribute('class', 'error');
			er_elem.innerHTML = 'Please enter a year in the future';
			return false;
		}
	}
	else if (yy == yy_now)
	{
		if (mm < mm_now)
		{
			mm_elem.setAttribute('class', 'error');
			yy_elem.setAttribute('class', '');
			er_elem.innerHTML = 'Please enter a month in the future';
			return false;
		}
		else
		{
			mm_elem.setAttribute('class', '');
			yy_elem.setAttribute('class', '');
			er_elem.innerHTML = '';
			return true;
		}
	}
	else if (yy > yy_now)
	{
		/*always valid*/
		mm_elem.setAttribute('class', '');
		yy_elem.setAttribute('class', '');
		er_elem.innerHTML = '';
		return true;
	}
}

//trim functions from http://www.webtoolkit.info/javascript-trim.html
function trim(str, chars)
{
	return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars)
{
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars)
{
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}

/*
 * toggle the form elements containing the new card details or the single field for last 4 digits of previously used card
 */
	function swap_upgrade_card_source(source) {
		
		if(source == 'new') {
			
			var elems =
			{
				'user_last_four':{'tst':'',		'err':''}
			}
			
			document.getElementById('old_card').style.display = 'none';
			document.getElementById('new_card').style.display = 'block';
			
		} else {
			
			document.getElementById('new_card').style.display = 'none';
			document.getElementById('old_card').style.display = 'block';
		
			
		}
	}
/*
 * load any other javascript
 */
function loadJs(js_path) {

	var js = document.createElement("script");

	js.type = "text/javascript";
	js.src = js_path;

	var head = document.getElementsByTagName('head')[0];
	head.appendChild(js);
}
/*loadJs("/media/generic/jquery/jquery-1.4.4.min.js");
        loadJs("/media/generic/jquery/jquery.validate.js");
        loadJs("/media/generic/validate.js");
*/
