/* ABE DISPLAY */

var reference;
var specialEquipment = new Array();



/* **************************************************************************************************** */
/*                                                                                     GLOBAL VARIABLES */
var abeLoadInterval, abeWaitInterval, abeWaitInterval2, abeWait, abeWait2,
abeProcessLoad = new String (abeAction ["process_load"]), abeProcessWait = new String (),
abeCurrencySymbol = new String (), abe_X = new String (), abe_Y = new String ();

// ********************
var abeAge;

/* **************************************************************************************************** */
/*                                                                                               COMMON */
// Returns element by ID
function abe_ID (element)
{
	return document.getElementById ("abe_" + element);
}
// Sets element's display style
function abe_display (element, d)
{
	abe_ID (element).style.display = d;
}
// Controls element's visibility style
function abe_visible (element)
{
	var e = abe_ID (element);
	e.style.visibility = e.style.visibility == "hidden" ? "visible" : "hidden";
}
// Writes content into element
function abe_inner (element, content)
{
	abe_ID (element).innerHTML = content;
}
// Assigns title to element
function abe_tip (element)
{
	var t = abeTip [element];
	t && t != "" ? abe_ID (element).title = t : null;
}
// Checks if element exists
function abe_exist (element)
{
	if (!abe_ID (element))
	{
		alert ("ERROR:\nno element exists: abe_" + element);
	}
	else
	{
		return true;
	}
}
// Returns the element's options collection
function abe_option (element)
{
	return abe_ID (element).options;
}
// Adds option to the select element
function abe_add_option (element, option_index, option_text, option_value)
{
	abe_option (element) [option_index] = new Option (option_text, option_value);
}

// Removes all option from the select element
function abe_remove_options (element)
{
	var object = abe_option (element);
	while(object.length>0)
	{
		try
		{
			object.remove (0);
		}
		catch (e)
		{
			object [0] = null;
		}
	}
}

// Removes option from the select element
function abe_rem_option (element, index)
{
	var object = abe_option (element);
	try
	{
		object.remove (index);
	}
	catch (e)
	{
		object [index] = null;
	}
}
// Enables / disables select element
function abe_disable (element, status)
{
	with (abe_ID (element))
	{
		disabled = status;
		style.backgroundColor = abeBG [(status ? "dis" : "en") + "able"];
	}
}
// Removes options list from select element
function abe_rem_list (element)
{
	abe_disable (element, true);
	while (abe_option (element).length > 0)
	{
		abe_rem_option (element, 0)
	}
}
// Sets "onchange" event to element
function abe_onchange (element)
{
	// ************************************************************** ADD KEYBOARD NAVIGATION *******************************
	abe_ID (element).onchange = eval ("abe_change_" + element);
}
// Sets "onclick" event to element
function abe_onclick (element)
{
	abe_ID (element).onclick = eval ("abe_click_" + element);
}
// Deletes table rows till minimum rows number
function abe_delete (table, minimum)
{
	var e = abe_ID (table);
	while (e.rows.length > minimum)
	{
		e.deleteRow (-1);
	}
}
// Returns formated address for search details
function abe_format_address (e)
{
	var a = abeLocationArray [e ["ID"]]["Address"], p = ", ";
	while (a.indexOf (p, 1) != -1)
	{
		a = a.replace (p, ",<br>");
	}
	return a;
}
// Writes content into table cells for search details
function abe_inner_details (row, content1, content2)
{
	with (abe_ID ("details").rows [row])
	{
		cells [1].innerHTML = content1;
		cells [3].innerHTML = content2;
	}
}
// Returns number with fixed number to the right of decimal
function abe_price (number)
{
	return Number (number).toFixed (2);
}



/* **************************************************************************************************** */
/*                                                                               INITIALIZING & LOADING */
// Shows loading window loading process
function abe_process_load ()
{
	var a = abeAction ["process_load"];
	abeProcessLoad = abeProcessLoad == a + a + a + a + a ? a : abeProcessLoad + a;
	abe_inner ("load_process", abeProcessLoad);
}
// Shows first request select field loading process
function abe_process_wait ()
{
	var a = abeAction ["process_wait"];
	abeProcessWait = abeProcessWait == a + a + a ? "" : abeProcessWait + a;
	abe_option (abeWait) [0].text = abeAction ["wait"] + abeProcessWait;
}
// Shows second request select field loading process
function abe_process_wait2 ()
{
	var a = abeAction ["process_wait"];
	abeProcessWait = abeProcessWait == a + a + a ? "" : abeProcessWait + a;
	abe_option ("residenceList") [0].text = abeAction ["wait"] + abeProcessWait;
}
// Shows loading window
function abe_load (action)
{
	if (action)
	{
		abe_inner ("load_action", abeAction [action]);
		abeLoadInterval = setInterval ("abe_visible ('load_wait'), abe_process_load ()", 250);
		abe_display ("load", "block");
	}
	else
	{
		abe_display ("load", "none");
		clearInterval (abeLoadInterval);
	}
}
// Disables select fileds, enables awaiting status, creates, sends and receives XML request / response
function abe_request (action)
{
	abeWait = action;
	switch (abeWait)
	{
		case "countryList":
			abe_add_option (abeWait, 0, abeAction ["wait"], "");
			abe_add_option ("residenceList", 0, abeAction ["wait"], "");
			abeWaitInterval = setInterval ("abe_process_wait ()", 250);
			abeWaitInterval2 = setInterval ("abe_process_wait2 ()", 250);
			break;
		case "locationPickup":
			abe_disable ("locationDropoff", true);
			break;
		case "search":
			abe_inner ("countryConditions", "&nbsp;");
			abe_delete ("cars", 1);
			break;
		case "fleet_countryList":
			abe_add_option (abeWait, 0, abeAction ["wait"], "");
			abeWaitInterval = setInterval ("abe_process_wait ()", 250);
			break;
		default:
			break;
	}
	if (abeWait == "locationPickup" || abeWait == "locationDropoff")
	{
		abe_add_option (abeWait, 0, abeAction ["wait"], "");
		clearInterval (abeWaitInterval);
		abeWaitInterval = setInterval ("abe_process_wait ()", 250);
	}
	abe_create1 ();
	abeXMLHttp1.onreadystatechange = abe_receive;
	abe_send ();
}
// Disables select filed, enables awaiting status, creates, sends and receives XML request / response
function abe_request2 (action)
{
	abe_disable ("residenceList", false);
	abe_create2 ();
	abeXMLHttp2.onreadystatechange = abe_receive2;
	abe_send2 ();
}



