﻿var map1;
var map2;
var sFromLocation;
var sToLocation;
var iAircraftType;
var sFromLocationLast;
var sToLocationLast;
var iAircraftTypeLast;
var ALS1 = [];
var ALS2 = [];
var localSearch1;
var localSearch2;

var centerPoint;

function initialize() {

    //alert(GBrowserIsCompatible());
    if (GBrowserIsCompatible()) {

        // Create and Center a Map
        map1 = new GMap2(document.getElementById("map1"));
        map1.setCenter(new GLatLng(0, 0), 10);
        map1.addControl(new GSmallMapControl());
        map1.addControl(new GMapTypeControl());

        // Create and Center a Map
        map2 = new GMap2(document.getElementById("map2"));
        map2.setCenter(new GLatLng(0, 0), 10);
        map2.addControl(new GSmallMapControl());
        map2.addControl(new GMapTypeControl());

        var ddlAircraftType = document.getElementById(ddlAircraftTypeID);

        //      centerPoint = new GLatLng(51.4775,0);
        //      centerPoint.x = 51.4775;
        //      centerPoint.y = 0;

        //create search 1 
        localSearch1 = new GlocalSearch();
        localSearch1.setSearchCompleteCallback(null, function() { SearchCallBack(localSearch1, map1, "map1_details", ALS1) });                 //ddlAircraftType.options(ddlAircraftTypeID.selectedIndex).value, 
        localSearch1.setCenterPoint("London");
        //localSearch1.setAddressLookupMode(GlocalSearch.ADDRESS_LOOKUP_DISABLED);

        localSearch2 = new GlocalSearch();
        localSearch2.setSearchCompleteCallback(null, function() { SearchCallBack(localSearch2, map2, "map2_details", ALS2) });                 //ddlAircraftType.options(ddlAircraftTypeID.selectedIndex).value, 
        localSearch2.setCenterPoint("London");
        //localSearch2.setAddressLookupMode(GlocalSearch.ADDRESS_LOOKUP_DISABLED);

        loadInitialLocations();

    }
}

