var durationVARIABLE;
function validityF(str)
{
	document.getElementById(str).style.border="none"; 
	//document.getElementById("validity").innerHTML ="<br>";
}
function reload()
{
	var overnightO = document.getElementById('ArrivalHour'); 
	var driversO = document.getElementById('AdditionalDrivers');
	var firstChildO = document.getElementById('child1');
	var secondChildO = document.getElementById('child2');
	var gpsO = document.getElementById('agps');
	var pickupOptionO = document.getElementsByName('PickupOption');
	var departureOptionO = document.getElementsByName('DepartureOption');
	var pickupOptionSelectedO; 
	var departureOptionSelectedO;

	for(i=0; i< pickupOptionO.length; i++)
	{
		if(pickupOptionO[i].checked)
			pickupOptionSelectedO = pickupOptionO[i].value;
	}
	for(i=0; i< departureOptionO.length; i++)
	{
		if(departureOptionO[i].checked)
			departureOptionSelectedO = departureOptionO[i].value;
	}

	duration(); 
	overnight(overnightO);
	drivers(driversO.value);
	firstchild(firstChildO.checked);
	secondchild(secondChildO.checked);
	gps(gpsO.checked);
	changeTo(pickupOptionSelectedO);
	DchangeTo(departureOptionSelectedO);
	//ToolTip.initByTitle();
}

function submitForm(){

	var validityMsg = document.getElementById("validity");

	var arrival = document.getElementById("PickupDate");
	var arrivaltd = document.getElementById("test");
	var depart = document.getElementById("DepartureDate");
	var departtd = document.getElementById("test2");
	var arrivalAirport = document.getElementById("arrivalAirportTxt");
	var arrivalAirportL = document.getElementById("arrivalAirporttd");
	var departureAirport = document.getElementById("departureAirportTxt");
	var departureAirportL = document.getElementById("departureAirporttd");
	var arrivalFlightNum = document.getElementById("ArrivalFlightNumber");

	var pickupOption = document.getElementsByName("PickupOption");
	var departureOption = document.getElementsByName("DepartureOption");

	var arrivalPlace = document.getElementById("pickupHotelTxt");
	var arrivalPlacetd = document.getElementById("pickupHoteltd");
	var departurePlace = document.getElementById("dropoffHotelTxt");
	var departurePlacetd = document.getElementById("departureHoteltd");

	for(i=0; i< pickupOption.length; i++)
	{
		if(pickupOption[i].checked)
			pickupOptionSelected = pickupOption[i].value;
	}

	for(i=0; i< departureOption.length; i++)
	{
		if(departureOption[i].checked)
			departureOptionSelected = departureOption[i].value;
	}

	if(arrival.value == "dd/mm/yyyy"){
		window.scrollTo(0,0);
		arrivaltd.style.border = "3px solid red";
		validityMsg.innerHTML = "Please enter pick-up date.";
		return true;
	}
	if(depart.value == "dd/mm/yyyy"){
		window.scrollTo(0,0);
		departtd.style.border = "3px solid red";
		validityMsg.innerHTML = "Please enter drop-off date.";
		return true;
	} 

	//some parsing to get the date from format xx/xx/xx 
	var arr = arrival.value;
	arr = arr.replace(/(\d+).(\d+).(\d+)/, "$3/$2/$1");
    arr = arr.replace(/^(\d\d\/)/, "20$1");
    
	arrD = new Date(arr);	//arrival date
   
    var dep = depart.value;
    dep = dep.replace(/(\d+).(\d+).(\d+)/, "$3/$2/$1");
    dep = dep.replace(/^(\d\d\/)/, "20$1");
    
	depD = new Date(dep); //departure date
   
	var one_day = 1000*60*60*24;
	var plusone = Number(checkHours());
		
	var duration = Math.round((depD.getTime()-arrD.getTime())/one_day);	
	duration = duration + plusone;
	
	var startMonth = arrD.getMonth()+1;
	var startDay = arrD.getDate();
	var startYear = arrD.getYear();
	var endMonth = depD.getMonth()+1;
	var endDay = depD.getDate();
	var endYear = depD.getYear();
	/*
	var call= "findduration.php?group=" + group + "&startDay=" + startDay + "&startMonth=" + startMonth + "&startYear=" + startYear + "&endDay=" + endDay + "&endMonth=" + endMonth + "&endYear=" + endYear;
	
	
	ajaxGetDuration(call);
	
	var durationdd = document.getElementById('duration');
	var duration = durationdd.innerHTML;
	duration = Number(duration) + Number(plusone);
	*/
	if(duration < min_duration)
		return true;
	
	if((pickupOptionSelected == "airport") && (arrivalAirport.value != "Larnaka")
		&& (arrivalAirport.value != "Paphos"))
	{
		window.scrollTo(0,0);
		arrivalAirportL.style.border = "3px solid red";
		validityMsg.innerHTML = "Please select arrival airport.";
		return true;
	}

	if((departureOptionSelected == "airport") && (departureAirport.value != "Larnaka")
		&& (departureAirport.value != "Paphos"))
	{
		window.scrollTo(0,0);
		departureAirportL.style.border = "3px solid red";
		validityMsg.innerHTML = "Please select departure airport.";
		return true;
	}

	if((pickupOptionSelected == "hotel") && (arrivalPlace.value.length < 1))
	{
		window.scrollTo(0,0);
		arrivalPlacetd.style.border = "3px solid red";
		validityMsg.innerHTML = "Please enter pick-up hotel/town.";
		return true;
	}
	
	if((departureOptionSelected == "hotel") && (departurePlace.value.length < 1))
	{
		window.scrollTo(0,0);
		departurePlacetd.style.border = "3px solid red";
		validityMsg.innerHTML = "Please enter drop-off hotel/town.";
		return true;
	}
	document.myform.submit();
}