/* **************************************************************************************************** */
/*                                                                                           NAVIGATION */
// Sets steps [id="abe_steps"] element's font weight & color, background color & image
function abe_step_status (element, weight, font, bg)
{
	var e = "step_" + element;
	e = abe_ID (e);
	e.getElementsByTagName ("span") [0].style.fontWeight = weight;
	e.style.color = "#" + font;
	e.style.backgroundColor = "#" + bg;
}
// Navigates BACK/FORWARD between STEPS 1, 2 & 3
function abe_selectStep (step)
{
	switch (step)
	{
		case "quote":
			abe_display ("details", "none");
			abe_display ("countryConditions", "none");
			abe_display ("legend", "none");
			abe_display ("cars", "none");
			abe_display ("popup", "none");
			abe_display ("confirm", "none");
			abe_display ("quote", "inline");
			abe_step_status (1, "bold", "ffffff", "646464");
			abe_step_status (2, "normal", "646464", "f3f3f3");
			abe_step_status (3, "normal", "646464", "f3f3f3");
			break;
		case "reserve":
			abe_display ("quote", "none");
			abe_display ("confirm", "none");
			abe_display ("popup", "none");
			abe_display ("details", "block");
			abe_display ("countryConditions", "block");
			abe_display ("legend", "inline");
			abe_display ("cars", "block");
			abe_step_status (1, "normal", "646464", "f3f3f3");
			abe_step_status (2, "bold", "ffffff", "646464");
			abe_step_status (3, "normal", "646464", "f3f3f3");
			break;
		case "confirm":
			abe_display ("details", "none");
			abe_display ("countryConditions", "none");
			abe_display ("legend", "none");
			abe_display ("cars", "none");
			abe_display ("popup", "none");
			abe_display ("confirm", "inline");
			abe_step_status (1, "normal", "646464", "f3f3f3");
			abe_step_status (2, "normal", "646464", "f3f3f3");
			abe_step_status (3, "bold", "ffffff", "646464");
			window.location.hash = "abe_step_3";
			break;
		default:
			break;
	}
}
// Removess history navigation BACK/FORWARD between STEPS 1, 2 & 3
function abe_clearStep () {	return; }

/* **************************************************************************************************** */
/*                                                                                                STEP1 */
// Populates currency & selects default currency
function abe_currency ()
{
	var o = abe_option ("currency");
	typeof (abePreselectedCurrency) == "undefined" ? null : abeCurrency = abePreselectedCurrency;
	for (i in abeCurrencies)
	{
		i.length == 3 ? abe_add_option ("currency", o.length, abeCurrencies [i], i) : null;
	}
	var i = new Number (0);
	while (o [i].value != abeCurrency)
	{
		i++;
	}
	o [i].selected = true;
	abe_disable ("currency", false);
}