function SearchMap() {
    var suggestedToLandingSite;
    var suggestedFromLandingSite;
    suggestedToLandingSite = false;
    suggestedFromLandingSite = false;
    // set appropriate from location
    if (document.getElementById(hfFlyFromLandingSiteIDClientID).value != "" && document.getElementById(hfFlyFromLandingSiteIDClientID).value != "0") {
        if (document.getElementById(tbFromLocationID).value != document.getElementById(hfFlyFromLandingSiteDisplayTextClientID).value) {
            sFromLocation = document.getElementById(tbFromLocationID).value;
            // Reset hidden fields
            resetLandingSiteHiddenFields(1);
            document.getElementById(tbFlyFromLandingSiteID).value = "";
        }
        else {
            suggestedFromLandingSite = true;
            sFromLocation = document.getElementById(hfFlyFromLandingSiteSearchTextClientID).value;
//            // Set LandingSiteID
//            document.getElementById(tbFlyFromLandingSiteID).value = document.getElementById(hfFlyFromLandingSiteIDClientID).value;
        }
    }
    else {
        sFromLocation = document.getElementById(tbFromLocationID).value;
        // Reset hidden fields
        //resetLandingSiteHiddenFields(1);
    }
    
    // set appropriate to location
    if (document.getElementById(hfFlyToLandingSiteIDClientID).value != "" && document.getElementById(hfFlyToLandingSiteIDClientID).value != "0") {
        if (document.getElementById(tbToLocationID).value != document.getElementById(hfFlyToLandingSiteDisplayTextClientID).value) {
            sToLocation = document.getElementById(tbToLocationID).value;
            // Reset hidden fields
            resetLandingSiteHiddenFields(2);
            document.getElementById(tbFlyToLandingSiteID).value = "";
        }
        else {
            suggestedToLandingSite = true;
            sToLocation = document.getElementById(hfFlyToLandingSiteSearchTextClientID).value;
//            // Set LandingSiteID
//            document.getElementById(tbFlyToLandingSiteID).value = document.getElementById(hfFlyToLandingSiteIDClientID).value;
        }
    }
    else {
        sToLocation = document.getElementById(tbToLocationID).value;
        // Reset hidden fields
        //resetLandingSiteHiddenFields(2);
    }

    var ddlAircraftType = document.getElementById(ddlAircraftTypeID);
    iAircraftType = ddlAircraftType.options[ddlAircraftType.selectedIndex].value;

    //alert(sFromLocation + '|' + defaultEstimatorLocationValue + '||' + sFromLocationLast + '|' + sFromLocation + '||' + iAircraftTypeLast + '|' + iAircraftType);

    var suggestionLat;
    var suggestionLong;

    if (sFromLocation != defaultEstimatorLocationValue && (sFromLocationLast != sFromLocation || iAircraftTypeLast != iAircraftType)) {
        //alert(sFromLocation);
        if (suggestedFromLandingSite == true) {
            // don't go to GLocal
            suggestionLat = sFromLocation.substring(0, sFromLocation.indexOf(" "));
            suggestionLong = sFromLocation.substring(sFromLocation.indexOf(" ") + 1);
            
            loadLocation(map1, "map1_details", suggestionLat, suggestionLong, ddlAircraftType.options[ddlAircraftType.selectedIndex].value);

            //update landing site id
            setLandingSiteID("map1_details", document.getElementById(hfFlyFromLandingSiteIDClientID).value);
        }
        else {
            localSearch1.execute(sFromLocation);
        }
    }

    if (sToLocation != defaultEstimatorLocationValue && (sToLocationLast != sToLocation || iAircraftTypeLast != iAircraftType)) {
        if (suggestedToLandingSite == true) {
            // don't go to GLocal
            suggestionLat = sToLocation.substring(0, sToLocation.indexOf(" "));
            suggestionLong = sToLocation.substring(sToLocation.indexOf(" ") + 1);

            loadLocation(map2, "map2_details", suggestionLat, suggestionLong, ddlAircraftType.options[ddlAircraftType.selectedIndex].value);

            //update landing site id
            setLandingSiteID("map2_details", document.getElementById(hfFlyToLandingSiteIDClientID).value);
        }
        else {
            localSearch2.execute(sToLocation);
        }
    }

    sFromLocationLast = sFromLocation;
    sToLocationLast = sToLocation;
    iAircraftTypeLast = iAircraftType;

    return false;
}

function resetLandingSiteHiddenFields(mode) {
    //mode: "From" = 1 | "To" = 2
    if (mode == 1) {
        document.getElementById(hfFlyFromLandingSiteIDClientID).value = "";
        document.getElementById(hfFlyFromLandingSiteDisplayTextClientID).value = "";
        document.getElementById(hfFlyFromLandingSiteSearchTextClientID).value = "";
    }
    else{
        document.getElementById(hfFlyToLandingSiteIDClientID).value = "";
        document.getElementById(hfFlyToLandingSiteDisplayTextClientID).value = "";
        document.getElementById(hfFlyToLandingSiteSearchTextClientID).value = "";
    }
}

function loadInitialLocations() {

    if (formSetFromQueryString == "true") {         // string compare!

        map1.clearOverlays();
        map1.setCenter(new GLatLng(0, 0), 0, G_NORMAL_MAP);

        map2.clearOverlays();
        map2.setCenter(new GLatLng(0, 0), 0, G_NORMAL_MAP);

        SearchMap();
    }
    else {
        var tbFlyFromLon = document.getElementById(tbFlyFromLonID);
        var tbFlyFromLat = document.getElementById(tbFlyFromLatID);
        var tbFlyToLon = document.getElementById(tbFlyToLonID);
        var tbFlyToLat = document.getElementById(tbFlyToLatID);
        //var tbFlyToLat = document.getElementById (tbFlyToLatID);
        var tbFlyFromLandingSite = document.getElementById(tbFlyFromLandingSiteID);
        var tbFlyToLandingSite = document.getElementById(tbFlyToLandingSiteID);
        var ddlAircraftType = document.getElementById(ddlAircraftTypeID);

        if (tbFlyFromLat.value != "" && tbFlyFromLon.value != "" && tbFlyFromLat.value != "0" && tbFlyFromLon.value != "0") {
            loadLocation(map1, "map1_details", tbFlyFromLat.value, tbFlyFromLon.value, ddlAircraftType.options[ddlAircraftType.selectedIndex].value);
        }
        else {

            map1.clearOverlays();
            map1.setCenter(new GLatLng(0, 0), 0, G_NORMAL_MAP);
        }

        if (tbFlyToLat.value != "" && tbFlyToLon.value != "" && tbFlyToLat.value != "0" && tbFlyToLon.value != "0") {
            loadLocation(map2, "map2_details", tbFlyToLat.value, tbFlyToLon.value, ddlAircraftType.options[ddlAircraftType.selectedIndex].value);
        }
        else {
            map2.clearOverlays();
            map2.setCenter(new GLatLng(0, 0), 0, G_NORMAL_MAP);
        }
    }
}

