var map;
var geocoder;
var map_legend = new Array();

var baseIcon = new GIcon();
baseIcon.shadow = "http://www.blueskytaxi.com/img/pin.png";
baseIcon.iconSize = new GSize(20, 12);
baseIcon.iconAnchor = new GPoint(20, 5);
baseIcon.infoWindowAnchor = new GPoint(15, 15);

var baseIcon_green = new GIcon();
baseIcon_green.shadow = "http://www.blueskytaxi.com/img/pin_green.png";
baseIcon_green.iconSize = new GSize(26, 26);
baseIcon_green.iconAnchor = new GPoint(12, 12);
baseIcon_green.infoWindowAnchor = new GPoint(15, 15);

var baseIcon_red = new GIcon();
baseIcon_red.shadow = "http://www.blueskytaxi.com/img/pin_blue.png";
baseIcon_red.iconSize = new GSize(20, 12);
baseIcon_red.iconAnchor = new GPoint(12, 12);
baseIcon_red.infoWindowAnchor = new GPoint(15, 15);

var baseIcon_standout = new GIcon();
baseIcon_standout.shadow = "http://www.blueskytaxi.com/img/home_airport.png";
baseIcon_standout.iconSize = new GSize(20, 12);
baseIcon_standout.iconAnchor = new GPoint(12, 12);
baseIcon_standout.infoWindowAnchor = new GPoint(15, 15);

function load() {
	if (GBrowserIsCompatible()) {
		geocoder = new GClientGeocoder();
		map = new GMap2(elementById('map'));
		map.addControl(new GSmallMapControl());
		map.addControl(new GMapTypeControl());
		map.setCenter(new GLatLng(42.000325, -88.791504), 5);
	}
}

function elementById(x) {
  if (document.getElementById) return document.getElementById(x);
    else if (document.all) return document.all[x];
    else if (document.layers) return document.layers[x];
    else return null;
}

function searchLocations(whichInputValue) {
	
	var address = elementById(whichInputValue+'addressInput_1').value + elementById(whichInputValue+'addressInput_2').value + elementById(whichInputValue+'addressInput_3').value;
	
	geocoder = new GClientGeocoder();
	geocoder.getLatLng(address, function(latlng) {
		if (!latlng) {
			//alert(address + ' not found');
		} else {
			searchLocationsNear(latlng, whichInputValue);
		}
	});
}

/*
function searchLocations2(whichInputValue) {
	var address = elementById(whichInputValue+'addressInput2').value;
	geocoder = new GClientGeocoder();
	geocoder.getLatLng(address, function(latlng) {
		if (!latlng) {
			//alert(address + ' not found');
		} else {
			searchLocationsNear(latlng, whichInputValue);
		}
	});
}

function searchLocations3(whichInputValue) {
	var address = elementById(whichInputValue+'addressInput3').value;
	geocoder = new GClientGeocoder();
	geocoder.getLatLng(address, function(latlng) {
		if (!latlng) {
			//alert(address + ' not found');
		} else {
			searchLocationsNear(latlng, whichInputValue);
		}
	});
}

function searchLocations4(whichInputValue) {
	var address = elementById(whichInputValue+'addressInput4').value;
	geocoder = new GClientGeocoder();
	geocoder.getLatLng(address, function(latlng) {
		if (!latlng) {
			//alert(address + ' not found');
		} else {
			searchLocationsNear(latlng, whichInputValue);
		}
	});
}

function searchLocations5(whichInputValue) {
	var address = elementById(whichInputValue+'addressInput5').value;
	geocoder = new GClientGeocoder();
	geocoder.getLatLng(address, function(latlng) {
		if (!latlng) {
			//alert(address + ' not found');
		} else {
			searchLocationsNear(latlng, whichInputValue);
		}
	});
}

function searchLocations6(whichInputValue) {
	var address = elementById(whichInputValue+'addressInput6').value;
	geocoder = new GClientGeocoder();
	geocoder.getLatLng(address, function(latlng) {
		if (!latlng) {
			//alert(address + ' not found');
		} else {
			searchLocationsNear(latlng, whichInputValue);
		}
	});
}
*/

