(function(w, d, undefined){
	
	var instatQuoteForm, IQF, xhr, btn;
	
	IQF = instantQuoteForm = d.getElementById('getInstantQuoteForm');//The double var is just a shorthand. I want to create a small variable, but still remember what it stands for.
	btn = d.getElementById('getInstantQuoteSidebarBtn');
	
	var xhr = new XMLHttpRequest();
	if(xhr && IQF){
		IQF.action = "";//Just make sure it doesn't do anything incase return false fails on event.
	}
	
	if(IQF){
		IQF.onsubmit = function(e){
			hidePrice();
			validateAddress(this)
			return false;
		}
	}
	
	function processFormData(form){
		var els, postTo, lon1, lat1, lon2, lat2, queryString;
			els = form.elements;
			postTo = 'ajax_quotefair_process.asp';
		
			//Only the lon and lat are needed for the calculation.
			lon1 = els['PickUpLongitude'].value;
			lat1 = els['PickUpLatitude'].value;
			lon2 = els['DestinationLongitude'].value;
			lat2 = els['DestinationLatitude'].value;
		
			if(!lon1 || !lon2 || !lat1 || !lat2){
				alert("Please fill out the form before pressing Calculate Quote");
				return false;
			}
		
			queryString = 'PickUpLongitude=' + lon1 + '&PickUpLatitude=' + lat1 + '&DestinationLongitude=' + lon2 + '&DestinationLatitude=' + lat2;
		
			xhr.open("POST", postTo, true);
			xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			xhr.setRequestHeader("Content-length", queryString.length);
			xhr.setRequestHeader("Connection", "close");
		
			xhr.onreadystatechange = function(){
				if(xhr.readyState == 4){
					var price = xhr.responseText;
					displayButton(price);
				}
			}
			
			xhr.send(queryString)
		
			return false;
	}
	
	function validateAddress(formElem){
		var number1, street1, city1, zip1,
		    number2, street2, city2, zip2,
		    address1, address2,
		    latlng1, latlng2;
		    
		var geocoder = new GClientGeocoder();
		
		number1 = d.getElementById('PickUpStreetNumber').value;
		street1 = d.getElementById('PickUpAddress').value;
		city1 = d.getElementById('PickUpCity').value;
		zip1 = d.getElementById('PickUpZip').value;
		
		number2 = d.getElementById('DestinationStreetNumber').value;
		street2 = d.getElementById('DestinationAddress').value;
		city2 = d.getElementById('DestinationCity').value;
		zip2 = d.getElementById('DestinationZip').value;
		
		address1 = number1 + ' ' + street1 + ' ' + zip1;
		address2 = number2 + ' ' + street2 + ' ' + zip2;
		
		geocoder.getLatLng(address1, function(point){
			if(point == null){
				alert('Your Pickup Address desn\'t seem to be valid. Please make sure it is correct.\nYou can use the Find on Map feature to solve this problem.');
			}else{
				d.getElementById('PickUpLongitude').value = ChangeCoordinate(point.lng());
				d.getElementById('PickUpLatitude').value = ChangeCoordinate(point.lat());
				geocoder.getLatLng(address2, function(point){
					if(point == null){
						alert('Your Destination Address desn\'t seem to be valid. Please make sure it is correct.\nYou can use the Find on Map feature to solve this problem.');
					}else{
						d.getElementById('DestinationLongitude').value = ChangeCoordinate(point.lng());
						d.getElementById('DestinationLatitude').value = ChangeCoordinate(point.lat());
						
						//Save Pickup and drop off locations in cookies so we can fill out the forms automatically later.
						createCookie("address1", number1 + ' ' + street1);
						createCookie("city1", city1);
						createCookie("zip1", zip1);
						
						createCookie("address2", number2 + ' ' + street2);
						createCookie("city2", city2);
						createCookie("zip2", zip2);
						//end cookies
						
						processFormData(formElem);
					}
				});
			}
		});
		
		return false;
	}
	
	function ChangeCoordinate(cood){//copied from mapping.js
  	if (cood < 0){
    	cood = cood * -1;
  	}
 		if (cood < 100){
  	  padding = 10000000;
		}else{
    	padding= 1000000;
  	}
  	return Math.floor(cood*padding)
	}
	
	function displayButton(price){
		var img = d.getElementById('bookNow');
		img.style.display = "block";
		var s = img.getElementsByTagName('span')[0];
		s.innerHTML = "Estimated Cost: " + price;
	}
	function hidePrice(){
		var img = d.getElementById('bookNow');
		img.style.display = "None";
		var s = img.getElementsByTagName('span')[0];
		s.innerHTML = "";
	}
	
	if(btn){
		
		btn.onclick = function(){
			var pantalla = d.createElement('div');
			pantalla.id = "pantalla";
			
			d.body.appendChild(pantalla);
			
			//Do Ajax stuff.
			xhr.open('GET', 'inc-getQuote.asp', true);
			xhr.onreadystatechange = function(){
				if(xhr.readyState == 4){
					var form = xhr.responseText;
					displayForm(form);
				}
			}
			xhr.send(null);
			return false;
		}
		
		function displayForm(form){
			var formDiv = d.createElement('div');
			formDiv.id="formDiv";
			formDiv.innerHTML = form;
			d.body.appendChild(formDiv);
			var w = document.body.clientWidth;
			var pos = (w/2) - (470/2);
			formDiv.style.left = pos + 'px';
			scrollTo(0,0);
			var img = d.createElement('img');
			img.src = "B_img/onebit_35.png";
			img.id = "closeBtn";
			formDiv.appendChild(img);
			img.onclick = function(){
				d.body.removeChild(formDiv);
				d.body.removeChild(d.getElementById('pantalla'));
			}
			//START form submission handling
			
			var IQF = d.getElementById('getInstantQuoteForm');
			if(IQF){
				IQF.onsubmit = function(e){
					hidePrice();
					validateAddress(this)
					return false;		
				}
			}
			//ENd form submission handling.
			
		}
	}


	//Prefill info in orderataxionline page
	//We prefill only once after the user has requested a quote. Then we delete the cookies.
	//Client said this is how it should work. That way user doesn't get forced into his last address.
	(function(){
		//inside a function to keep variables local to this function.
		var address1, city1, zip1,
		    address2, city2, zip2,
		    cookieAddress1, cookieCity1, cookieZip1,
		    cookieAddress2, cookieCity2, cookieZip2,
		    //This are to auto select the time
		    pickUpTimeHour;
		
		//auto select time
		var dte = new Date;
		var hour = dte.getHours();
		if(hour > 12) hour -= 1;
		pickUpTimeHour = d.getElementById('pickUpHour');
		if(pickUpTimeHour){
			pickUpTimeHour.value = hour;
			pickUpTimeHour.innerHTML = hour;
		}
		
		cookieAddress1 = readCookie('address1');
		cookieCity1 = readCookie('city1');
		cookieZip1 = readCookie('zip1');
		
		cookieAddress2 = readCookie('address2');
		cookieCity2 = readCookie('city2');
		cookieZip2 = readCookie('zip2');
		
		eraseCookie('address1');
		eraseCookie('city1');
		eraseCookie('zip1');
		eraseCookie('address2');
		eraseCookie('city2');
		eraseCookie('zip2');
		
		address1 = d.getElementById('address1');
		city1 = d.getElementById('city1');
		zip1 = d.getElementById('zip1');
		
		address2 = d.getElementById('address2');
		city2 = d.getElementById('city2');
		zip2 = d.getElementById('zip2');
		
		if(address1 && cookieAddress1 && address1.value == ''){
			address1.value = cookieAddress1;
		}
		if(city1 && cookieCity1 && city1.value == ''){
			city1.value = cookieCity1;
		}
		if(zip1 && cookieZip1 && zip1.value == ''){
			zip1.value = cookieZip1;
		}
		
		if(address2 && cookieAddress2 && address2.value == ''){
			address2.value = cookieAddress2;
		}
		if(city2 && cookieCity2 && city2.value == ''){
			city2.value = cookieCity2;
		}
		if(zip2 && cookieZip2 && zip2.value == ''){
			zip2.value = cookieZip2;
		}
	})();
	
//NICE Cookie Functions from: http://www.quirksmode.org/js/cookies.html
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}


//order a taxi functions
(function(){
	var form = d.getElementById('orderATaxiForm');
	if(form){
		form.onsubmit = function(){
			var n = this['name'].value;
			var email = this['Email'].value;
			var pAddr = this['PickUpAddressHidden'].value;
			var pZip = this['PickUpZipHidden'].value;
			var dAddr = this['DestinationAddressHidden'].value;
			var dZip = this['DestinationZipHidden'].value;
			
			var password = this['password'] ? this['password'].value : null;
			if(password){
				//we are trying to register.
				var passwordConf = this['passwordConfirm'] ? this['passwordConfirm'].value : null;
				if(password != passwordConf){
					alert('Your chosen password doesn\'t match your password confirmation.');
					this['password'].focus();
					return false;
				}
			}
			
			if(!n || !email || !pAddr || !pZip || !dAddr || !dZip){
				this['name'].style.border = !n ? "1px solid #F00" : '';
				this['Email'].style.border = !email ? "1px solid #F00" : '';
				this['PickUpAddressHidden'].style.border = !pAddr ? "1px solid #F00" : '';
				this['PickUpZipHidden'].style.border = !pZip ? "1px solid #F00" : '';
				this['DestinationAddressHidden'].style.border = !dAddr ? "1px solid #F00" : '';
				this['DestinationZipHidden'].style.border = !dZip ? "1px solid #F00" : '';
				
				alert('You have missed a few fields that are mandatory for us to book your taxi. You\'ll see those fields highlighted in red. Thank you.');
				return false;
			}
			
			validateAddress2(this);
			return false;
		}
	}
	
	function validateAddress2(form){
		var pAddr = form['PickUpAddressHidden'].value;
		var pZip = form['PickUpZipHidden'].value;
		var dAddr = form['DestinationAddressHidden'].value;
		var dZip = form['DestinationZipHidden'].value;
		
		var address1 = pAddr + ' ' + pZip;
		var address2 = dAddr + ' ' + dZip;
		
		var geocoder = new GClientGeocoder();
		
		geocoder.getLatLng(address1, function(point){
			if(point == null){
				alert('Your Pickup Address desn\'t seem to be valid. Please make sure it is correct.');
			}else{
				d.getElementById('PickUpLongitude').value = ChangeCoordinate(point.lng());
				d.getElementById('PickUpLatitude').value = ChangeCoordinate(point.lat());
				geocoder.getLatLng(address2, function(point){
					if(point == null){
						alert('Your Destination Address desn\'t seem to be valid. Please make sure it is correct.');
					}else{
						d.getElementById('DestinationLongitude').value = ChangeCoordinate(point.lng());
						d.getElementById('DestinationLatitude').value = ChangeCoordinate(point.lat());
						
						//everything is correct.
						form.onsubmit = function(){};//prevent this check from being done again, so the form gets submitted.
						form.submit();
					}
				});
			}
		});
	}
})()

var slct = d.getElementById('payTypeSlct');
if(slct){
	slct.onchange  = checkPayType;
}
function checkPayType(){
	var val = this.options[this.selectedIndex].value;
	var inpt = d.getElementById('accNum');
	if(val == 'W3'){
		inpt.style.visibility = 'visible';
	}else{
		inpt.style.visibility = 'hidden';
		inpt.getElementsByTagName('input')[0].value = "";
	}
}

(function(){
	var form = d.getElementById('instantCallForm');
	form.onsubmit = function(){
		var num = form['from'];
		var val = num.value;
		if(!val){
			alert('Please input your phone number. (###)###-####');
			num.focus();
		}else{
			if(val[0] != 1){
				val = "1" + val;
			}
			var tmpVal = val.replace(/\d/g, "#");
			//allow for
			/*
				1(123)123-1234
				1-123-123-1234
				1123-123-1234
				1(123)1231234
				11231231234
			*/
			if(tmpVal != "#(###)###-####" && tmpVal != '#-###-###-####' && tmpVal != '#(###)#######' && tmpVal != '###########' && tmpVal != '####-###-####' && tmpVal != '#(###)-###-####'){
				alert('Please use the format (123)123-1234 for your phone number.');
				num.focus();
				return false;
			}
			
			val = val.replace('(','');
			val = val.replace(')','');
			val = val.replace(/-/g,'');
			
			//num.value = val;
			
			var cmd = form['cmd'].value;
			var to = form['to'].value;
			var fname = form['fname'].value;
			
			var url = form.action + '?cmd=' + cmd + '&to=' + to + '&fname=' + fname + '&from=' + val;
			var img = d.createElement('img');
			img.src = url;
			//alert(val);
			//alert('You\'re phone should ring in a few seconds, when you pick up it will ring and connect with Mainline Taxi');
			setTimeout(function(){document.location.href="wearecallingyou.asp";}, 1000);//Give it tiem to load the url.
			return false;
		}
		return false;
	}
})()
	
})(window, document);