/* **************************************************************************************************** */
/*                                                                                         STEP1 EVENTS */
// On country change
function abe_change_countryList ()
{
	var e = abe_ID ("countryList");
	// abort locations request ***************************************************************************
	e.options [0].text == abeAction ["select"] ? abe_rem_option ("countryList", 0) : null;
	abe_rem_list ("locationPickup");
	abe_rem_list ("locationDropoff");
	abeCountryID = e.value;
	abe_request ("locationPickup");
}
// On residence country change
function abe_change_residenceList ()
{
	abe_option ("residenceList") [0].text == abeAction ["select"] ? abe_rem_option ("residenceList", 0) : null;
}
// On pick up location change
function abe_change_locationPickup ()
{
	var e = abe_ID ("locationPickup");
	// abort drop off location request ***************************************************************************
	e.options [0].text == abeAction ["select"] ? abe_rem_option ("locationPickup", 0) : null;
	abe_rem_list ("locationDropoff");
	abePickup ["ID"] = e.value;
	abe_request ("locationDropoff");
}
// On search click
function abe_click_search ()
{
	//jmcjmcjmc
	//abe_reservationID="IE1000033050";	// with ThankYou message
	//abe_reservationID="IE1000035330";	// without  ThankYou message
	//abe_request ("reservationEmail");
	//return;

	if (!abe_ID ("residenceList").value.length)
	{
		alert ("Please select country of your residence");
		return;
	}
	if (!abe_ID ("locationPickup").value.length)
	{
		alert ("Please select the pick up location");
		return;
	}
	if (!abe_ID ("locationDropoff").value.length)
	{
		alert ("Please select the drop off location");
		return;
	}
	var up = "datePickup", off = "dateDropoff";
	// Gets pick up date
	abePickup ["day"] = abe_day (abePickup ["date"] = abe_ID (up + "_d").value, abePickup ["month"] = abe_ID (up + "_m").value, abePickup ["year"] = abe_ID (up + "_y").value);
	// Gets drop off date
	abeDropoff ["day"] = abe_day (abeDropoff ["date"] = abe_ID (off + "_d").value, abeDropoff ["month"] = abe_ID (off + "_m").value, abeDropoff ["year"] = abe_ID (off + "_y").value);

	//alert('abePickup ["date"] = ' + abePickup ["date"]);
	if(abePickup ["date"] > abe_get_days (abePickup ["month"], abePickup ["year"]))
	{
		alert ("The Dates are incorrect");
		return;
	}
	//alert('abeDropoff ["date"] = ' + abeDropoff ["date"]);
	if(abeDropoff ["date"] > abe_get_days (abeDropoff ["month"], abeDropoff ["year"]))
	{
		alert ("The Dates are incorrect");
		return;
	}

	var	pickupDate	 = new Date(abe_ID ("datePickup_y").value, abe_ID ("datePickup_m").value, abe_ID ("datePickup_d").value);
	var	dropOffDate	 = new Date(abe_ID ("dateDropoff_y").value, abe_ID ("dateDropoff_m").value, abe_ID ("dateDropoff_d").value);
	if(pickupDate > dropOffDate)
	{
		alert ("The Dates are incorrect");
		return;
	}

	abe_display ("quote", "none");
	abe_load ("search");

	up = "timePickup";
	off = "timeDropoff";

	// Gets pick up time
	abePickup ["hour"] = abe_ID (up + "_h").value;
	abePickup ["minute"] = abe_ID (up + "_m").value;
	// Gets drop off time
	abeDropoff ["hour"] = abe_ID (off + "_h").value;
	abeDropoff ["minute"] = abe_ID (off + "_m").value;

	abeDropoff ["ID"] = abe_ID ("locationDropoff").value;
	abeCurrency = abe_ID ("currency").value;

	// Sets currency symbol
	switch (abeCurrency)
	{
		case "EUR":
			o = "&euro;";
			break;
		case "USD":
			o = "$";
			break;
		case "GBP":
			o = "&pound;";
			break;
		default:
			o = abeCurrency;
			break;
	}
	abeCurrencySymbol = o;
	// Writes search details

	abe_inner_details (1, abeLocationArray [abePickup ["ID"]]["Name"], abeLocationArray [abeDropoff ["ID"]]["Name"]);
	abe_inner_details (2, abe_format_address (abePickup), abe_format_address (abeDropoff));
	abe_inner_details (3, abe_format_date (abePickup), abe_format_date (abeDropoff));
	abe_inner_details (4, abe_format_time (abePickup), abe_format_time (abeDropoff));

	abe_inner ("rental_currency", abeCurrencySymbol);
	abe_inner ("admin_currency", abeCurrencySymbol);
	abe_inner ("total_currency", abeCurrencySymbol);
	abe_inner ("deposit_currency", abeCurrencySymbol);
	abe_inner ("arrival_currency", abeCurrencySymbol);
	
	abeLocationArray [abePickup ["ID"]]["Airport"] ? abe_display ("airport", "block") : abe_display ("airport", "none");

	// Requests cars availability
	abe_request ("search");
}

function abe_search_disable (status)
{
	abe_ID ("search").disabled = status;
	var e = abe_ID ("search");
	e.style.color = status ? abeBG ["search_button"]["disable"] : abeBG ["search_button"]["enable"];
}

/* **************************************************************************************************** */
/*                                                                                                STEP2 */
// Sorts cars list by price
function abe_sort (a, b)
{
	return a ["Price"] - b ["Price"];
}


function abe_process_reservationEmail (response)
{//jmcjmcjmcjmc
	//abeClientName = '';
	//abeThankYouMessage = '';

	//return;

/*
	abe_inner ("clientName", "us");

	//alert('abe_process_reservationEmail');
	var listClientNames = response.getElementsByTagName ("Client");
	//abeClientName = listClientNames[0].firstChild.nodeValue;
	if(abeClientName.length>0)
	{
		abe_inner ("clientName", abeClientName);
	}

	//alert('clientname=' + abeClientName);
	var thankYouMessages = response.getElementsByTagName ("ThanksMessage");
	//alert('abeThankYouMessage = 1' + thankYouMessages[0]);
	//alert('abeThankYouMessage = 2' + thankYouMessages[0].firstChild);
	if(thankYouMessages[0].firstChild != null)
	{
		//alert('abeThankYouMessage = 3' + thankYouMessages[0].firstChild.nodeValue);
		abeThankYouMessage = thankYouMessages[0].firstChild.nodeValue
	}
*/
	//abe_inner ("thankYouMessage",'Sean Hendrickx<BR><BR>Ambassador Car Hire.<BR><BR>www.ambassadorcarhire.com  <BR>FOR THE LOWEST GUARANTEED CAR HIRE RATES IN THE WORLD.  <BR><BR>Now that you have found the best car hire rates around, please tell all your family, friends and colleagues.');
	//abe_inner ("thankYouMessage", abeThankYouMessage);

	//alert('abeThankYouMessage="' + abeThankYouMessage+'"');

}

// Opens rental conditions pop-up window
function abe_conditions (vendorCode, kCode, title)
{
	abeVendorCode = vendorCode;
	abeKCode = kCode;
	//open popup half of the screen
	window.open ("./conditions.html?vendorCode=" + abeVendorCode + "&carCode=" + abeKCode + "&title=" + title, "", "top=" + ((screen.height - 500) / 2) + ", left=" + ((screen.width - 700) / 2) + ", width=700, height=500, scrollbars=yes");
	//window.open ("./conditions.html?vendorCode=" + vendorCode + "&carCode=" + kCode + "&title=" + title, "", "top=" + ((screen.height - 500) / 2) + ", left=" + ((screen.width - 700) / 2) + ", width=700, height=500, scrollbars=yes");
}