function searchLocationsNear(center, thisForm) {
	//map.removeOverlay(GPolyline);
	//var radius = elementById(thisForm+'radiusSelect').value;
	var radius = 100;
	var searchUrl = 'inc/engine.php?lat=' + center.lat() + '&lng=' + center.lng() + '&radius=' + radius;
	GDownloadUrl(searchUrl, function(data) {
		var xml = GXml.parse(data);
		var markers = xml.documentElement.getElementsByTagName('marker');
		map.clearOverlays();
		var sidebar = elementById(thisForm+'sidebar');
		sidebar.innerHTML = '';
		if (markers.length == 0) {
			sidebar.innerHTML = 'out of service range';
			var optn = document.createElement("option");
			optn.text = "out of service range";
			optn.value = "";
			elementById(thisForm+"sidebar").options.add(optn);
			map.setCenter(new GLatLng(42.000325, -88.791504), 5);
			return;
		}
		createFirstSidebarEntry(thisForm);
		var bounds = new GLatLngBounds();
		map_legend[thisForm] = new Array();
		for (var i = 0; i < markers.length; i++) {
			var name = markers[i].getAttribute('name');
			var address = markers[i].getAttribute('address');
			var distance = parseFloat(markers[i].getAttribute('distance'));
			var point = new GLatLng(parseFloat(markers[i].getAttribute('lat')), parseFloat(markers[i].getAttribute('lng')));
			var my_lat = parseFloat(markers[i].getAttribute('lat'));
			var my_lng = parseFloat(markers[i].getAttribute('lng'));
			var indexnum = i;
			
			if(name == 'Waukegan Regional Airport'){
				var marker = createMarker(point, name, address, thisForm, indexnum, my_lat, my_lng, baseIcon_standout);
			}else if(name == 'Chicago Executive Airport'){
				var marker = createMarker(point, name, address, thisForm, indexnum, my_lat, my_lng, baseIcon_standout);
			}else if(name == 'Dupage Airport'){
				var marker = createMarker(point, name, address, thisForm, indexnum, my_lat, my_lng, baseIcon_standout);
			}else{
				var marker = createMarker(point, name, address, thisForm, indexnum, my_lat, my_lng, baseIcon);
			}
			
			map_legend[thisForm][indexnum+1] = [marker, my_lat, my_lng];
			map.addOverlay(marker);
			var sidebarEntry = createSidebarEntry(marker, name, address, distance, thisForm, my_lat, my_lng);
			bounds.extend(point);
		}
		
		GEvent.addDomListener( elementById(thisForm+"sidebar"), "change", function() {
				
			var curIndex = elementById(thisForm+"sidebar").selectedIndex;
			
			if ((curIndex > 0) && (curIndex < map_legend[thisForm].length))
			{
				GEvent.trigger(map_legend[thisForm][curIndex][0], "click");
				elementById(myForm+"saved_lat").value = map_legend[thisForm][curIndex][1];
				elementById(myForm+"saved_lng").value = map_legend[thisForm][curIndex][2];
				calculateDistance();
			}
		});
		
		map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
	});
}

function createMarker(point, name, address, myForm, indexnum, my_lat, my_lng, my_icon) {
	var customIcon = new GIcon(my_icon);
	markerOptions = { icon:customIcon };
	var html = "<b>" + name + "</b> <br/>" + address;
	var marker = new GMarker(point, markerOptions);
	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(html);
		elementById(myForm+"sidebar").selectedIndex = indexnum + 1;
		elementById(myForm+"saved_lat").value = my_lat;
		elementById(myForm+"saved_lng").value = my_lng;
		calculateDistance();
    });
	return marker;
}

function createSimpleMarker(point, name, address, my_icon) {
	var customIcon = new GIcon(my_icon);
	var html = "<b>" + name + "</b> <br/>" + address;
	markerOptions = { icon:customIcon };
	var marker = new GMarker(point, markerOptions);
	GEvent.addListener(marker, "click", function() {
		marker.openInfoWindowHtml(html);
    });
	return marker;
}

