$(document).ready(function (){
	$("#pickup_or_delivery").change(pickup_or_delivery);
	$("#delivery_charges").click(showLocation);
	$("#delivery_date").datepicker({minDate:+1});
	$("#change_delivery").click(change_delivery);
	$("#order_food").submit(checkform);
	$("#credit_card").submit(checkcredit);
});


function convert_to_num (num) {
	num = num.replace('\,','');
	num = Number (num);
	return num;
}

function pickup_or_delivery (evt) {
	
	var pickupordelivery = $("#pickup_or_delivery").val();
	
	if (pickupordelivery=='Pickup') {
		var order_total;
		var sub_total = $("#sub_total").text();
		var tax = $("#tax").text();
		
		sub_total = convert_to_num (sub_total);
		tax = convert_to_num (tax);
		
		order_total = sub_total + tax;
		
		$("#order_total").val(order_total);
		$("#order_total_disp").text('$' + addCommas(order_total));
		$("#delivery_total_disp").text('');
		$("#delivery_total").val('');

		$("#delivery_row").hide();
		$("#delivery_address").hide();
		$("#restaurant_field").show();
		$("#distance_info").hide();
		
		$("#submit_button").show();
	
	} else if (pickupordelivery=='Delivery') {
		
		$("#delivery_row").show();
		$("#delivery_address").show();
		$("#submit_button").hide();
	}
}

function change_delivery (evt) {
	evt.preventDefault();

	$("#restaurant_field").show();
	$("#delivery_row").show();
	$("#delivery_address").show();
	$("#submit_button").hide();
	$("#distance_info").hide();
}

function getdistance(evt) {
	check_delivery_fields(evt);
	
	$("#delivery_row").show();
	$("#total_row").show();
	$("#distance_info").show();
	$("#submit_button").show();
	$("#delivery_address").hide();
	$("#restaurant_field").hide();

	var distance = gDir.getDistance().meters / 1609.344;
	var distnum;
	
	var order_total;
	var sub_total = $("#sub_total").text();
	var tax = $("#tax").text();
	
	sub_total = convert_to_num (sub_total);
	tax = convert_to_num (tax);

	distnum = Math.round(distance);

	if (distnum>5) {delivery_total=(distnum*.75)+(distnum*.50)} else {delivery_total=5}
	order_total = sub_total+tax+delivery_total;
	order_total = Math.round(order_total*100)/100;

	//address fields
	$("#distance").text((distnum*2)+' miles round trip');
	
	//display total fields
	$("#delivery_total_disp").text('$'+delivery_total.toFixed(2));
	$("#order_total_disp").text('$'+addCommas(order_total.toFixed(2)));
	
	//form fields
	$("#delivery_total").val(delivery_total.toFixed(2));
	$("#order_total").val(order_total.toFixed(2));
	
	$("#delivery_total").val(delivery_total.toFixed(2));
	$("#delivery_distance").val((distnum*2)+' miles round trip');

}

function check_delivery_fields(evt) {
	
	whiteoutform() ;
	var restaurant = document.getElementById('restaurant');
	var office_home = document.getElementById('office_home');
	var street = document.getElementById('street');
	var city = document.getElementById('city');
	var zip = document.getElementById('zip');
	
	if (restaurant.value=='') {
		alert('The restaurant field is empty'); 
		restaurant.focus();	
		changeBackground (restaurant);
		evt.preventDefault();
	} else if (office_home.value=='') {
		alert('The location type field is empty'); 
		office_home.focus();	
		changeBackground (office_home);
		evt.preventDefault();
	} else if (street.value=='') {
		alert('The street field is empty'); 
		street.focus();	
		changeBackground (street);
		evt.preventDefault();
	} else if (city.value=='') {
		alert('The city field is empty'); 
		city.focus();	
		changeBackground (city);
		evt.preventDefault();
	} else if (zip.value=='') {
		alert('The zip field is empty'); 
		zip.focus();	
		changeBackground (zip);
		evt.preventDefault();
	} else if ((zip.value!='')&&(!validateZIP(zip.value))) {
		zip.focus();	
		changeBackground (zip);
		evt.preventDefault();
	}
}