//function total() calculates the total cost of the booking request.
//the validity of total value will be cross-checked with the 
//server-side validity checker.
var durationPrice;
function total()
{
	durationPrice = document.getElementById('durationr').innerHTML;
	var driverPrice = document.getElementById('driverr').innerHTML;
	//var petrolPrice = Number(document.getElementById('petrolr').innerHTML);
	var childPrice = Number(document.getElementById('sndchildseatr').innerHTML);
	var overnight = Number(document.getElementById('overnightr').innerHTML);
	var gps = Number(document.getElementById('gpss').innerHTML);
	
	if(durationPrice == '---.--')
		durationPrice = Number(0);	
	else
		durationPrice = Number(durationPrice);	
		
	if(driverPrice == 'free')
		driverPrice = Number(0);	
	else
		driverPrice = Number(driverPrice);
		

    var totalPrice = durationPrice + driverPrice + childPrice + overnight + gps;
	var totalr = document.getElementById('totalr');
	totalr.innerHTML = "<b>"+totalPrice.toFixed(2)+"</b>";
}

//checkHour() implements the +4 hour difference rule which states:
//if the difference of hours is +4, then an extra day applies.
function checkHours()
{
	arrivalHour = document.getElementById('ArrivalHour').value;
	departHour = document.getElementById('DepartureHour').value;
	overnightd = document.getElementById('overnight');
	if(arrivalHour == "12 noon")
		arrivalHour = "12";
	arrivalHour = Number(arrivalHour);

	if(departHour == "12 noon")
		departHour = "12";
	departHour = Number(departHour);

	diff = departHour - arrivalHour;
	if(diff > hour_difference)
		return 1;
	else
		return 0;
}

//function overnight(o) implements the overnight rule which states:
//For any pickup time after midnight and before morning, there is an extra charge.
function overnight(o)
{
	var overnightd = document.getElementById('overnight');
	var overnightr = document.getElementById('overnightr');
	
	if(Number(o.value) < midnight_Hours){
		overnightd.innerHTML = ": Midnight charge";
		overnightr.innerHTML = midnight_charge.toFixed(2);
	}
	else{
		overnightd.innerHTML = "";
		overnightr.innerHTML = "";
	}
	total();
}


