var APAirportInput='';
if (GBrowserIsCompatible()) { 
		
	var map = new GMap2(document.getElementById("AP_AirportsMap"));
	//map.setUIToDefault();
	map.addMapType(G_PHYSICAL_MAP);        
	map.addControl(new GLargeMapControl3D());
	map.addControl(new GScaleControl());
	map.addControl(new GMapTypeControl());
	map.enableScrollWheelZoom();
	map.setCenter(new GLatLng(37,-95),3);
	
	// ====== Create a Client Geocoder ======
	var geo = new GClientGeocoder(); 
	
	// ====== Array for decoding the failure codes ======
	var reasons=[];
	reasons[G_GEO_SUCCESS]            = "Success";
	reasons[G_GEO_MISSING_ADDRESS]    = "Missing Location: The location was either missing or had no value.";
	reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unknown Location:  No corresponding geographic location could be found for the specified location.";
	reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Unavailable Address:  The geocode for the given address cannot be returned due to legal or contractual reasons.";
	reasons[G_GEO_BAD_KEY]            = "Bad Key: The API key is either invalid or does not match the domain for which it was given";
	reasons[G_GEO_TOO_MANY_QUERIES]   = "Too Many Queries: The daily geocoding quota for this site has been exceeded.";
	reasons[G_GEO_SERVER_ERROR]       = "Server error: The request could not be successfully processed.";
	
	// ====== Geocoding ======
	function APshowAddress() {
		map.clearOverlays();
		map.checkResize();
		map.setCenter(new GLatLng(37,-95),3);
		var search = document.getElementById("AP_AirportSearch").value;
		var radius = document.getElementById("radius").value;
		// ====== Perform the Geocoding ======        
		if(search.length>0){
			geo.getLocations(search, function (result){					 
				//numResults = result.Placemark.length;
				// If that was successful
				if (result.Status.code == G_GEO_SUCCESS) {
				  // How many resuts were found
					if(result.Placemark.length == 1){
						var p = result.Placemark[0].Point.coordinates;
						APgetAirports(p[1],p[0], radius);
						document.getElementById("AP_message").innerHTML = "<p>Airports within a "+radius+" mile radius of "+result.Placemark[0].address+"</p>";
						// Loop through the results, placing markers
						for (var i=0; i<result.Placemark.length; i++) {
						var p = result.Placemark[i].Point.coordinates;
						var point = new GLatLng(p[1],p[0]);
						var marker = APcreateMarker(point, result.Placemark[i].address, 0);
						if(marker != null) {map.addOverlay(marker)};
						}					
						// centre the map on the first result
						var p = result.Placemark[0].Point.coordinates;
						map.setCenter(new GLatLng(p[1],p[0]),14);
					} else {
				
						var resultsList = $('<ol class="AP_AirportsList"></ol>');
						document.getElementById("AP_message").innerHTML="<p>We found "+result.Placemark.length+" results. Please choose one of following or search again.</p><br/>";
						var locations='';
						var locationbounds = new GLatLngBounds( );
						for (var i=0; i<result.Placemark.length; i++) {
							var p = result.Placemark[i].Point.coordinates;
							var point = new GLatLng(p[1],p[0]);
							var marker = APcreateMarker(point, result.Placemark[i].address, 1);
							if(marker != null) {map.addOverlay(marker)};							
							locations = "<li><a class=\"noUnderlineLink\" onclick=\"APuseThisAddress('"+result.Placemark[i].address+"');\">"+ result.Placemark[i].address+"</a></li>";						
							resultsList.append(locations);												
							locationbounds.extend( point );
						}
						
						$('#AP_message').append(resultsList);
						var p = result.Placemark[0].Point.coordinates;
						map.setCenter( locationbounds.getCenter( ), map.getBoundsZoomLevel( locationbounds ) );
					}
					document.getElementById("AP_errorAirports").innerHTML = ('');
				} else { // ====== Decode the error status ======
					var reason="Code "+result.Status.code;
					if (reasons[result.Status.code]) {
						reason = reasons[result.Status.code]
					} 
					document.getElementById("AP_errorAirports").innerHTML += ('Could not find "'+search+ '" ' + reason);
				}
			});
		}
	}
}

// display a warning if the browser was not compatible
else {
  alert("Sorry, the Google Maps API is not compatible with this browser");
}
function APuseThisAddress(address){
	$('#AP_AirportSearch').val(address);
	APshowAddress();
}
function APshowAirports(textboxId){
	$('#AP_AirportsWrapper').fadeIn('normal');
	$('#AP_AirportSearch').focus();
	if ($('#AP_AirportSearchSidebarInput').val() !== ''){$('#AP_AirportSearch').val($('#AP_AirportSearchSidebarInput').val());}
	if(textboxId=="null"){
		APAirportInput = ''; //if textboxId=null, we are not going to use the airports to fill in a textbox
		APshowAddress(); 
	} else {
		APAirportInput = textboxId;
		APshowAddress(); // if textboxId is set, the textbox with this id will be filled with the selected airport			
	}
}