function loadLocation(map, mapdetailsid, lat, lng, aircraftType, results) {

    // mjg 20080429 ensure new markers are drawn.
    map.clearOverlays();

    mapdetails = document.getElementById(mapdetailsid);
    mapdetails.innerHTML = '';

    //map.setCenter(new GLatLng(lat, lng), 10, G_NORMAL_MAP);		
    //map.setCenter(new GLatLng(lat, lng), 8, G_NORMAL_MAP);		
    map.setCenter(new GLatLng(lat, lng), 9, G_NORMAL_MAP);

    //update lat and lng
    setLatLng(mapdetailsid, lat, lng);

    var icon = new GIcon();
    icon.image = "http://labs.google.com/ridefinder/images/mm_20_orange.png";
    icon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
    icon.iconSize = new GSize(12, 20);
    icon.shadowSize = new GSize(22, 20);
    icon.iconAnchor = new GPoint(6, 20);
    icon.infoWindowAnchor = new GPoint(5, 1);
    map.addOverlay(new GMarker(new GLatLng(lat, lng), icon));

    PlotNearestALS(map, mapdetailsid, lat, lng, aircraftType, results);

}

function SearchCallBack(localSearch, map, mapdetailsid, results) {           //aircraftType,

    // mjg 20080429 ensure new markers are drawn.
    map.clearOverlays();

    mapdetails = document.getElementById(mapdetailsid);
    mapdetails.innerHTML = '';

    if (localSearch.results == null || localSearch.results.length == 0) {
        //update lat and lng to zero;
        //alert('nullness');
        setLatLng(mapdetailsid, 0, 0);
        return;
    }
    var first = localSearch.results[0];
    //map.setCenter(new GLatLng(first.lat, first.lng), 10, G_NORMAL_MAP);		
    //map.setCenter(new GLatLng(first.lat, first.lng), 8, G_NORMAL_MAP);		
    map.setCenter(new GLatLng(first.lat, first.lng), 9, G_NORMAL_MAP);

    //update lat and lng
    setLatLng(mapdetailsid, first.lat, first.lng);

    var icon = new GIcon();
    icon.image = "http://labs.google.com/ridefinder/images/mm_20_orange.png";
    icon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
    icon.iconSize = new GSize(12, 20);
    icon.shadowSize = new GSize(22, 20);
    icon.iconAnchor = new GPoint(6, 20);
    icon.infoWindowAnchor = new GPoint(5, 1);
    map.addOverlay(new GMarker(new GLatLng(first.lat, first.lng), icon));

    //PlotNearestALS (map, mapdetailsid, first.lat, first.lng, aircraftType, results);
    // use global variable iAircraftType instead as this is set dynamically afressh on every search call
    PlotNearestALS(map, mapdetailsid, first.lat, first.lng, iAircraftType, results);

    //ifLandingSiteSelectionSelected(mapdetailsid);
    //alert(document.getElementById(tbFromLocationID).value + '\n' + document.getElementById(hfFlyFromLandingSiteIDClientID).value + '\n' + document.getElementById(hfFlyFromLandingSiteDisplayTextClientID).value + '\n' + document.getElementById(hfFlyFromLandingSiteSearchTextClientID).value);
}