function createSidebarEntry(marker, name, address, distance, myForm, my_lat, my_lng) {
	var html = name + " - " + address;
	var this_optn = document.createElement("option");
	this_optn.text = html;
	this_optn.value = html;
	this_optn.id = name;
	this_optn.name = name;
	elementById(myForm+"sidebar").options.add(this_optn);
	
		//GEvent.addDomListener(this_optn, "click", function() {
			//GEvent.trigger(marker, "click");
			//elementById(myForm+"saved_lat").value = my_lat;
			//elementById(myForm+"saved_lng").value = my_lng;
			//calculateDistance();
		//});
}

function createFirstSidebarEntry(myForm) {
	var html = "select from available airports";
	var optn = document.createElement("option");
	optn.text = html;
	optn.value = html;
	elementById(myForm+"sidebar").options.add(optn);
}

function drawAPoly( whichelement, from_saved_lat, from_saved_lng, to_saved_lat, to_saved_lng, name_1, address_1, name_2, address_2 ){
	geocoder = new GClientGeocoder();
	map = new GMap2(elementById(whichelement));
	map.addControl(new GSmallMapControl());
	map.addControl(new GMapTypeControl());
	map.setCenter(new GLatLng(42.000325, -88.791504), 5);
	var point_1 = new GLatLng(parseFloat(from_saved_lat), parseFloat(from_saved_lng));
	var point_2 = new GLatLng(parseFloat(to_saved_lat), parseFloat(to_saved_lng));
	var marker_1 = createSimpleMarker(point_1, name_1, address_1, baseIcon_green);
	var marker_2 = createSimpleMarker(point_2, name_2, address_2, baseIcon_red);
	map.addOverlay(marker_1);
	map.addOverlay(marker_2);
	var polyline = new GPolyline([new GLatLng(from_saved_lat, from_saved_lng),new GLatLng(to_saved_lat, to_saved_lng)], "#ff0000", 7);
	map.addOverlay(polyline);
}

function changecolor(newcolor, oldcolor, div, otherdiv, thirddiv){
	if(document.getElementById()){
		document.getElementById(div).style.backgroundColor = newcolor;
		document.getElementById(otherdiv).style.backgroundColor = oldcolor; 
		document.getElementById(thirddiv).style.backgroundColor = oldcolor;
		return;
	}
	if(document.layers){ //browser="NN4"
		document.layers[div].bgColor = newcolor;
		document.layers[otherdiv].bgColor = oldcolor;
		document.layers[thirddiv].bgColor = oldcolor;
	}
	if(document.all){ //browser="IE"
		document.all.div.style.backgroundColor = newcolor;
		document.all.otherdiv.style.backgroundColor = oldcolor;
		document.all.thirddiv.style.backgroundColor = oldcolor;
	}
	if(!document.all && document.getElementById()){ //browser="NN6+ or IE5+
		document.getElementById(div).style.backgroundColor = newcolor;
		document.getElementById(otherdiv).style.backgroundColor = oldcolor;
		document.getElementById(thirddiv).style.backgroundColor = oldcolor;
	}
}

function changecolor_simple(newcolor, div){
	if(document.getElementById()){
		document.getElementById(div).style.backgroundColor = newcolor;
		return;
	}
	if(document.layers){ //browser="NN4"
		document.layers[div].bgColor = newcolor;
	}
	if(document.all){ //browser="IE"
		document.all.div.style.backgroundColor = newcolor;
	}
	if(!document.all && document.getElementById()){ //browser="NN6+ or IE5+
		document.getElementById(div).style.backgroundColor = newcolor;
	}
}

function roundnumberTime(num){
	num = num.toString();
	var split = num.split(".");
	var dec = split[1].substr(0,3);
	var dec1 = dec.match(/\d{2,2}/);
	var dec2 = dec.match(/(\d$)/);
	var rounded = (dec1 + "." + dec2[0]);
	return split[0] + "." + Math.round(rounded);
	//return split[0];
}
function roundnumberPrice(num){
	num = num.toString();
	return Math.round(num);
}
function roundnumberPrice2(num){
	num = num.toString();
	return Math.round(num);
}

