﻿var curentCountryCode;
var defaultCountryCode = "DK";
var locationHiddenFieldName = "hfLocationCityname"

var gdir = null; // the GDirections
var lastpoint = null; // the GLatLng point we try to reverse geocode

function initializeLocations() {
    gdir = new GDirections();
    GEvent.addListener(gdir, "load", onGDirectionsLoad);
}

function GetCountryCode() {
    RequestContryCode();
    
    if (!isset(curentCountryCode)) {
        return defaultCountryCode;
    }

    return curentCountryCode;
}

function RequestContryCode() {
    var pointasstring = lastpoint.lat() + "," + lastpoint.lng();
    geocoder.getLocations(pointasstring, SetCountryCode);
}

function onGDirectionsLoad() {
    var nrroutes = gdir.getNumRoutes();

    if (nrroutes != 0) {
        var route = gdir.getRoute(0);
        var nrsteps = route.getNumSteps();

        if (nrsteps != 0) {
            var step = route.getStep(0);

            // 4. returns "Turn east on <b>someroad</b>", so cut out the street 
            // and use it in the GClientGeocoder
            var street = getStreet(step.getDescriptionHtml());
            // The GClientGeoCoder sometimes performs better if we cut out Road, Rd, Rue, Avenue, Way, ...
            // so we will clean the street name with generalize (not working at the moment)
            street = generalizeStreet(street);
            // Add country code, at the end
            street = street + " " + GetCountryCode();
            
            //Search for the streed in Geocoder
            geocoder.getLocations(street, refineStreet);
        }
    }
}

// cuts out the street name from the step.getDescriptionHtml()
// If the street is a highway the surrounding tags are <wbr> instead of <b>
function getStreet(str) {
    var street = str.substring(str.lastIndexOf("<b>") + 3, str.lastIndexOf("</b>"));
    if (street.lastIndexOf("/<wbr/>") > 0) {
        street = street.substring(0, street.lastIndexOf("/<wbr/>"));
    }

    return street;
}

function refineStreet(response) {
    //Clear the Location City Name
    document.getElementById(locationHiddenFieldName).value = "";
    
    if (!response || response.Status.code != 200) {
        return;
    } else {
        // Use the distance between the original saved latlngpoint and each 
        // candidate, and select the one with minimum distance.
        var place = getBestMatchingPlacemark(response);
        // if we have a location search for city name
        if (place != null) {
            if (CheckForLocalityName(place)) {
                document.getElementById(locationHiddenFieldName).value = place.AddressDetails.Country.AdministrativeArea.Locality.LocalityName;
                //alert(document.getElementById(locationHiddenFieldName).value);
            }
        } 
    }
}

function CheckForLocalityName(placeObj)
{
    if (isset(placeObj.AddressDetails)) {
        if (isset(placeObj.AddressDetails.Country)) {
            if (isset(placeObj.AddressDetails.Country.AdministrativeArea)) {
                if (isset(placeObj.AddressDetails.Country.AdministrativeArea.Locality)) {
                    if (isset(placeObj.AddressDetails.Country.AdministrativeArea.Locality.LocalityName)) {
                        return true;
                    }
                }
            }
        }
    }

    return false;
}

function getBestMatchingPlacemark(response) {
    var i = 0;
    var j = -1;
    // the result should be at least within 1 km. 
    var mindist = 1000;
    for (i = 0; i < response.Placemark.length; i++) {
        var place = response.Placemark[i];
        var point = new GLatLng(place.Point.coordinates[1], place.Point.coordinates[0]);
        var temp = lastpoint.distanceFrom(point);
        
        if (temp < mindist) {
            j = i; mindist = temp;
        }
    }

    if (j < 0) return null;
    return response.Placemark[j];
}


// Not used right now 
function generalizeStreet(street) {
    // var temp = street.replace(/straat/,""); 
    // temp = temp.replace(/sesteenweg/,""); 
    // temp = temp.replace(/steenweg/,""); 
    // temp = temp.replace(/weg/,""); 
    // temp = temp.replace(/laan/,"");
    // temp = temp.replace(/rue/,"");

    return street;
}

function SetCountryCode(response) {
    if (!response || response.Status.code != 200) {
        return;
    }

    if (isset(response.Placemark[0])) {
        var place = response.Placemark[0];

        if (isset(place.AddressDetails.Country.CountryNameCode)) {
            curentCountryCode = place.AddressDetails.Country.CountryNameCode;
        }
    }
}