function PlotNearestALS(map, mapdetails, Lat, Long, aircraftType, results) {
    var sURL = "/XMLTransfer/NearestALS.aspx?lat=" + Lat.toString() + "&lon=" + Long.toString() + "&at=" + aircraftType.toString() + "&ts=" + new Date().getMilliseconds();
    GDownloadUrl(sURL, function(data, responseCode) { PlotNearestALSCallBack(map, mapdetails, data, results, responseCode) });
}

function PlotNearestALSCallBack(map, mapdetailsid, data, results, responseCode) {

    var tbFlyFromLon = document.getElementById(tbFlyFromLonID);
    var tbFlyFromLat = document.getElementById(tbFlyFromLatID);
    var tbFlyToLon = document.getElementById(tbFlyToLonID);
    var tbFlyToLat = document.getElementById(tbFlyToLatID);

    var icon = new GIcon();
    icon.image = "http://labs.google.com/ridefinder/images/mm_20_green.png";
    icon.shadow = "http://labs.google.com/ridefinder/images/mm_20_shadow.png";
    icon.iconSize = new GSize(12, 20);
    icon.shadowSize = new GSize(22, 20);
    icon.iconAnchor = new GPoint(6, 20);
    icon.infoWindowAnchor = new GPoint(5, 1);

    results = [];

    var mapdetails = document.getElementById(mapdetailsid);
    //alert(data);
    if (data.length > 0) {
        var xml = GXml.parse(data);
        var markers = xml.documentElement.getElementsByTagName("marker");
        for (var i = 0; i < markers.length; i++) {
            var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")), parseFloat(markers[i].getAttribute("lng")));
            var marker = new GMarker(point, { icon: icon, title: markers[i].getAttribute("name") });
            marker.infoDiv = "div" + mapdetailsid + i;
            marker.siteID = markers[i].getAttribute("siteid");
            marker.title = markers[i].getAttribute("name");

            //add pushpin
            map.addOverlay(marker);

            //add to information panel
            var detailDiv = document.createElement("div");
            detailDiv.id = "div" + mapdetailsid + i;
            detailDiv.innerHTML += "<b>" + i + "</b> " + markers[i].getAttribute("name") + " (" + markers[i].getAttribute("dist") + "mi)<br/>";
            detailDiv.markerIndex = i;
            detailDiv.className = "estimator_mapDetailsItem";

            mapdetails.appendChild(detailDiv);

            // select chosen location
            if (mapdetailsid == "map1_details") {
                if (parseFloat(markers[i].getAttribute("lat")) == parseFloat(tbFlyFromLat.value) && parseFloat(markers[i].getAttribute("lng")) == parseFloat(tbFlyFromLon.value)) {
                    marker.setImage("http://labs.google.com/ridefinder/images/mm_20_orange.png");
                    detailDiv.className = "estimator_mapDetailsItemSelected";
                }
            }
            else {
                if (parseFloat(markers[i].getAttribute("lat")) == tbFlyToLat.value && parseFloat(markers[i].getAttribute("lng")) == tbFlyToLon.value) {
                    marker.setImage("http://labs.google.com/ridefinder/images/mm_20_orange.png");
                    detailDiv.className = "estimator_mapDetailsItemSelected";
                }
            }


            //add to results stack
            results.push(marker);

            GEvent.addListener(marker, "click", function() { markerClicked(mapdetailsid, map, results, this); });

            //wireup event for clicking div
            GEvent.bindDom(detailDiv, "click", detailDiv, function() { itemClicked(mapdetailsid, map, results, this); });

        }


    }
}

function markerClicked(mapdetailsid, map, results, marker) {

    //clear all currently selected items
    for (i = 0; i < results.length; i++) {
        results[i].setImage("http://labs.google.com/ridefinder/images/mm_20_green.png");
        document.getElementById(results[i].infoDiv).className = "estimator_mapDetailsItem";
    }

    //change image	      
    marker.setImage("http://labs.google.com/ridefinder/images/mm_20_orange.png");
    //marker.

    //center map
    map.setCenter(marker.getPoint());

    //change selected item
    document.getElementById(marker.infoDiv).className = "estimator_mapDetailsItemSelected";

    //update lat and lng
    setLatLng(mapdetailsid, marker.getPoint().lat(), marker.getPoint().lng());

    //update landing site id
    setLandingSiteID(mapdetailsid, marker.siteID);

}

