// JavaScript Document

function showIndicator(targetDiv, msg)
{
	Element.show(targetDiv);
	$(targetDiv).innerHTML = "<img src='images/indicator.gif'> " + msg ;
}

function changePicture(url)
{
	$('mainimage').src = url;
}

function loadVehicleInformation(carId)
{
	
	Element.hide('carImage');
	
	if (carId)
	{
		// if carId specified in query string, select the car in the dropdown.
		$('carId').value = carId;
	}
	else
	{
		// get carId selected from drop-down
		carId = $('carId').value;
	
		if (carId == null || carId == "")
		{
			$('carDetails').innerHTML = "";
			return;
		}
	}

/*
	
	new Ajax.Request ( 'reservation_car_details.php',
					  {
						  method: 'post',
						  onCreate: onLoadVehicleCreate(),
						  onSuccess: updateReservationCar,
						  parameters: 'carId=' + carId
					  }
					 );
*/
pageUrl = "reservation_car_details_" + carId + ".html";

new Ajax.Request ( pageUrl,
	{
		method:'get',
		onSuccess: updateReservationCar,
		onFailure: function(t) {alert('Error ' + t.status + ' -- ' + t.statusText);}
	});

	$('vehicle').value = $('carId').options[$('carId').selectedIndex].text;
}

function onLoadVehicleCreate()
{
	Element.show('carImage');
	$('carImage').src = "images/indicator.gif";
	showIndicator('carDetails', ' Loading Vehicle Information ...');
}

function updateReservationCar(response)
{
	/* XML parsing is not working.  Do it the old fashioned way.

	var xmlDoc=new ActiveXObject("Microsoft.XMLDOM")
	if (xmlDoc)
	{
		xmlDoc.async="false"
		xmlDoc.loadXML(response.responseText);
		$('carDetails').innerHTML = xmlDoc.getElementsByTagName("bodyText")[0].firstChild.nodeValue;
		if (xmlDoc.getElementsByTagName("carImage").count > 0) {
			$('carImage').src = xmlDoc.getElementsByTagName("carImage")[0].firstChild.nodeValue;
		}
	}
	else
	{
		var parser = new DOMParser();
		if (parser)
		{
			alert("I got me a DOM Parser!");
			
			//$('carDetails').innerHTML = ;
		}
		else
		{
		
		}
	}
	
	*/
	


	var resp = response.responseText;
	
	var index = resp.indexOf("<carImage>");
	var end = resp.indexOf("</carImage");
	var begin;
	
	if (index >= 0 && end >= 0)
	{
		begin = index + "<carImage>".length;
		$('carImage').src = resp.substring(begin, end);
		Element.show('carImage');
	}
	
	index = resp.indexOf("<bodyText>");
	end = resp.indexOf("</bodyText>");

	if (index >= 0 && end >= 0)
	{
		begin = index + "<bodyText>".length;
		$('carDetails').innerHTML = resp.substring(begin, end);
	}

}

function changePersonalInfo()
{
	if ($('sameAddress').checked)
	{
		$('bAddress1').value = $F('address1');
		$('bAddress2').value = $F('address2');
		$('bCity').value = $F('city');
		$('bState').value = $F('state');
		$('bZipCode').value = $F('zipCode');
		$('bCountry').value = $F('country');
	}
}