//function duration2() identical with duration() (see below)
//there is a technical difficulty which requires a second duration() function.
function duration2()
{	
	var arrival = document.getElementById("PickupDate");
	var depart = document.getElementById("DepartureDate");
	
	var arr = arrival.value;
	arr = arr.replace(/(\d+).(\d+).(\d+)/, "$3/$2/$1");
    arr = arr.replace(/^(\d\d\/)/, "20$1");
    arrD = new Date(arr);
   
    var dep = depart.value;
    dep = dep.replace(/(\d+).(\d+).(\d+)/, "$3/$2/$1");
    dep = dep.replace(/^(\d\d\/)/, "20$1");
    depD = new Date(dep);
   
	var one_day = 1000*60*60*24;
	var plusone = Number(checkHours());
		
	var duration = Math.round((depD.getTime()-arrD.getTime())/one_day);	
	duration = duration + plusone;	
	
	
	var startMonth = arrD.getMonth()+1;
	var startDay = arrD.getDate();
	var startYear = arrD.getYear();
	var endMonth = depD.getMonth()+1;
	var endDay = depD.getDate();
	var endYear = depD.getYear();
	/*
	var call= "findduration.php?startDay=" + startDay + "&startMonth=" + startMonth + "&startYear=" + startYear + "&endDay=" + endDay + "&endMonth=" + endMonth + "&endYear=" + endYear;
	
	
	ajaxGetDuration(call);
	
	var durationdd = document.getElementById('duration');
	var duration = durationdd.innerHTML;
	duration = Number(duration) + Number(plusone);
	*/
	if(Number(duration) < min_duration || isNaN(duration))
		;
	else{
		
		var call = "price.php?group=" + group + "&startDay=" + startDay + "&startMonth=" + startMonth + "&endDay=" + endDay + "&endMonth=" + endMonth + "&duration=" + duration;
		ajaxGetPrice(duration,call); //make AJAX call here
	}

	var durationr = document.getElementById('durationr');
	var durationd = document.getElementById('duration'); 
	var validityd = document.getElementById('validity');
	
	if(duration < min_duration && duration >= 0){
		durationd.innerHTML = ": Minimum "+min_duration+" days.";
		durationr.innerHTML = "---.--";
		validityd.innerHTML = "<font color=red size=2.5><b>*Please select another date. Minimum car rental period is "+min_duration+" days.</b></font>";
		total();
	}
	if(duration < 0)
	{
		durationd.innerHTML = ": Invalid date.";
		durationr.innerHTML = "---.--";
		validityd.innerHTML = "<font color=red size=2.5><b>*Please select another date. Pickup and drop-off dates do not match.</b></font>";
		total();
	}	
}
//the duration() function will calculate the duration of the request:
//1) create two date() objects from pickup date and departure date.
//2) add a day if the checkHours() function says so.
//3) make AJAX call to get the price from the database given duration and rental periods
//4) update fields 
function duration()
{
	var arrival = document.getElementById("PickupDate");
	var depart = document.getElementById("DepartureDate");
	validityF("test");
	validityF("test2");
	//some parsing to get the date from format xx/xx/xx 
	var arr = arrival.value;
	arr = arr.replace(/(\d+).(\d+).(\d+)/, "$3/$2/$1");
    arr = arr.replace(/^(\d\d\/)/, "20$1");
    
	arrD = new Date(arr);	//arrival date
   
    var dep = depart.value;
    dep = dep.replace(/(\d+).(\d+).(\d+)/, "$3/$2/$1");
    dep = dep.replace(/^(\d\d\/)/, "20$1");
    
	depD = new Date(dep); //departure date
   
	var one_day = 1000*60*60*24;
	var plusone = Number(checkHours());

	var duration = Math.round((depD.getTime()-arrD.getTime())/one_day);	
	//alert(plusone);
	duration = duration + plusone;	
	//alert(depD.getTime() - arrD.getTime());
	var startMonth = arrD.getMonth()+1;
	var startDay = arrD.getDate();
	var startYear = arrD.getYear();
	var endMonth = depD.getMonth()+1;
	var endDay = depD.getDate();
	var endYear = depD.getYear();
	
	/*
	var call= "findduration.php?startDay=" + startDay + "&startMonth=" + startMonth + "&startYear=" + startYear + "&endDay=" + endDay + "&endMonth=" + endMonth + "&endYear=" + endYear;
	
	ajaxGetDuration(call);
	
	var durationdd = document.getElementById('duration');
	var duration = durationdd.innerHTML;
	duration = Number(duration) + Number(plusone);
	alert("We are experiencing technical difficulties. Please try again later.");
	*/
	//validity check for duration
	if(Number(duration) < min_duration || isNaN(duration))
		;				
	else{

		var call = "price.php?group=" + group + "&startDay=" + startDay + "&startMonth=" + startMonth + "&endDay=" + endDay + "&endMonth=" + endMonth + "&duration=" + duration;
		ajaxGetPrice(duration,call); //make AJAX call here
	}

	var durationr = document.getElementById('durationr');
	var durationd = document.getElementById('duration'); 
	var validityd = document.getElementById('validity');

	if(duration < min_duration && duration >= 0){
		durationd.innerHTML = ": Minimum "+min_duration+" days.";
		durationr.innerHTML = "---.--";
		validityd.innerHTML = "<font color=red size=2.5><b>*Please select another date. Minimum car rental period is "+min_duration+" days.</b></font>";
		total();
	}
	if(duration < 0)
	{
		durationd.innerHTML = ": Invalid date.";
		durationr.innerHTML = "---.--";
		validityd.innerHTML = "<font color=red size=2.5><b>*Please select another date. Pickup and drop-off dates do not match.</b></font>";
		total();
	}	
}