function itemClicked(mapdetailsid, map, results, div) {

    //clear all currently selected items
    for (i = 0; i < results.length; i++) {
        results[i].setImage("http://labs.google.com/ridefinder/images/mm_20_green.png");
        document.getElementById(results[i].infoDiv).className = "estimator_mapDetailsItem";
    }

    var marker = results[div.markerIndex];

    //change image	      
    marker.setImage("http://labs.google.com/ridefinder/images/mm_20_orange.png");

    //center map
    map.setCenter(marker.getPoint());

    //change selected item
    div.className = "estimator_mapDetailsItemSelected";

    //update lat and lng
    setLatLng(mapdetailsid, marker.getPoint().lat(), marker.getPoint().lng());

    //update landing site id
    setLandingSiteID(mapdetailsid, marker.siteID);
}

//function ifLandingSiteSelectionSelected(mapdetailsid) {

//    if (mapdetailsid == "map1_details") {
//        // set appropriate from location
//        if (document.getElementById(hfFlyFromLandingSiteIDClientID).value != "" && document.getElementById(hfFlyFromLandingSiteIDClientID).value != "0") {
//            if (document.getElementById(tbFromLocationID).value == document.getElementById(hfFlyFromLandingSiteDisplayTextClientID).value) {
//                setLandingSiteID(mapdetailsid, document.getElementById(hfFlyFromLandingSiteIDClientID).value);
//            }
//        }
//    }
//    else {
//        // set appropriate to location
//        if (document.getElementById(hfFlyToLandingSiteIDClientID).value != "" && document.getElementById(hfFlyToLandingSiteIDClientID).value != "0") {
//            if (document.getElementById(tbToLocationID).value == document.getElementById(hfFlyToLandingSiteDisplayTextClientID).value) {
//                setLandingSiteID(mapdetailsid, document.getElementById(hfFlyToLandingSiteIDClientID).value);
//            }
//        }
//    }
//}


function setLandingSiteID(mapdetailsid, siteID) {

    var tbFlyFromLandingSite = document.getElementById(tbFlyFromLandingSiteID);
    var tbFlyToLandingSite = document.getElementById(tbFlyToLandingSiteID);

    if (mapdetailsid == 'map1_details') {
        tbFlyFromLandingSite.value = siteID;
    } else {
        tbFlyToLandingSite.value = siteID;
    }

}


function setLatLng(mapdetailsid, lat, lng) {

    var tbFlyFromLon = document.getElementById(tbFlyFromLonID);
    var tbFlyFromLat = document.getElementById(tbFlyFromLatID);
    var tbFlyToLon = document.getElementById(tbFlyToLonID);
    var tbFlyToLat = document.getElementById(tbFlyToLatID);
    var tbFlyDistance = document.getElementById(tbFlyDistanceID);

    if (mapdetailsid == 'map1_details') {
        tbFlyFromLat.value = lat;
        tbFlyFromLon.value = lng;
    }
    else {
        tbFlyToLat.value = lat;
        tbFlyToLon.value = lng;
    }

    var fromPoint = new GLatLng(tbFlyFromLat.value, tbFlyFromLon.value);
    var toPoint = new GLatLng(tbFlyToLat.value, tbFlyToLon.value);

    tbFlyDistance.value = toPoint.distanceFrom(fromPoint) / 1000;

    //		alert (fromPoint.lat() + " - " + fromPoint.lng() + " - " + toPoint.lat() + " - " + toPoint.lng());
    //		alert (toPoint.distanceFrom (fromPoint)/10000);

}

//var googleSuggestions = [];
//var fmnSuggestions = [];