// E-Mails requested quote
function abe_email_quote ()
{
	abe_display ("popup", "none");
	abe_ID ("popup").style.left = posx;
	abe_ID ("popup").style.top = posy;
	abe_display ("car_picture", "none");
	abe_display ("email_progress", "none");
	abe_display ("email_complete", "none");
	abe_display ("email_bar", "block");
	abe_display ("popup", "block");
}
// Populates available cars list & navigates to STEP 2
function abe_cars (list)
{
	var r, c;
	var up = new Date (abePickup ["year"] , abePickup ["month"] , abePickup ["date"] , abePickup ["hour"] , abePickup ["minute"] , "00");
	var off = new Date (abeDropoff ["year"] , abeDropoff ["month"] , abeDropoff ["date"] , abeDropoff ["hour"] , abeDropoff ["minute"] ,"00");
	var day = Math.ceil((off - up) / (24 * 60 * 60 * 1000));
	for (var i = new Number (0); i < list.length; i++)
	{
		r = abe_ID ("cars").insertRow (-1);
		typeof (abe_sColRowBg) == "undefined" ? null : abeBG ["row"] = "#" + abe_sColRowBg;
		typeof (abe_sColAltRowBg) == "undefined" ? null : abeBG ["row_alternative"] = "#" + abe_sColAltRowBg;
		r.style.backgroundColor = i % 2 ? abeBG ["row"] : abeBG ["row_alternative"];
		for (var j = new Number (0); j < 14; j++)
		{
			switch (j.valueOf ())
			{
				case 0:
					c = "company";
					break;
				case 1:
					c = "code";
					break;
				case 2:
					c = "name";
					break;
				case 9:
					c = "duration";
					break;
				case 10:
					c = "currency";
					break;
				case 11:
					c = "price";
					break;
				case 12:
					c = "email";
					break;
				case 13:
					c = "book";
					break;
				default:
					c = "default";
					break;
			}
			r.insertCell (-1);
			r.cells [r.cells.length - 1].className = "abe_cars_" + c;
		}
		with (r)
		{
			var companyName = list [i]["CompanyName"];
			cells [0].innerHTML = companyName.length ? "<img src=\"https://www.argusrentals.com/master/GetImage.asp?action=caragent&id=" + list [i]["VendorImgCode"] + "\" title=\"" + companyName + "\">" : "&nbsp;";
			cells [1].innerHTML = list [i]["Code"];
			cells [2].innerHTML = abeCarPictures ? "<span onmouseover=\"this.style.cursor='pointer'; this.style.textDecoration='underline';\" onmouseout=\"this.style.textDecoration='none';\" onclick=\"abe_mousePosition (event); abe_similar_cars ('" + list [i]["Code"] + "', " + i + ");\">" + list [i]["Name"] + "</span>" : list [i]["Name"];
			cells [3].innerHTML = "<img onclick=\"abe_conditions ('" + list [i]["VendorCode"] + "','" + list [i]["Code"] + "');\" src=\"/common/abe/image/icon/conditions.gif\" width=\"18\" height=\"18\" title=\"Rental Conditions\" style=\"cursor:pointer;\">";
			cells [4].innerHTML = list [i]["AirCondition"] == "true" ? "<img src=\"/common/abe/image/icon/aircondition.gif\" width=\"16\" height=\"16\" title=\"Air Conditioning\">" : "&nbsp;";
			cells [5].innerHTML = list [i]["Transmission"] == "Automatic" ? "<img src=\"/common/abe/image/icon/transmission.gif\" width=\"16\" height=\"16\" title=\"Automatic Vehicle\">" : "&nbsp;";
			cells [6].innerHTML = list [i]["Fuel"] == "Diesel" ? "<img src=\"/common/abe/image/icon/fuel.gif\" width=\"16\" height=\"16\" title=\"Diesel Vehicle\">" : "&nbsp;";
			c = list [i]["Passenger"];
			cells [7].innerHTML = parseInt (c, 10) ? "<img src=\"/common/abe/image/icon/passenger.gif\" width=\"16\" height=\"16\" title=\"Passengers Quantity\"><br>" + c : "&nbsp;";
			c = list [i]["Baggage"];
			cells [8].innerHTML = parseInt (c, 10) ? "<img src=\"/common/abe/image/icon/baggage.gif\" width=\"16\" height=\"16\" title=\"Baggage Quantity\"><br>" + c : "&nbsp;";
			c = "&nbsp;days";
			// *********************************************************Number (d.charAt (-1)) == 1 ? t += "s" : null;
			//alert (d.toString ().charAt (d.toString ().length - 1));
			cells [9].innerHTML = day + c;
			cells [10].innerHTML = abeCurrencySymbol;
			cells [11].innerHTML = list [i]["Price"];
			cells [12].innerHTML = "<img onclick=\"abe_mousePosition (event); abe_email_quote ();\" src=\"/common/abe/image/icon/email.gif\" width=\"32\" height=\"16\" title=\"E-Mail Quote\">";
			cells [13].innerHTML = "<input onclick=\"step3 (" + i + ");\" type=\"button\" value=\"BOOK\" title=\"Click to Book Car\" class=\"abe_cars_book_button\">";
		}
	}
	abe_inner ("duration", day + c);
	dhtmlHistory.add ("reserve");
	abe_selectStep ("reserve");
	abe_load ();
}









/* ******************** RUBISH *********************************** */
function MM_showHideLayers (age)
{
	abeAge = age;
	abe_ID ("agegroup").style.visibility = abeAge != 30 ? "visible" : "hidden";
}