function calculateDistance(){
	var lat_1 = elementById('from_saved_lat').value;
	var lng_1 = elementById('from_saved_lng').value;
	var lat_2 = elementById('to_saved_lat').value;
	var lng_2 = elementById('to_saved_lng').value;
	//var basePrice = 495; //$495/hr 1st hour of waiting is free
	var basePrice = 3.50; // per mile
	var avgspeed = 160; //average speed of the plane
	if(lat_1 != '' && lng_1 != '' && lat_2 != '' && lng_2 != ''){
		var x = 69.1 * (lat_2 - lat_1);
		var y = 53.0 * (lng_2 - lng_1);
		var totalDistance = roundnumberTime(Math.sqrt(x * x + y * y));
		var totalTime = roundnumberTime(totalDistance/avgspeed);
		//var totalPrice = roundnumberPrice(totalTime*basePrice);
		var totalPrice = roundnumberPrice(totalDistance*basePrice);
		elementById('trip_details').style.display = 'block';
		elementById('distance').innerHTML = "Distance: "+totalDistance+" Miles";
		elementById('travel_time').innerHTML = "Travel Time: "+totalTime+' Hours';
		elementById('total_travel_time').value = totalTime;
		elementById('price').innerHTML = 'Approximate Price: $'+totalPrice;
		elementById('distance_form').value = totalDistance;
		elementById('travel_time_form').value = totalTime;
		elementById('price_form').value = totalPrice;
	}
}



function recalculatePrice(){
	
	var default_price = elementById('default_price').value;
	var updated_price_wait = elementById('updated_price_wait').value;
	var updated_price_double = elementById('updated_price_double').value;
	
	var hourly_rate = 45;
	
	var hours_to_wait = elementById('pilot_wait_time').value;
	
	//var new_price = elementById('updated_price').value*1 + (hourly_rate*hours_to_wait);
	
	if(elementById('updated_price_double').value != ''){
		var new_price = (updated_price_double*1 + (hourly_rate*hours_to_wait*1) - 45);
	}else{
		var new_price = (default_price*1 + (hourly_rate*hours_to_wait*1) - 45);
	}
	
	
	
	//var new_price = (default_price*1 + (hourly_rate*hours_to_wait*1) - 45);
	
	
	
	var new_price2 = (hourly_rate*1)*(hours_to_wait*1) - 45;

	elementById('update_price').innerHTML = roundnumberPrice2(new_price);
	elementById('updated_price_wait').value = roundnumberPrice2(new_price2);
	elementById('updated_price').value = roundnumberPrice2(new_price);
}

function recalculatePrice_double(){
	
	var default_price = elementById('default_price').value;
	var updated_price_wait = elementById('updated_price_wait').value;
	
	var new_price = (((default_price*1)* 2) + (updated_price_wait*1)) ;
	var new_pricedd = (default_price*1) * 2;
	
	elementById('update_price').innerHTML = roundnumberPrice2(new_price);
	elementById('updated_price_double').value = new_pricedd;
	elementById('updated_price').value = roundnumberPrice2(new_price);
}

function recalculatePrice_minusdouble(){
	
	var default_price = elementById('default_price').value;
	var updated_price_wait = elementById('updated_price_wait').value;
	
	var new_price = (default_price*1) + (updated_price_wait*1);
	
	elementById('update_price').innerHTML = roundnumberPrice2(new_price);
	elementById('updated_price_double').value = '';
	elementById('updated_price').value = roundnumberPrice2(new_price);
	
	//alert(new_price);
	//alert(default_price);
}


function pilot_wait_time_on(){
	elementById("hidden_div").style.display = 'block';
}
function pilot_wait_time_off(){
	elementById("hidden_div").style.display = 'none';
	
	
	if(elementById('updated_price_double').value != ''){
		elementById('update_price').innerHTML = elementById('updated_price_double').value;
		elementById('updated_price').value = elementById('updated_price_double').value;
	}else{
		elementById('update_price').innerHTML = elementById('default_price').value;
		elementById('updated_price').value = elementById('default_price').value;
	}
	
	elementById('updated_price_wait').value = "";
	elementById('pilot_wait_time').value = "";
	
}

