var map;
var geocoder;
var fromadress;
var toadress;
var duration;
var distance;
var directionsDisplay;
var directionsService;
var distanceMatrixservice; 

function initialize() {
    directionsService = new google.maps.DirectionsService();
    geocoder = new google.maps.Geocoder();
    var mCenter = new google.maps.LatLng(latStart, lngStart);
    var myOptions = {
        zoom: zoomStart,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        center: mCenter
    };
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
		
    distanceMatrixService = new google.maps.DistanceMatrixService();

    var rendererOptions = {
        draggable: true
    };
    directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
    directionsDisplay.setMap(map);
      
      //For draggable markers
    google.maps.event.addListener(directionsDisplay, 'directions_changed', function() {
        getAdress(directionsDisplay.directions);
    });

    userDirections();
}

function userDirections () {
    var start_address = document.getElementById("fromAddress").value +', Sverige';
    var end_address = document.getElementById("toAddress").value +', Sverige';


    var dirRequest = {
        origin:start_address, 
        destination:end_address,
        travelMode: google.maps.DirectionsTravelMode.DRIVING
    };
    
    
    directionsService.route(dirRequest, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {    
            directionsDisplay.setDirections(response);
        }
    });
}

function getAdress (results){
    var myroute = results.routes[0];
    var start_address = myroute.legs[0].start_address;
    var end_address = myroute.legs[0].end_address;
    setDirections(start_address, end_address);
}


// ===== list of words to be standardized =====
var standards = [ 
["vägen","v"],
["gata","g"],
["en","e"],
["gata","ga"],
];

// ===== convert words to standard versions =====
function standardize(a) {
    for (var i=0; i<standards.length; i++) {
        if (a == standards[i])  {
            a = standards[i];
        }
    }
    return a;
}

// ===== check if two addresses are sufficiently different =====
function different(a,b) {
    // only interested in the bit before the first comma in the reply
    var c = b.split(",");
    b = c[0];
    // convert to lower case
    a = a.toLowerCase();
    b = b.toLowerCase();
    // remove apostrophies
    a = a.replace(/'/g ,"");
    b = b.replace(/'/g ,"");
    // replace all other punctuation with spaces
    a = a.replace(/\W/g," ");
    b = b.replace(/\W/g," ");
    // replace all multiple spaces with a single space
    a = a.replace(/\s+/g," ");
    b = b.replace(/\s+/g," ");
    // split into words
    awords = a.split(" ");
    bwords = b.split(" ");
    // perform the comparison
    var reply = false;
    for (var i=0; i<bwords.length; i++) {
        //GLog.write (standardize(awords[i])+"  "+standardize(bwords[i]))
        if (standardize(awords[i]) != standardize(bwords[i])) {
            reply = true;        
        }           
    }
    //GLog.write(reply);
    return (reply);
}

String.prototype.extractNumbers = function(returnType){
    var i, l = this.length, t = isNaN(returnType), r = "";
    for (i=0; i<l; i++) if (isNaN(this.charAt(i)) == t) r += this.charAt(i);
    return (t) ? r : Number(r);
}

// ====== Geocoding ======
function showAddress(field, div) {
    var search = document.getElementById(field).value;
    document.getElementById(div).style.visibility = 'hidden';
    if (search != ""){
        search = search + ",Sverige";
        // ====== Perform the Geocoding ======
        geocoder.geocode({
            'address': search
        }, function (results, status)

        {
            if (status == google.maps.GeocoderStatus.OK) {
            
                // ===== If there was more than one result, "ask did you mean" on them all =====
                if (results.length > 1) {
                    document.getElementById(div).style.visibility = 'visible';
                    document.getElementById(div).innerHTML = "Menar du: ";
                    // Loop through the results
                    for (var i=0; i<results.length; i++) {
                        //Varje adress, ta bort "Sverige" från strängen, samt skriv inte ut strängen om bara gatan finns i svaret
                        var searchadress = results[i].formatted_address;
                        searchadress = searchadress.substring(0,searchadress.length-8);
                        var coordinates = results[i].geometry.location;
                        if (searchadress.indexOf(',') != -1){
                            //searchadress = searchadress.extractNumbers("a");
                            var searcharray = new Array();
                            searcharray [i] = searchadress;
                            document.getElementById(div).innerHTML += "<br>"+"<a href=\"JavaScript:setUserAddress('"+searchadress+"','"+field+"','"+div+"','"+coordinates.lng()+"','"+coordinates.lat()+"')\">" + searchadress+"<\/a>";
 
                        }
                    }
                }
                // ===== If there was a single marker, is the returned address significantly different =====
                else {
                    document.getElementById(div).innerHTML = "";
                    if (different(search, results[0].formatted_address)) {
                        searchadress = results[0].formatted_address;
                        searchadress = searchadress.substring(0,searchadress.length-8);
                        var coordinates = results[0].geometry.location;
                        document.getElementById(div).style.visibility = 'visible';
                        document.getElementById(div).innerHTML = "Menade du: ";
                        document.getElementById(div).innerHTML += "<br>"+"<a href=\"JavaScript:setUserAddress('"+searchadress+"','"+field+"','"+div+"','"+coordinates.lng()+"','"+coordinates.lat()+"')\">" + searchadress+"<\/a>";
                    }
                    else {
                        userDirections();
                        
                        document.getElementById(div).innerHTML = "";
                    }
                }
            }
            // ====== Decode the error status ======
            else {
                document.getElementById(div).innerHTML = "";
                var reason="Code "+ status;
                document.getElementById(div).style.visibility = 'visible';
                document.getElementById(div).innerHTML = reason;
            }
        }
        );
    }
}

function setUserAddress (adress, field, div, lat , lng){
    document.getElementById(field).value = adress;
    document.getElementById(div).style.visibility = 'hidden';
    document.getElementById(div).innerHTML = "";
    //Gör om lat lng till ett objekt som sedan kan sättas in i gdir
    point = new google.maps.LatLng(lat,lng);
    if (field == "toAddress"){  
        
        userDirections ();
        document.getElementById("searchError").innerHTML = "";
        savetoAddressToSession(adress);
    }
    else if (field == "fromAddress"){
        document.getElementById("searchError").innerHTML = "";
        savefromAddressToSession(adress);
        userDirections ()
    }
}

    

function distanceMatrixCallback(response, status) {
    if (status != google.maps.DistanceMatrixStatus.OK) {
        alert('Error was: ' + status);
    }    
    else {
        var origins = response.originAddresses;
        var destinations = response.destinationAddresses;

        for (var i = 0; i < origins.length; i++) {
            var results = response.rows[i].elements;
            for (var j = 0; j < results.length; j++) {
                distance = results[j].distance.value/1000;
                duration = results[j].duration.value/3600;
            }
        }
        startadress = origins.toString().substring(0,origins.toString().length - 8);
        slutadress = destinations.toString().substring(0,destinations.toString().length - 8);;
        makeRequest();
    }
}

function setDirections(fromAddress, toAddress){   
    distanceMatrixService.getDistanceMatrix(
    {
        origins: [fromAddress],
        destinations: [toAddress],
        travelMode: google.maps.TravelMode.DRIVING,
        unitSystem: google.maps.UnitSystem.METRIC,
        avoidHighways: false,
        avoidTolls: false
    }, distanceMatrixCallback);    
}