//Forwards to Step3 of the booking process,
//called by the 'book' button being pressed on the Step 2 page.
function step3 (i)
{

//var specialEquipment = new Array();

	// ******************************************************* RUBISH
	abeVendorCode =  car [i]["VendorCode"];
	abeKCode = car [i]["Code"];
	//alert('abeVendorCode = ' + abeVendorCode);
	//alert('abeKCode = ' + abeKCode);
	reference = '<Reference Type="' + car [i]["Reference"]["Type"] + '" ID="' + car [i]["Reference"]["ID"] + '" ID_Context="' + car [i]["Reference"]["ID_Context"] + '" DateTime="' + car [i]["Reference"]["DateTime"] + '" />';
var optionaExtras = abe_ID ("optionalExtras");
//Initilise the list of optional Extras.
while (optionaExtras.rows.length > 0)
{
	optionaExtras.deleteRow(0);
}

var equipmentIndex = 0;
for (p in car [i]["Equipment"])
{
	if (p.indexOf ("array") == -1)
	{
		var newRow = optionaExtras.insertRow (-1);
		var cell1 = newRow.insertCell (-1);
		var type = car [i]["Equipment"][p]["Type"];
		var id = "abe_se_" + type;

		cell1.innerHTML = '<select onchange="selectPricedEquip (' + equipmentIndex + ',' + type + ');" id="' + id + '" class=\"abe_form_month\">' +
                              '<option selected="selected" value="0">No</option>' +
                              '<option value="' + type + '">Yes</option>' +
                            '</select>';

		specialEquipment[equipmentIndex] = 0;
		equipmentIndex++;

		var cell2 = newRow.insertCell (-1);
		cell2.className = "abe_duration";
		cell2.innerHTML = p;
		var cell3 = newRow.insertCell (-1);
		cell3.innerHTML = abeCurrencySymbol;
		var cell4 = newRow.insertCell (-1);
		cell4.className = "abe_price";
		cell4.innerHTML = car [i]["Equipment"][p]["Price"];
	}
}

	
	abe_inner ("rental", Number (car [i]["Price"]).toFixed(2));
	abe_inner ("admin", Number (car [i]["Fee"][6]["Price"]).toFixed(2));
	abe_inner ("total", Number (car [i]["TotalPrice"]).toFixed(2));
	abe_inner ("deposit", Number (car [i]["Fee"]["22"]["Price"]).toFixed(2));
	abe_inner ("arrival", Number (car [i]["Fee"]["23"]["Price"]).toFixed(2));
	
	abe_inner ("customerCountry", abe_ID ("residenceList").options [abe_ID ("residenceList").options.selectedIndex].text);
	dhtmlHistory.add ("confirm");
	abe_selectStep ("confirm");
}

var email;

function isValidData(sText,sValidChars)
{
	var char;
	for (var i = 0; i < sText.length; i++)
	{
		char = sText.charAt(i);
    if(sValidChars.indexOf(char) == -1)
		{
			return false;
		}
	}
	return true;
}

function isValidPhone(sText)
{
	return isValidData(sText,"0123456789.+- ");
}

function isAlphaNumeric(val)
{
	if (val.match(/^[a-zA-Z0-9]+$/))
	{
		return true;
	}
	else
	{
		return false;
	}
}

//Method to make a Car Reservation using the OTA_VehRes message.
//It first does some basic validation of the information entered to make
//sure all mandatory information is present.
function abe_doOTA_VehRes()
{
	if((reference==null) || (reference.length==0))
	{
		alert ("Error, you must select a Quote from the availability first");
		return;
	}

	var firstname = abe_ID ("firstname").value;
	var surname = abe_ID ("surname").value;
	var address1 = abe_ID ("address_1").value;
	var address2 = abe_ID ("address_2").value;
	
	var phoneNo = abe_ID ("phone").value;
	var mobilePhoneNo = abe_ID ("mobile").value;
	email =  abe_ID ("customerEmail").value;
	var confirmEmail = abe_ID ("customerEmail_confirm").value;

	var airline = abe_ID ("airline").value;
	var flightNo = abe_ID ("flight").value;

	var cardNumber = abe_ID ("card_number").value;
	var cardName = abe_ID ("card_name").value;
	var cvn = abe_ID ("card_cvn").value;

	var customerCountry = abe_ID ("residenceList").value;
	var cardTypeControl = abe_ID ("card_type").value;
	var expiryMonthControl = abe_ID ("expiry_month").value;
	var expiryYearControl = abe_ID ("expiry_year").value;

	if (!isNaN (firstname))
	{
		alert ("Please enter valid first name");
		return;
	}

	if (!isNaN (surname))
	{
		alert ("Please enter valid surname");
		return;
	}

	if (!abeAge)
	{
		alert ("Please select age group");
		return;
	}

	if (abeAge != 30 && !abe_ID ("ageconditions").checked)
	{
		alert ("Please check the tickbox to confirm that you have read, understood and agree with the Age Rental Conditions provided");
		return;
	}

	if (address1.length == 0)
	{
		alert("Address is Mandatory");
		return;
	}
	var addressLine = address1;
	if (address2.length > 0)
	{
		addressLine += " ";
		addressLine += address2;
	}

	if (phoneNo.length != 0)
	{
		if(!isValidPhone(phoneNo))
		{
			alert ("Phone number is invalid");
			return;
		}
	}
	if (mobilePhoneNo.length!=0)
	{
		if(!isValidPhone(mobilePhoneNo))
		{
			alert ("Mobile Phone number is invalid");
			return;
		}
	}

	if (email.length==0)
	{
		alert ("Email is Mandatory");
		return;
	}
	if (email.indexOf ("@") == -1 || email.indexOf (".") == -1)
	{
		alert ("Please enter valid email");
		return;
	}

	if (abeLocationArray [abePickup ["ID"]]["Airport"])
	{
		if (!airline.length)
		{
			alert ("Airline is Mandatory");
			return;
		}
		if (flightNo.length == 0)
		{
			alert ("Flight Number is Mandatory");
			return;
		}
		if(!isAlphaNumeric(flightNo))
		{
			alert ("Flight number must be numeric or alphabetic");
			return;
		}
	}

	if (!cardTypeControl.length)
	{
		alert ("Credit Card Type is Mandatory");
		return;
	}
	if((cardNumber.length==0) || (cardName.length==0) || (cvn.length==0)) {
		alert ("Credit Card Number, Holder, Expiry Date, CVN are Mandatory");
		return;
	}

	if (isNaN (cardNumber))
	{
		alert ("Please enter valid credit card number");
		return;
	}

	if (!isNaN (cardName))
	{
		alert ("Please enter valid credit card holder");
		return;
	}

	if (!Number (expiryMonthControl) || !Number (expiryYearControl))
	{
		alert ("Expiry Date is Mandatory");
		return;
	}
	var expireDate = expiryMonthControl + expiryYearControl;

	if (isNaN (cvn))
	{
		alert ("Please enter valid credit card verification number");
		return;
	}

	if (!abe_ID ("conditions").checked)
	{
		alert ("Please check the tickbox to confirm that you have read, understood and agree with the Rental Conditions provided");
		return;
	}
	
	if (email != confirmEmail)
	{
		alert ("E-Mail and Confirmation E-Mail do not match");
		return;
	}
	
	abe_ID ("confirm_button").disabled = true;
	abe_display ("confirm", "none");
	window.location.hash = "abe_step_3";
	abe_display ("load", "block");
	abe_load ("car_reservation");
	var request = getOTA_VehResRQXML (abeCurrency, firstname, surname, addressLine, customerCountry, cardTypeControl, cardNumber, expireDate, cvn, cardName, abeAge, email, phoneNo, mobilePhoneNo, flightNo, airline)

	//alert(request);
	abe_create1 ();
	abeXMLHttp1.onreadystatechange = receivedMakeReservation;

	with (abeXMLHttp1)
	{
		open ("POST", abeURL, true);
		setRequestHeader ("Content_Type", "text/xml");
		send (request);
	}
}