function checkform (evt) {
	whiteoutform();
	var restaurant = document.getElementById('restaurant');
	var minimum = document.getElementById('minimum');
	var myname = document.getElementById('myname');
	var phone = document.getElementById('phone');
	var cell = document.getElementById('cell');
	var email = document.getElementById('email');
	var delivery_date = document.getElementById('delivery_date');
	var delivery_time = document.getElementById('delivery_time');
	
	if (minimum.value < 75) {
		alert('There is a minimum charge of $75'); 
		evt.preventDefault();
	} else if (myname.value=='') {
		alert('The Name field is empty'); 
		myname.focus();	
		changeBackground (myname);
		evt.preventDefault();
	} else if (email.value=='') {
		alert('The Email field is empty'); 
		email.focus();	
		changeBackground (email);
		evt.preventDefault();
	} else if ((email.value != '') && (!validateEmail(email.value))) { 
		email.focus();	
		changeBackground (email);
		evt.preventDefault();
	} else if (phone.value=='') {
		alert('The Phone field is empty'); 
		phone.focus();	
		changeBackground (phone);
		evt.preventDefault();
	} else if ((phone.value != '') && checkPhoneFormat(phone, evt)) { 
		phone.focus();	
		changeBackground (phone);
		evt.preventDefault();
	} else if ((cell.value != '') && checkPhoneFormat(cell, evt)) { 
		cell.focus();	
		changeBackground (cell);
		evt.preventDefault();
	} else if (delivery_date.value=='') {
		alert('The delivery date field is empty'); 
		delivery_date.focus();	
		changeBackground (delivery_date);
		evt.preventDefault();
	} else if (delivery_time.value=='') {
		alert('The delivery time field is empty'); 
		delivery_time.focus();	
		changeBackground (delivery_time);
		evt.preventDefault();
	} else if (restaurant.value=='') {
		alert('The restaurant field is empty'); 
		restaurant.focus();	
		changeBackground (restaurant);
		evt.preventDefault();
	}
}

function checkcredit (evt) {
	whiteoutform();
	var cc_type = document.getElementById('cc_type');
	var cc_num = document.getElementById('cc_num');
	var cc_exp_month = document.getElementById('cc_exp_month');
	var cc_exp_year = document.getElementById('cc_exp_year');
	var cc_sec = document.getElementById('cc_sec');
	
	if (cc_type.value=='') {
		alert('The Card Type field is empty'); 
		cc_type.focus();	
		changeBackground (cc_type);
		evt.preventDefault();
	} else if (cc_num.value=='') {
		alert('The Card Number field is empty'); 
		cc_num.focus();	
		changeBackground (cc_num);
		evt.preventDefault();
	} else if (cc_exp_month.value=='') {
		alert('The Card Expiration Month field is empty'); 
		cc_exp_month.focus();	
		changeBackground (cc_exp_month);
		evt.preventDefault();
	} else if (cc_exp_year.value=='') {
		alert('The Card Expiration Year field is empty'); 
		cc_exp_year.focus();	
		changeBackground (cc_exp_year);
		evt.preventDefault();
	} else if (cc_sec.value=='') {
		alert('The CVV field is empty'); 
		cc_sec.focus();	
		changeBackground (cc_sec);
		evt.preventDefault();
	}	
	
	
}
function validateEmail (emailStr) {
	
	var checkTLD=1;
	var knownDomsPat=/^(com|net|org|edu|int|mil|gov|arpa|biz|aero|name|coop|info|pro|museum)$/;
	var emailPat=/^(.+)@(.+)$/;
	var specialChars="\\(\\)><@,;:\\\\\\\"\\.\\[\\]";
	var validChars="\[^\\s" + specialChars + "\]";
	var quotedUser="(\"[^\"]*\")";
	var ipDomainPat=/^\[(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})\]$/;
	var atom=validChars + '+';
	var word="(" + atom + "|" + quotedUser + ")";
	var userPat=new RegExp("^" + word + "(\\." + word + ")*$");
	var domainPat=new RegExp("^" + atom + "(\\." + atom +")*$");
	var matchArray=emailStr.match(emailPat);
	if (matchArray==null) {
	alert("Email address seems incorrect (check @ and .'s)");
		return false;
	}
	var user=matchArray[1];
	var domain=matchArray[2];
	for (i=0; i<user.length; i++) {
		if (user.charCodeAt(i)>127) {
			alert("Ths username contains invalid characters.");
			return false;
		}
	}
	
	for (i=0; i<domain.length; i++) {
		if (domain.charCodeAt(i)>127) {
			alert("Ths domain name contains invalid characters.");
			return false;
		}
	}
	
	if (user.match(userPat)==null) {
	
	alert("The username doesn't seem to be valid.");
		return false;
	}
	
	var IPArray=domain.match(ipDomainPat);
	
	if (IPArray!=null) {
		for (var i=1;i<=4;i++) {
			if (IPArray[i]>255) {
				alert("Destination IP address is invalid!");
				return false;
			   }
		}
		return true;
	}
	var atomPat=new RegExp("^" + atom + "$");
	var domArr=domain.split(".");
	var len=domArr.length;
	for (i=0;i<len;i++) {
	if (domArr[i].search(atomPat)==-1) {
	alert("The domain name does not seem to be valid.");
	return false;
	   }
	}
	
	if (checkTLD && domArr[domArr.length-1].length!=2 && 
		domArr[domArr.length-1].search(knownDomsPat)==-1) {
		alert("The address must end in a well-known domain or two letter " + "country.");
		return false;
	}
	
	if (len<2) {
		alert("This address is missing a hostname!");
		return false;
	}
	return true;
}