//function GetSuggestions(tb, mode) {
//    var sLocation = tb.value;
//    if (sLocation.length > 2) {
//        localSearch3 = new GlocalSearch();
//        localSearch3.setSearchCompleteCallback(null, function() { SuggestionsGoogleCallback(sLocation, localSearch3, "hgc" + mode + "Suggestions", "hgc" + mode + "GSuggestions", googleSuggestions) });
//        localSearch3.setCenterPoint("London");
//        //localSearch3.setAddressLookupMode(google.search.LocalSearch.ADDRESS_LOOKUP_DISABLED);
//        localSearch3.execute(sLocation);

////        var sURL = "http://ws.geonames.org/postalCodeSearch?placename=" + sLocation + "&maxRows=10";
////        GDownloadUrl(sURL, function(data, responseCode) { SuggestionsGeoCallback(sLocation, "hgc" + mode + "Suggestions", "hgc" + mode + "FMNSuggestions", data, fmnSuggestions, responseCode) });


//        //            var sURL = "/XMLTransfer/NearestALS.aspx?lat=0.25&lon=-52.8&at=1&ts=" + new Date().getMilliseconds();
//        //            GDownloadUrl(sURL, function(data, responseCode) { SuggestionsALSCallback(sLocation, "hgc" + mode + "Suggestions", "hgc" + mode + "FMNSuggestions", data, fmnSuggestions, responseCode) });
//    }
//}

//function SuggestionsGoogleCallback(sLocation, localSearch, suggestionListId, gSuggestionList, results) {

//    var suggestionList = document.getElementById(suggestionListId);        // suggestion list
//    var gSuggestionList = document.getElementById(gSuggestionList);
//    if (gSuggestionList.hasChildNodes()) {
//        while (gSuggestionList.childNodes.length >= 1) {
//            gSuggestionList.removeChild(gSuggestionList.firstChild);
//        }
//    }


//    for (var i = 0; i < localSearch.results.length; i++) {
//        var div = document.createElement("div")
//        div.innerHTML += localSearch.results[i].title + "|" + localSearch.results[i].city + "|" + localSearch.results[i].country;
//        gSuggestionList.appendChild(div);
//    }
//}

////function SuggestionsGeoCallback(sLocation, suggestionListId, fmnSuggestionListId, data, results, responseCode) {
////    var suggestionList = document.getElementById(suggestionListId);        // suggestion list
////    var fmnSuggestionsList = document.getElementById(fmnSuggestionListId);

////    if (data.length > 0) {
////        var xml = GXml.parse(data);
////        var codes = xml.documentElement.getElementsByTagName("code");

////        for (var i = 0; i < codes.length; i++) {
////            var detailDiv = document.createElement("div");
////            detailDiv.id = "div" + fmnSuggestionListId + i;
////            detailDiv.innerHTML += codes[i].SelectSingleNode("name").value;

////            suggestionList.appendChild(detailDiv);

////            //add to results stack
////            results.push(marker);

////            //GEvent.addListener(marker, "click", function() { markerClicked(mapdetailsid, map, results, this); });

////            //wireup event for clicking div
////            //GEvent.bindDom(detailDiv, "click", detailDiv, function() { itemClicked(mapdetailsid, map, results, this); });
////        }
////    }
////}


////    function SuggestionsALSCallback(sLocation, suggestionListId, fmnSuggestionListId, data, results,responseCode) {
////        var suggestionList = document.getElementById(suggestionListId);        // suggestion list
////        var fmnSuggestionsList = document.getElementById(gSuggestionList);

////        if (data.length > 0) {
////            var xml = GXml.parse(data);
////            var markers = xml.documentElement.getElementsByTagName("marker");

////            for (var i = 0; i < markers.length; i++) {
////                var detailDiv = document.createElement("div");
////                detailDiv.id = "div" + mapdetailsid + i;
////                detailDiv.innerHTML += markers[i].getAttribute("name");

////                suggestionList.appendChild(detailDiv);

////                //add to results stack
////                results.push(marker);

////                //GEvent.addListener(marker, "click", function() { markerClicked(mapdetailsid, map, results, this); });

////                //wireup event for clicking div
////                //GEvent.bindDom(detailDiv, "click", detailDiv, function() { itemClicked(mapdetailsid, map, results, this); });
////            }
////        }
////    }