var abe_reservationID;
var vendorName;
var vendorAddress;

// Step4
function step4 ()
{
	//alert('clientname='+abe_ID ("sClientName").text);

	//abe_inner ("thankYouMessage",'Sean Hendrickx<BR><BR>Ambassador Car Hire.<BR><BR>www.ambassadorcarhire.com  <BR>FOR THE LOWEST GUARANTEED CAR HIRE RATES IN THE WORLD.  <BR><BR>Now that you have found the best car hire rates around, please tell all your family, friends and colleagues.');
	typeof (abeThankYouMessage) == "undefined" ? null : abe_inner ("thankYouMessage", abeThankYouMessage);

	abe_request ("reservationEmail");

	abe_inner ("reservationID", abe_reservationID);
	abe_inner ("email", email);
	abe_inner ("vendorName", vendorName);
	abe_inner ("vendorAddress", vendorAddress);

	abe_inner ("clientName", "us");
	if (typeof (abeClientName) != "undefined" && abeClientName.length)
	{
		abe_inner ("clientName", abeClientName);
	}

	abe_inner ("reservationLink", "http://www.cartrawler.com/reserve/html_voucher.asp?resid=" + abe_reservationID);
	abe_ID ("reservationLink").href = "http://www.cartrawler.com/reserve/html_voucher.asp?resid=" + abe_reservationID;
	abe_ID ("homeLink").href = abeCountryArray ["Homepage"];
	abe_display ("confirm", "none");
	abe_load ();
	abe_display ("reference", "block");
	abe_display ("steps", "none");
	window.history.forward (1);
	dhtmlHistory.addListener (abe_clearStep);
}

//Ajax callback method called when we receive the response
//from the OTA_VehRes message.
function receivedMakeReservation()
{
	if (abeXMLHttp1.readyState == 4)
	{

		var error = "Error Making Reservation";

		var response = abeXMLHttp1.responseXML;
		if(response==null)
		{
			alert ("SORRY,\nINTERNET CONNECTION LOSS!\nPlease try again or refresh the page.");
			abe_load ();
			abe_ID ("confirm_button").disabled = false;
			abe_display ("confirm", "inline");
			return;
		}

		// get the XML root item
		var root = response.getElementsByTagName("OTA_VehResRS")[0];
		if(root==null)
		{
			alert ("SORRY,\nINTERNET CONNECTION LOSS!\nPlease try again or refresh the page.");
			abe_load ();
			abe_ID ("confirm_button").disabled = false;
			abe_display ("confirm", "inline");
			return;
		}

		var	successElement = root.getElementsByTagName("Success")[0];
		if(successElement != null)
		{
			//Got a successfull response
			var confId = root.getElementsByTagName("ConfID")[0];
			if(confId != null)
			{
				abe_reservationID = confId.getAttribute ("ID");
				var vendor = root.getElementsByTagName("Vendor")[0];
				vendorAddress = root.getElementsByTagName("AddressLine")[0].firstChild.nodeValue;
				if (vendor != null)
				{
					vendorName = vendor.getAttribute ("CompanyShortName");
					step4 ();
				}
			}
			return;
		}
		else
		{
			if (response.getElementsByTagName ("Error").length)
			{
				var error = response.getElementsByTagName ("Error") [0].getAttribute ("Type");
				//var error = new Array ();
				//error [response.getElementsByTagName ("Error") [0].getAttribute ("Type")] = response.getElementsByTagName ("Error") [0].firstChild.nodeValue;
				var msg = "SORRY,\nCAN NOT PROCESS ";
				switch  (error)
				{
					case "189":
						msg += "CREDIT CARD.\nPayment not authorised";
						break;
					case "240":
						msg += "CREDIT CARD.\nCredit card has expired";
						break;
					case "365":
						msg += "CREDIT CARD.";
						break;
					case "1":
						msg += "RESERVATION.\n";
						msg += response.getElementsByTagName ("Error") [0].getAttribute ("ShortText");
						break;
					default:
						msg += "RESERVATION.";
						break;
				}
				alert (msg);
				abe_load();
				abe_ID ("confirm_button").disabled = false;
				abe_display ("confirm", "inline");
				return;
			}
			abe_ID ("confirm_button").disabled = false;
			abe_display ("confirm", "inline");
		}
		alert ("SORRY,\nINTERNET CONNECTION LOSS!\nPlease try again or refresh the page.");
		abe_load ();
		abe_ID ("confirm_button").disabled = false;
		abe_display ("confirm", "inline");
		return;
	}
}