function checkPhoneFormat(passField, evt) {
	var phonenum = passField.value;
	var re = /[\D]/g;// remove non-numeric numbers
	phonenum = phonenum.replace(re , '');
	if (phonenum.length!=10) { 
		passField.value = phonenum;	
		alert('Please enter a 10 digit number of the form 123-123-1234');
		return true;
	 } else {
	 	phonenum = phonenum.substring(0, 3) + '-' + phonenum.substring(3, 6) + '-' + phonenum.substring(6, 10);
		passField.value = phonenum;	 
		return false;
	}
}

//validateZIP(this.zip.value)

function validateZIP(field) {
	var valid = "0123456789-";
	var hyphencount = 0;
	
	if (field.length!=5 && field.length!=10) {
		alert("Please enter your 5 digit or 5 digit+4 zip code.");
		return false;
	}
	
	for (var i=0; i < field.length; i++) {
		temp = "" + field.substring(i, i+1);
		if (temp == "-") hyphencount++;
		if (valid.indexOf(temp) == "-1") {
			alert("Invalid characters in your zip code.  Please try again.");
			return false;
		}
		if ((hyphencount > 1) || ((field.length==10) && ""+field.charAt(5)!="-")) {
			alert("The hyphen character should be used with a properly formatted 5 digit+four zip code, like '12345-6789'.   Please try again.");
			return false;
	   }
	}
	return true;
}


function whiteoutform() {
	$('input:text, select').each( function () { $(this).css({'background-color':'#ffffff'}); });
}

function changeBackground(passField) {
	passFieldname = passField.id;
	blinkme(passFieldname, 0); // can only pass string, not objects
}

function blinkme(thispassField, count) {
 	if (count%2==0) {
		document.getElementById(thispassField).style.backgroundColor = '#ffffff';
	} else {
		document.getElementById(thispassField).style.backgroundColor = '#FFFF00';
	}
	count++;
	if (count<14) {
		setTimeout("blinkme('"+thispassField+"', '"+count+"')", 50); 
	}
}





var geocoder, location1, location2, gDir;

function initialize() {
	geocoder = new GClientGeocoder();
	gDir = new GDirections();
	GEvent.addListener(gDir, "load", getdistance);
}

function showLocation() {
	var street = $("#street").val();
	var city = $("#city").val();
	var zip = $("#zip").val();
	
	var address1 = $("#restaurant").val();
	var address2 = street + ', ' + city + ', ' + zip;
	
	
	geocoder.getLocations(address1, function (response) {
		if (!response || response.Status.code != 200)
		{
			alert("Sorry, we were unable to geocode the first address");
		}
		else
		{
			location1 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
			
			geocoder.getLocations(address2, function (response) {
				if (!response || response.Status.code != 200)
				{
					alert("Sorry, we were unable to geocode the second address");
				}
				else
				{
					location2 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
					gDir.load('from: ' + location1.address + ' to: ' + location2.address);
				}
			});
		}
	});
}

function addCommas(nStr)
{
	nStr += '';
	x = nStr.split('.');
	x1 = x[0];
	x2 = x.length > 1 ? '.' + x[1] : '';
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(x1)) {
		x1 = x1.replace(rgx, '$1' + ',' + '$2');
	}
	return x1 + x2;
}