//function drivers(o) will update fields and add extra charge for extra drivers.
function drivers(o)
{
	num = parseInt(o);

	drivertd = document.getElementById('driver'); 
	drivertdr= document.getElementById('driverr');
	if(o != 0){
		if ( o == 1) //rule: if extra drivers = 1, then charge is free 
		{ 
			drivertd.innerHTML = ": "+ o + " extra driver"; 
			drivertdr.innerHTML = "free"; 
		}
		else 
		{ 
			drivertd.innerHTML = ": "+ o + " extra drivers"; 
			drivertdr.innerHTML = additionalDriver_charge.toFixed(2);
		}
	}
	else{
		drivertd.innerHTML = "";
		drivertdr.innerHTML = "";
	}
	total();
}

//rule for the firstchild seat: update fields stating free charge!
function firstchild(o)
{
	firstchildtd = document.getElementById('fstchildseat');
  	firstchildtdr = document.getElementById('fstchildseatr');
	
	if(o){	
		firstchildtd.innerHTML = ": 1st child seat";
		firstchildtdr.innerHTML = "free";
	}
	else{
		firstchildtd.innerHTML = "";
		firstchildtdr.innerHTML = "";
		if(document.getElementById('child2').checked == true){
			document.getElementById('child2').checked = false;
			secondchild(false);
		}
	}
}

//rule for second child seat: update fields stating extra charge
function secondchild(o)
{

  	secondchildtd = document.getElementById('sndchildseat');
  	secondchildtdr = document.getElementById('sndchildseatr');
	if(o){	
		document.getElementById('child1').checked = true;
		firstchild(document.getElementById('child1'));
		secondchildtd.innerHTML = ": 2nd child seat";
		secondchildtdr.innerHTML = secondchild_charge.toFixed(2);
	}
	else{
		secondchildtd.innerHTML = "";
		secondchildtdr.innerHTML = "";
	}
	total();
}

function gps(o)
{
  	gpstd = document.getElementById('gps');
  	gpstdr = document.getElementById('gpss');
	if(o){	
		document.getElementById('agps').checked = true;
		gpstd.innerHTML = ": GPS Navigator";
		gpstdr.innerHTML = Number(gps_charge).toFixed(2);
	}
	else{
		gpstd.innerHTML = "";
		gpstdr.innerHTML = "";
	}
	total();
}

//disable or enable fields for airport or hotel, according to selection
function changeTo(place)
{
	var pickupHotel=document.getElementById('pickupHotel');
	var pickupHotelTxt = document.getElementById('pickupHotelTxt');
	var arrivalAirport = document.getElementById('arrivalAirport');
	var arrivalAirportTxt = document.getElementById('arrivalAirportTxt');
	var arrivalFlightNum = document.getElementById('arrivalFlightNum');
	var arrivalFlightNumber = document.getElementById('ArrivalFlightNumber');
	var pickup_time_text = document.getElementById('pickup_time_text');
 
	if(place == 'hotel'){
		pickupHotel.style.color='#000000';
		pickupHotelTxt.style.backgroundColor='#ffffff';
		pickupHotelTxt.disabled=false;		
	
		arrivalAirport.style.color='#909090';
		arrivalAirportTxt.style.backgroundColor='#c0c0c0';
		arrivalAirportTxt.disabled=true;	
	
		arrivalFlightNum.style.color='#909090';
		arrivalFlightNumber.style.backgroundColor='#c0c0c0';
		arrivalFlightNumber.disabled=true;
		
		pickup_time_text.innerHTML='Pick-up time:';
	}
	else
	{
		pickupHotel.style.color='#909090';
		pickupHotelTxt.style.backgroundColor='#c0c0c0';
		pickupHotelTxt.disabled=true;		
		
		arrivalAirport.style.color='#000000';
		arrivalAirportTxt.style.backgroundColor='#ffffff';
		arrivalAirportTxt.disabled=false;
			
		arrivalFlightNum.style.color='#000000';
		arrivalFlightNumber.style.backgroundColor='#ffffff';
		arrivalFlightNumber.disabled=false;
		pickup_time_text.innerHTML='Arrival time:';
	}
}