function APgetAirports(lat, lon, radius){
    queryString = "lat="+lat+"&lon="+lon+"&radius="+radius;
    $("#loadingAirports")
    .ajaxStart(function(){
        $(this).fadeIn(500);
    })
    .ajaxComplete(function(){
        $(this).fadeOut(500);
    })
    .ajaxStop(function(){
        $(this).fadeOut(500);
    });
    $.ajax({
        type: 'POST',
        url: '/airportsProximityMapList.php',
        data: queryString,
        dataType: 'json',
        timeout: 10000,
        error: function(){
            alert('Error getting the airports');
        },
        success: function(json){
            var airportList = $('<ol class="AP_AirportsList"></ol>');
			var latlngbounds = new GLatLngBounds( );
            //var map = new GMap2(document.getElementById("map"));
            for(i=0;i<json.id.length;i++){
                j=i+1;
                if(APAirportInput==''){
                	//if APAirportInput=null, we are not going to use the airports to fill in a textbox ... link to the airport info page instead.
					var airport = "<li><b><a href=\"http://www.paramountbusinessjets.com/airports.php?airport="+json.id[i]+"\" class=\"noUnderlineLink\"  target=\"_blank\">"+json.name[i] + ", "; 				
				} else {
					// if APAirportInput is set, the textbox with this id will be filled with the selected airport
					var airport = "<li><b><a onclick=\"APchooseAirport('"+json.icao[i]+"');\" class=\"noUnderlineLink\">"+json.name[i] + ", "; 			
				}
                airport += json.icao[i]+"</b>, ";
                if(json.iata[i].length>0){ airport += "<b>"+json.iata[i]+"</b>, "; }
                airport += "</a>";
                airport += json.city[i] + ", ";
                if(json.state[i].length>0){ airport += json.state[i]+", "; }
                airport += json.country[i]+" - (<b>"+json.distance[i]+" miles</b>)"+"</li>";
                airportList.append(airport);
                var pointA = new GLatLng(parseFloat(json.latitude[i]),parseFloat(json.longitude[i]));
                var markerA = APcreateMarkerA(pointA, json.name[i], json.icao[i], json.iata[i], json.id[i], i);
                if(markerA != null) {map.addOverlay(markerA)};
				latlngbounds.extend( pointA );				
            }
			var source=new GLatLng(parseFloat(lat),parseFloat(lon));
			latlngbounds.extend( source );
			map.setCenter( latlngbounds.getCenter( ), map.getBoundsZoomLevel( latlngbounds ) );
            $('#AP_message').append(airportList);
            $("#loadingAirports").fadeOut(500);
        }
    });
}
function APcreateMarker(point, address, showLink) {         
    var marker = new GMarker(point);
    var html = '<span class="mapHtml"><b>' + address + '</b></span><br/>'+'<br/>';
	if (showLink==1){
		html += '<span class="mapHtml"><a onclick="APuseThisAddress(\''+address+'\');">Choose this location</a></span>';
	}
	GEvent.addListener(marker, 'click', function() {
		marker.openInfoWindowHtml(html);
	});
    return marker;
}
function APcreateMarkerA(point, name, icao, iata, id, num) {
	// Create our "tiny" marker icon
    num=num+1;
    var iconOptions = {};
    iconOptions.primaryColor = "#FFAA00";
    iconOptions.strokeColor = "#FF7700";
    iconOptions.label = ""+num+"";
    iconOptions.labelColor = "#000000";
    iconOptions.addStar = false;
    iconOptions.starPrimaryColor = "#FF6666";
    iconOptions.starStrokeColor = "#0000FF";
    var icon = MapIconMaker.createLabeledMarkerIcon(iconOptions);
        
    // Set up our GMarkerOptions object
    markerOptions = { icon:icon };
    
    var marker = new GMarker(point, markerOptions);
    var html = "<span class=\"mapHtml\"><b>" + name + "</b><br/><b>ICAO</b>:"+icao+"<br/><b>IATA</b>:"+iata+"</span><br/><br/><span class=\"mapHtml\">";
    if(APAirportInput==''){
    	//if APAirportInput=null, we are not going to use the airports to fill in a textbox ... link to the airport info page instead.
		html += "<a href=\"http://www.paramountbusinessjets.com/airports.php?airport="+id+"\" target=\"_blank\">View Airport Details</a><br/></span>";
	} else {
		// if APAirportInput is set, the textbox with this id will be filled with the selected airport
		html += "<a onclick=\"APchooseAirport('"+icao+"');\" class=\"noUnderlineLink\">Select this airport</a><br/></span>"; 			
	}
    GEvent.addListener(marker, 'click', function() {
        marker.openInfoWindowHtml(html);
    });
    return marker;
}
function APchooseAirport(icao){
	$(APAirportInput).val(icao);
	$(APAirportInput).focus();
	$('#AP_AirportsWrapper').fadeOut('normal');
	$('#AP_AirportSearch').val('');
	$('#AP_message').empty();
}