function echeck(str) {
	var at="@"
	var dot="."
	var lat=str.indexOf(at)
	var lstr=str.length
	var ldot=str.indexOf(dot)
	if (str.indexOf(at)==-1){
		  alert("Please enter a valid email address")
		  return false
	}
	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr){
		alert("Please enter an Email Address")
		return false
	}
	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr){
		alert("Please enter an Email Address")
		return false
	}
	if (str.indexOf(at,(lat+1))!=-1){
		alert("Please enter an Email Address")
		return false
	}
	if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
		alert("Please enter an Email Address")
		return false
	}
	if (str.indexOf(dot,(lat+2))==-1){
		alert("Please enter an Email Address")
		return false
	}
	if (str.indexOf(" ")!=-1){
		alert("Please enter an Email Address")
		return false
	}
	return true
	/*
	if (echeck(emailID.value)==false){
		emailID.value=""
		emailID.focus()
		return false
	}
	*/
}

function ValidateForm_1(){
	var from_sidebar = elementById("from_sidebar");
	var to_sidebar = elementById("to_sidebar");
	var date = elementById("date");
	var num_adults = elementById("num_adults").selectedIndex;
	var num_child = elementById("num_child").selectedIndex;
	if(from_sidebar.value == "Enter A City, State, or Zip Code To Begin" || from_sidebar.value == "select from available airports"){
		alert("Please choose the airport you are leaving from.");
		elementById("from_sidebar").focus();
		return false;
	}else if(to_sidebar.value == "Enter A City, State, or Zip Code To Begin" || to_sidebar.value == "select from available airports"){
		alert("Please choose the airport you would like to arrive at.");
		elementById("to_sidebar").focus();
		return false;
	}else if(date.value == ""){
		alert("Please choose the date you would like to travel.");
		elementById("date").focus();
		return false;
	}else if(num_adults.value < "1"){
		alert("Please enter how many adults will be traveling with you.");
		elementById("num_adults").focus();
		return false;
	}else if((num_adults + num_child) > 3){
		alert("Only 3 passengers are allowed on each flight. Please choose a lower amount of passengers.");
		elementById("num_adults").focus();
		return false;
	}else{
		elementById("bluesky_flights").submit();
	}
}

function ValidateForm_2(){
	var pass_1_first_name = elementById("pass_1_first_name");
	var pass_1_last_name = elementById("pass_1_last_name");
	var pass_1_weight = elementById("pass_1_weight");

	var telephone_1 = elementById("telephone_1");
	var email = elementById("email");
	
	if(pass_1_first_name.value == ""){
		alert("Please enter your first name");
		elementById("pass_1_first_name").focus();
		return false;
	}else if(pass_1_last_name.value == ""){
		alert("Please enter your last name");
		elementById("pass_1_last_name").focus();
		return false;
	}else if(pass_1_weight.value == ""){
		alert("Please enter your weight");
		elementById("pass_1_weight").focus();
		return false;
	}else if(telephone_1.value == ""){
		alert("Please enter your telephone number");
		elementById("telephone_1").focus();
		return false;
	}else if(email.value == ""){
		alert("Please enter your email address");
		elementById("email").focus();
		return false;
	}else{
		elementById("bluesky_flights").submit();
	}
}

function validateSS_public(){
	var departure_airport = elementById("departure_airport");
	var arrival_airport = elementById("arrival_airport");
	var phone = elementById("phone");
	if(departure_airport.value == ""){
		alert("Please enter a departure airport");
		elementById("departure_airport").focus();
		return false;
	}else if(arrival_airport.value == ""){
		alert("Please enter an arrival airport");
		elementById("arrival_airport").focus();
		return false;
	}else if(phone.value == ""){
		alert("Please enter your phone number");
		elementById("phone").focus();
		return false;
	}else{
		return true;	
	}
}

function rollcolor(div, newcolor) {
	elementById(div).style.backgroundColor = newcolor;
} 

function showHide(shID) {
    if (elementById(shID).style.display == 'none') {
		elementById(shID).style.display = 'block';
    }else if(elementById(shID).style.display = 'block'){
		elementById(shID).style.display = 'none';
	}
}