//Creates XML Request to do a Vehicle Reservation.
function getOTA_VehResRQXML(currency,
givenName,surname,
addressLine,countryId,
cardCode,cardNumber,
expireDate,seriesCode,cardHolderName,age,
email, phonenumber, mobile,
flightNo,airline)
{
	var request = '<?xml version="1.0" encoding="UTF-8"?>'+
		'<OTA_VehResRQ '+
		 'xmlns="http://www.opentravel.org/OTA/2003/05" '+
		 'xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" '+
		 'xsi:schemaLocation="http://www.opentravel.org/OTA/2003/05 OTA_VehResRQ.xsd" '+
		 'Target="'+abeTarget+'" '+
		 'Version="1.005"> '+
		 '<POS>';
	if(currency==null)
	{
		request += '<Source>';
	}
	else
	{
		request += '<Source ISOCurrency="'+abeCurrency+'">';
	}
	var up = abePickup, off = abeDropoff;
	request += '<RequestorID Type="16" ID="' + abeClientID + '" ID_Context="CARTRAWLER" />'+
		 '</Source>'+
		 '</POS>'+
		 '<VehResRQCore Status="All">'+
		 '<VehRentalCore PickUpDateTime="' + up ["year"] + '-' + abe_zero (Number (up ["month"]) + 1) + '-' + up ["date"] + 'T' + up ["hour"] + ':' + up ["minute"] + ':00" ReturnDateTime="' + off ["year"] + '-' + abe_zero (Number (off ["month"]) + 1) + '-' + off ["date"] + 'T' + off ["hour"] + ':' + off ["minute"] +':00">'+
		 	'<PickUpLocation CodeContext="CARTRAWLER" LocationCode="' + up ["ID"] + '" />' +
			'<ReturnLocation CodeContext="CARTRAWLER" LocationCode="' + off ["ID"] + '" />' +
		 '</VehRentalCore>'+
		 '<Customer>'+
		 '<Primary>'+
		 '<PersonName>'+
		 '<GivenName>'+givenName+'</GivenName>'+
		 '<Surname>'+surname+'</Surname>'+
		 '</PersonName>';
	if(phonenumber.length>0)
	{
		request += '<Telephone PhoneTechType="1" PhoneNumber="'+phonenumber+'"/>';
	}
	if(mobile.length>0)
	{
		request += '<Telephone PhoneTechType="5" PhoneNumber="'+mobile+'"/>';
	}
	request += '<Email EmailType="2">'+email+'</Email>'+
		 '<Address Type="2">'+
		 '<AddressLine>'+addressLine+'</AddressLine>'+
		 '<CountryName Code="'+abe_ID ("residenceList").value+'" />'+
		 '</Address>'+
		 '</Primary>'+
		 '</Customer>'+
		 '<DriverType Age="'+abeAge+'"/>';

	var countSpecialEquipment = 0;
	for(var i=0;i<specialEquipment.length;i++)
	{
		var equipCode = specialEquipment[i];
		if(equipCode > 0)
		{
			countSpecialEquipment++;
		}
	}
	//alert('countSpecialEquipment = ' + countSpecialEquipment);
	if(countSpecialEquipment>0)
	{
		request+='<SpecialEquipPrefs>';
		for(var i=0;i<specialEquipment.length;i++)
		{
			var equipCode = specialEquipment[i];
			if(equipCode > 0)
			{
				request+='<SpecialEquipPref EquipType="' + equipCode + '" Quantity="1"/>';
			}
		}
		request+='</SpecialEquipPrefs>';
	}

	request += '</VehResRQCore>';
	request += '<VehResRQInfo>';


	if(abeLocationArray [abePickup ["ID"]]["Airport"])
	{
		request+='<ArrivalDetails TransportationCode="14" Number="'+flightNo+'">'+
//'<OperatingCompany CompanyShortName="EI">'+airline+'</OperatingCompany>'+
		 '<OperatingCompany >'+airline+'</OperatingCompany>'+
		 '</ArrivalDetails>';
	}

	request+='<RentalPaymentPref>'+
		 '<PaymentCard CardType="1" CardCode="'+cardCode+'" CardNumber="'+cardNumber+'" ExpireDate="'+expireDate+'" SeriesCode="'+seriesCode+'">'+
		 '<CardHolderName>'+cardHolderName+'</CardHolderName>'+
		 '</PaymentCard>'+
		 '</RentalPaymentPref>'+
		 reference +
		 '</VehResRQInfo>'+
		 '</OTA_VehResRQ>';

	return request;
}

// Popup windows positioning
function abe_mousePosition (e)
{
	abe_X = e.clientX + document.body.scrollLeft + 25 + "px";
	abe_Y = e.clientY + document.body.scrollTop + 5 + "px";
}


//Called when the user selects/unselects some special equipment.
function selectPricedEquip(seIndex, spId)
{
	var id = "abe_se_" + spId;

	//alert('selectPricedEquip : seIndex=' + seIndex + ', id='+id);
	var priceEquipControl = document.getElementById(id);
	var pec_id = (priceEquipControl.options[priceEquipControl.selectedIndex].value);

	if( (seIndex >= 0) && (seIndex < specialEquipment.length) )
	{
		specialEquipment[seIndex] = pec_id;
		//alert('Setting value : ' + pec_id);
	}
	//else
	//{
	// 	alert('specialEquipment.length='+specialEquipment.length);
	//}
}