function validateReservationForm(form)
{
	
/*	"First%20Name=sohel&Last%20Name=katchi&Phone%20Number%201=713&Phone%20Number%202=&Phone%20Number%203=&Email%20Address=&Date%20of%20Birth%20Month=&Date%20of%20Birth%20Date=&Date%20of%20Birth%20Year=&Address=&address2=&City=&Zip%20Code=&rate=daily&Pickup%20Date%20Month=&Pickup%20Date%202=&Pickup%20Date%20Year=&Return%20Date%20Month=&Return%20Date=&Return%20Date%20Year=&carrier=&policyNumber=&insuranceEffMM=&insuranceEffDD=&insuranceEffYYYY=&insuranceEndMM=&insuranceEndDD=&insuranceEndYYYY=&agentName=&agentPhone1=&agentPhone2=&agentPhone3=&ccNumber=&ccExpMM=&ccExpDD=&ccExpYYYY=&ccCode=&bAddress1=&bAddress2=&bCity=&bZipCode=&bCountry=&State=TX&Car=11&Pickup%20Location=DEF&Pickup%20Time=00%3A00&Return%20Location=DEF&Return%20Time=00%3A00&ccType=visa&bState=TX"
*/
	changePersonalInfo();
		
	if ($('carId').selectedIndex == 0)
	{
		alert("Please select a vehicle.");
		$('carId').focus();
		return false;
	}
	
	$('vehicle').value = $('carId').options[$('carId').selectedIndex].text;

	var required = document.getElementsByClassName( 'required_text', form );
	for (i = 0; i < required.length; ++i)
	{
		if (trim($F(required[i])) == "" || !isAlpha($F(required[i])) )
		{
			alert($(required[i]).name + " is required.  Please do not enter any numbers.");
			$(required[i]).focus();
			return false;
		}
	}
	
	required = document.getElementsByClassName( 'required', form );
	for ( i = 0; i < required.length; ++i )
	{
		if (trim($F(required[i])) == "")
		{
			alert($(required[i]).name + " is required");
			$(required[i]).focus();
			return false;
		}
	}	
	
	required = document.getElementsByClassName( 'required_numeric', form );
	for (i = 0; i < required.length; ++i)
	{
		if ( trim($F(required[i])) == "" || !isNumeric($F(required[i])) )
		{
			alert($(required[i]).name + " is required.  Please enter numbers only.");
			$(required[i]).focus();
			return false;
		}
	}
	
	if ( trim($F('phone1')) == ""  || !isNumeric($F('phone1'))  || $F('phone1').length != 3  )
	{
		alert($('phone1').name + " is required.  Please enter a valid phone number.");
		$('phone1').focus();
		return false;
	}
	
	if ( trim($F('phone2')) == ""  || !isNumeric($F('phone2'))  || $F('phone2').length != 3  )
	{
		alert($('phone2').name + " is required.  Please enter a valid phone number.");
		$('phone2').focus();
		return false;
	}
	
	if ( trim($F('phone3')) == "" || !isNumeric($F('phone3')) || $F('phone3').length != 4 )
	{
		alert($('phone3').name + " is required.  Please enter a valid phone number.");
		$('phone3').focus();
		return false;
	}

	
	if ( trim($F('zipCode')) == "" || !isNumeric($F('zipCode')) || $F('zipCode').length != 5 ) 
	{
		alert("Zip Code is required.  Please enter a valid zip code.");
		$('zipCode').focus();
		return false;
	}
	
	if ( trim($F('bZipCode')) == "" || !isNumeric($F('bZipCode')) || $F('bZipCode').length != 5 ) 
	{
		alert("Billing Zip Code is required.  Please enter a valid zip code.");
		$('bZipCode').focus();
		return false;
	}
	
	if ( trim($F('email')) == "" || !isEmail($F('email')) )
	{
		alert($('email').name + " is required.  Please enter a valid e-mail address.");
		$('email').focus();
		return false;
	}
	
	var now = new Date(); // today
	
	var month, date, year;
	
	// DOB
	month = $F('dobMM');
	date  = $F('dobDD');
	year = $F('dobYYYY');
	
	var dob  = month + "/" + date + "/" + year;
	if (!isDate ( dob ))
	{
		alert("Please enter a valid Date of Birth");
		$('dobMM').focus();
		return false;	
	}
	dob = new Date(year, month-1, date);
	if ( dob > now )
	{
		alert("Please enter a date of birth which is before today.");
		$('dobMM').focus();
		return false;
	}
	
	// PICKUP and DROP OFF
	month = $F('pickupMM');
	date = $F('pickupDD');
	year = $F('pickupYYYY');

	var pickup = month + "/" + date + "/" + year;
	if (!isDate(pickup))
	{
		alert("Please enter a valid Pickup Date");
		$('pickupMM').focus();
		return false;
	}
	
	pickup = new Date(year, month-1, date);
	
	if ( pickup < now )
	{
		alert("Please enter a pick up date which is after today.");
		$('pickupMM').focus();
		return false;
	}
	
	month = $F('returnMM');
	date = $F('returnDD');
	year = $F('returnYYYY');
	var ret =  month + "/" + date + "/" + year;
	if (!isDate(ret))
	{
		alert("Please enter a valid Return Date");
		$('returnMM').focus();
		return false;
	}

	ret = new Date(year, month-1, date);
	if ( ret <= pickup ) 
	{
		alert("Please enter a date after Pickup Date");
		$('returnMM').focus();
		return false;
	}
	
	/*
	carrier=&policyNumber=&insuranceEffMM=&insuranceEffDD=&insuranceEffYYYY=&insuranceEndMM=&insuranceEndDD=&insuranceEndYYYY=&agentName=&agentPhone1=&agentPhone2=&agentPhone3=
	*/
	month = $F('insuranceEffMM');
	date = $F('insuranceEffDD');
	year = $F('insuranceEffYYYY');
	
	var effDate = month + "/" + date + "/" + year;
	if (!isDate(effDate))
	{
		alert("Please enter a valid Effective Date");
		$('insuranceEffMM').focus();
		return false;
	}
	effDate = new Date(year, month-1, date);
	
	month = $F('insuranceEndMM');
	date = $F('insuranceEndDD');
	year = $F('insuranceEndYYYY');
	
	var expDate = month + "/" + date + "/" + year;
	if (!isDate(expDate))
	{
		alert("Please enter a valid Expiration Date");
		$('insuranceEndMM').focus();
		return false;
	}
	expDate = new Date(year, month-1, date);
	
	if ( effDate > expDate )
	{
		alert("Effective Date cannot be after Expiration Date");
		$('insuranceEffMM').focus();
		return false;
	}
	
	if (expDate < now)
	{
		alert("Insurance already expired.");
		$('insuranceEndMM').focus();
		return false;
	}
	
	// if agent name is specified, make sure phone number is correct
	if (trim($F('agentName')) != "")
	{
		if ( trim($F('agentPhone1')) == ""  || !isNumeric($F('agentPhone1'))  || $F('agentPhone1').length != 3  )
		{
			alert("Phone number for Insurance Agent is required if you specify an agent.  Please enter a valid phone number.");
			$('agentPhone1').focus();
			return false;
		}
		
		if ( trim($F('agentPhone2')) == ""  || !isNumeric($F('agentPhone2'))  || $F('agentPhone2').length != 3  )
		{
			alert("Phone number for Insurance Agent is required if you specify an agent.  Please enter a valid phone number.");
			$('agentPhone2').focus();
			return false;
		}
		
		if ( trim($F('agentPhone3')) == "" || !isNumeric($F('agentPhone3')) || $F('agentPhone3').length != 4 )
		{
			alert("Phone number for Insurance Agent is required if you specify an agent.  Please enter a valid phone number.");
			$('agentPhone3').focus();
			return false;
		}
	}
		
	// Billing Validation
	
	if ( trim($F('ccNumber')).length != 16 )
	{
		alert("Please enter a valid 16-digit Credit Card Number");
		$('ccNumber').focus();
		return false;
	}
	
	month = $F('ccExpMM');
	date = $F('ccExpDD');
	year = $F('ccExpYYYY');
	
	expDate = month + "/" + date + "/" + year;
	
	if (!isDate(expDate))
	{
		alert("Please enter a valid Credit Card Expiration Date");
		$('ccExpMM').focus();
		return false;
	}
	
	expDate = new Date(year, month-1, date);
	if (expDate < now)
	{
		alert("Credit Card already expired.");
		$('ccExpMM').focus();
		return false;
	}
	
}