//identical to changeTo() above.
function DchangeTo(place)
{
	var dropoffHotel=document.getElementById('dropoffHotel');
	var dropoffHotelTxt = document.getElementById('dropoffHotelTxt');
	var departureAirport = document.getElementById('departureAirport');
	var departureAirportTxt = document.getElementById('departureAirportTxt');
	var departureFlightNum = document.getElementById('departureFlightNum');
	var departureFlightNumber = document.getElementById('departureFlightNumTxt');
	var dep_time_text = document.getElementById('departure_time_text');
	
 
	if(place == 'hotel'){
		dropoffHotel.style.color='#000000';
		dropoffHotelTxt.style.backgroundColor='#ffffff';
		dropoffHotelTxt.disabled=false;		
	
		departureAirport.style.color='#909090';
		departureAirportTxt.style.backgroundColor='#c0c0c0';
		departureAirportTxt.disabled=true;	
	
		departureFlightNum.style.color='#909090';
		departureFlightNumber.style.backgroundColor='#c0c0c0';
		departureFlightNumber.disabled=true;
		
		dep_time_text.innerHTML = 'Drop-off time:<br><i><a HREF="javascript:;" onmouseover="Tip(\'<b>Late drop-off:</b><br>If drop-off time is later than 4 hours from <br>pick-up time then an extra day will be calculated<br> in the total price below.\');">(late drop-off)</a></i><br>';
	}
	else
	{
		dropoffHotel.style.color='#909090';
		dropoffHotelTxt.style.backgroundColor='#c0c0c0';
		dropoffHotelTxt.disabled=true;		
		
		departureAirport.style.color='#000000';
		departureAirportTxt.style.backgroundColor='#ffffff';
		departureAirportTxt.disabled=false;
			
		departureFlightNum.style.color='#000000';
		departureFlightNumber.style.backgroundColor='#ffffff';
		departureFlightNumber.disabled=false;
		
		dep_time_text.innerHTML = 'Drop-off time:<br><i><a HREF="javascript:;" onmouseover="Tip(\'<b>Late drop-off:</b><br>If drop-off time is later than 4 hours from <br>pick-up time then an extra day will be calculated<br> in the total price below.\');">(late drop-off)</a></i><br>';
	}
}

function ajaxGetDuration(call){

	var xmlHttp;
	var value;
	//find browser
  	try
  	{
    	// Firefox, Opera 8.0+, Safari
  		xmlHttp=new XMLHttpRequest();
  	}
  	catch (e){
    	// Internet Explorer
  		try
  		{
      		xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    	}
 		catch (e){
    		try
      		{
        		xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
      		}
      		catch (e){
        		alert("Your browser does not support AJAX. Please update browser to use this page.");
        		return false;
      		}
    	}
	}
	
    xmlHttp.onreadystatechange=function()
  	{
  		if(xmlHttp.readyState==4) //response is ready, update fields
    	{   
			value = xmlHttp.responseText;
			var durationdd = document.getElementById('duration');
			durationdd.innerHTML = value;
    	}
  	}
	
	//make the call 
 	xmlHttp.open("GET",call,true);
  	xmlHttp.send(null);
  	
}


//AJAX call to get a price from the database given car group,period of year and duration
//the rules for the price are in the database. 
function ajaxGetPrice(duration,call){

	var xmlHttp;
	//find browser
  	try
  	{
    	// Firefox, Opera 8.0+, Safari
  		xmlHttp=new XMLHttpRequest();
  	}
  	catch (e){
    	// Internet Explorer
  		try
  		{
      		xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
    	}
 		catch (e){
    		try
      		{
        		xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
      		}
      		catch (e){
        		alert("Your browser does not support AJAX. Please update browser to use this page.");
        		return false;
      		}
    	}
	}
	xmlHttp.onreadystatechange=function()
  	{
  		if(xmlHttp.readyState==4) //response is ready, update fields
    	{   

    		var durationrr = document.getElementById('durationr');
			durationrr.innerHTML = xmlHttp.responseText;
			
			var durationdd = document.getElementById('duration'); 
			var validitydd = document.getElementById('validity');	
			if(!isNaN(duration))
			durationdd.innerHTML = ": " + duration + " days";
			validitydd.innerHTML = "<br>";

			total();
    	}
  	}
	
	//make the call 
 	xmlHttp.open("GET",call,true);
  	xmlHttp.send(null);
}