/* **************************************************************************************************** */
/*                                                                   CONFIGURING ABE & ACTIVATING STEP1 */
// Preloads data, assigns hover tips, activates STEP1
function abe_configure ()
{
	try
	{
		new XMLHttpRequest ();
	}
	catch (e)
	{
		try
		{
			new ActiveXObject ("Microsoft.XMLHTTP");
		}
		catch (e)
		{
			abe_load ();
			abe_inner ("load_wait", abeAction ["ActiveX_note"]);
			abe_inner ("load_action",abeAction ["ActiveX_support"]);
			abe_inner ("load_process", abeAction ["ActiveX_enable"]);
			abe_inner ("load_url", abeAction ["ActiveX_url"]);
			abe_display ("load" ,"block");
			return;
		}
	}
	abe_parseQueryString ();
	abe_search_disable (false);
	// Populates country list & preselected country, pick up and drop off locations
	abe_request ("countryList");
	// Populates date and time & preselected offset
	abe_date ();
	abe_time ();
	abe_calendar ();
	// Populates currency & preselected currency
	abe_currency ();
	// Assigns titles to elements
	abe_tip ("countryList");
	abe_tip ("residenceList");
	abe_tip ("locationPickup");
	abe_tip ("locationDropoff");
	abe_tip ("datePickup_d");
	abe_tip ("datePickup_m");
	abe_tip ("datePickup_y");
	abe_tip ("dateDropoff_d");
	abe_tip ("dateDropoff_m");
	abe_tip ("dateDropoff_y");
	abe_tip ("calendarPickup_button");
	abe_tip ("calendarDropoff_button");
	abe_tip ("timePickup_h");
	abe_tip ("timePickup_m");
	abe_tip ("timeDropoff_h");
	abe_tip ("timeDropoff_m");
	abe_tip ("currency");
	abe_tip ("search");
	abe_tip ("confirm_button");
	// Adds events to elements
	abe_onchange ("countryList");
	abe_onchange ("residenceList");
	abe_onchange ("locationPickup");
	abe_onchange ("datePickup_d");
	abe_onchange ("datePickup_m");
	abe_onchange ("dateDropoff_d");
	abe_onchange ("dateDropoff_m");
	abe_onchange ("datePickup_y");
	abe_onchange ("dateDropoff_y");
	abe_onchange ("timePickup_h");
	abe_onchange ("timePickup_m");
	abe_onclick ("calendarPickup_button");
	abe_onclick ("calendarDropoff_button");
	abe_onclick ("search");

	abe_visible ("agegroup");
	
	/* RUBBISH */
	abe_inner ("popup_car_similar", abeText ["popUp"]["similar_cars"]);
	abe_inner ("popup_car_description", abeText ["popUp"]["car_desription"]);
	abe_add_option ("expiry_year", 0, "");
	abe_add_option ("expiry_month", 0, "");
	for (var i = new Number (0); i < 7; i++)
	{
		abe_add_option ("expiry_year", i + 1, 2006 + i, abe_zero (6 + i));
	}
	for (i = 0; i < abeMonth.length; i++)
	{
		abe_add_option ("expiry_month", i + 1, abeDate ["month_short_name"] ? abeMonth [i].slice (0, 3) : abeMonth [i], abe_zero (i + 1));
	}
	abePaymentCarTrawler ? null : abe_visible ("payment");
	
	
	/* ********************************************************************************************************** */
	// Adds STEP1 history
	document.all ? abe_ID ("iframe").src = "./blank.html" : null;
	with (dhtmlHistory)
	{
		initialize ();
		//isFirstLoad () ? dhtmlHistory.add ("quote") : null;
		dhtmlHistory.add ("quote");
		addListener (abe_selectStep);
	}
	/* *** */

	// Activates STEP1
	abe_selectStep ("quote");
	abe_load ();
}

// Checks existings of all elements
// onSuccess - configures ABE, loads data
// onFail - aborts loading, displays error [missing element]
function abe_generate ()
{
	abe_exist ("default") &&
	abe_exist ("load") &&
	abe_exist ("step_1") &&
	abe_exist ("step_2") &&
	abe_exist ("step_3") &&
	abe_exist ("quote") &&
	abe_exist ("countryList") &&
	abe_exist ("locationPickup") &&
	abe_exist ("locationDropoff") &&
	abe_exist ("datePickup_d") &&
	abe_exist ("datePickup_m") &&
	abe_exist ("datePickup_y") &&
	abe_exist ("dateDropoff_d") &&
	abe_exist ("dateDropoff_m") &&
	abe_exist ("dateDropoff_y") &&
	abe_exist ("calendarPickup_button") &&
	abe_exist ("calendarDropoff_button") &&
	//abe_exist ("calendarPickup") &&
	//abe_exist ("calendarDropoff") &&
	//abe_exist ("calendarPickup_navigation") &&
	//abe_exist ("calendarDropoff_navigation") &&
	//abe_exist ("calendarPickup_close") &&
	//abe_exist ("calendarDropoff_close") &&
	//abe_exist ("calendarPickup_dates") &&
	//abe_exist ("calendarDropoff_dates") &&
	//abe_exist ("calendarPickup_today") &&
	//abe_exist ("calendarDropoff_today") &&
	abe_exist ("timePickup_h") &&
	abe_exist ("timePickup_m") &&
	abe_exist ("timeDropoff_h") &&
	abe_exist ("timeDropoff_m") &&
	abe_exist ("currency") &&
	abe_exist ("residenceList") &&
	abe_exist ("search") &&
	abe_exist ("details") &&
	abe_exist ("countryConditions") &&
	abe_exist ("legend") &&
	abe_exist ("cars") &&
	abe_exist ("confirm") &&
	abe_exist ("confirm_button") &&
	abe_exist ("reference")
	? abe_configure () : null;
	// ***************************** add steps 4 tables
}