function trim(sInString) {
  sInString = sInString.replace( /^\s+/g, "" );// strip leading
  return sInString.replace( /\s+$/g, "" );// strip trailing
}

function isNumeric(ObjVal)
{
	return /^\d+$/.test(ObjVal);
}

function isAlpha(ObjVal) {
	
	return !(/[^a-zA-Z]/.test(ObjVal));	
    
}    

function isPhone(ObjVal) {
    var pattern = /[0-9]{3}-[0-9]{3}-[0-9]{4}/;
    if (pattern.test(ObjVal)) {
        return true;
    }
    else {
        return false;
    }
} 

function isEmail(ObjVal) {
    var pattern = /^[a-zA-Z_0-9\- ]+\@[a-zA-Z0-9 \-\.]+\.([a-zA-Z]{2,3})$/;
    if (pattern.test(ObjVal)) {
        return true;
    }
    else {
        return false;
    }
}   


/**
 * DHTML date validation script. Courtesy of SmartWebby.com (http://www.smartwebby.com/dhtml/)
 * FROM http://www.smartwebby.com/DHTML/date_validation.asp
 */
// Declaring valid date character, minimum year and maximum year
var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function stripCharsInBag(s, bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}
function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31;
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30;}
		if (i==2) {this[i] = 29;}
   } 
   return this;
}

function isDate(dtStr){
	var daysInMonth = DaysArray(12);
	var pos1=dtStr.indexOf(dtCh);
	var pos2=dtStr.indexOf(dtCh,pos1+1);
	var strMonth=dtStr.substring(0,pos1);
	var strDay=dtStr.substring(pos1+1,pos2);
	var strYear=dtStr.substring(pos2+1);
	strYr=strYear;
	if (strDay.charAt(0)=="0" && strDay.length>1) strDay=strDay.substring(1);
	if (strMonth.charAt(0)=="0" && strMonth.length>1) strMonth=strMonth.substring(1);
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1) strYr=strYr.substring(1);
	}
	month=parseInt(strMonth);
	day=parseInt(strDay);
	year=parseInt(strYr);
	if (pos1==-1 || pos2==-1){
		alert("The date format should be : mm/dd/yyyy");
		return false;
	}
	if (strMonth.length<1 || month<1 || month>12){
//		alert("Please enter a valid month");
		return false;
	}
	if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
//		alert("Please enter a valid day");
		return false;
	}
	if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
//		alert("Please enter a valid 4 digit year between "+minYear+" and "+maxYear);
		return false;
	}
	if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isNumeric(stripCharsInBag(dtStr, dtCh))==false){
//		alert("Please enter a valid date");
		return false;
	}
	return true;
}

/*
function ValidateForm(){
	var dt=document.frmSample.txtDate
	if (isDate(dt.value)==false){
		dt.focus()
		return false
	}
    return true
 }
*/