﻿//
//Global vars
//

var map;            // map
var gdir;           // directions
var gicons = [];    // icons
var gmarkers = [];  // markers
var infoWindow;

// Create an associative array of GIcons()
gicons["yellow"] = new GIcon(G_DEFAULT_ICON, "/images/gmap/marker.gif");
gicons["yellow"].image = "/images/gmap/marker.gif"; 
gicons["yellow"].printImage = "/images/gmap/marker.gif"; 
gicons["yellow"].mozPrintImage = "/images/gmap/marker.gif"; 
gicons["yellow"].transparent = "/images/gmap/marker.gif"; 


//
//    Initialize
//

function InitMap()
{

    // Fade
    infoWindow = ($("infoWindow"));
    //infoWindow.appear({ duration: 0.5});
    
    if (GBrowserIsCompatible()) {
        // create a new instance of a map object
        map = new GMap2(document.getElementById("map"));
        map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());
        map.addControl(new GOverviewMapControl());
        map.setCenter(new GLatLng( 57.781798,14.158510), 6);
        
        // create a new instance of a directions object
        gdir = new GDirections(map);
        GEvent.addListener(gdir, "load", onGDirectionsLoad);
        GEvent.addListener(gdir, "error", handleErrors);

        readXML();
    }
    else {
        alert("Sorry, the Google Maps API is not compatible with this browser");
    }
}

//
//    Load data
//
function readXML()
{
    // Read XML
    var request = GXmlHttp.create();
    //request.open("GET", "/js/gmap/data.xml", true);
    request.open("GET", "http://www.ejmunds.se/gmapData.aspx", true);

    // When ready
    request.onreadystatechange = function() {
        if (request.readyState == 4) {
            var xmlDoc = GXml.parse(request.responseText);

            // obtain the array of markers and loop through it
            var markers = xmlDoc.documentElement.getElementsByTagName("Placemark");
            var icontype = "yellow";    // set icontype

            for (var i = 0; i < markers.length; i++) {
                var id =xmlDoc.getElementsByTagName("Placemark")[i].attributes.getNamedItem("id").nodeValue;
                var label = GXml.value(markers[i].getElementsByTagName("name")[0]);
                var description = GXml.value(markers[i].getElementsByTagName("description")[0]);

                // Dela upp koordinater och skapa Pointer
                var coordinates = GXml.value(markers[i].getElementsByTagName("Point")[0]);
                var splitResult = coordinates.split(",");
                var lat = parseFloat(splitResult[0]);
                var lng = parseFloat(splitResult[1]);
                var point = new GLatLng(lat,lng);

                // Skapa markör
                var marker = createMarker(id, point,label,description,icontype, lat, lng);
                map.addOverlay(marker);
            }
        }
    };
    request.send(null);
}

//
//  Create marker
//
function createMarker(id, point,label,description,icontype,  lat, lng) {
    var marker = new GMarker(point,gicons[icontype]);

    GEvent.addListener(marker, 'click', function(){ 
        clearMap();
        map.panTo(new GLatLng( lat,lng));

        var html = "";
        html += "<a href=\"#\" id=\"infoWindoClose\" onclick=\"clearMap();fadeInfoWindow();\"><img src=\"/images/gmap/iconClose.png\" /></a>";
        html += "<h2>" + label + "</h2>";
        html += "<p class=\"strong\">Kontaktuppgifter</p>";
        html += "<p>" + description + "</p>";
        html += "<p class=\"strong\">Vägbeskrivning -varifrån åker du?</p>";
        html += "<input type=\"text\" id=\"from\"/>";
        html += "<input type=\"hidden\" id=\"to\" value=\"" + lat + "," + lng + "\" />";
        //html += "<a href=\"#\" onclick=\"setDirections($('from').value, $('to').value);\">visa vägbeskrivning</a>";
        html +="<input type=\"submit\" value=\"Visa\" class=\"submit\" onclick=\"setDirections($('from').value, $('to').value);\" />";
        
        html += "<div id=\"directions\"></div>";
        
        $('infoWindowData').innerHTML = html;
        $('infoWindow').appear({ duration: 0});
    });
    return marker;
}

// Fade div#infowindow
function fadeInfoWindow() {
    infoWindow.fade({ duration: 0 });
}

function setDirections(fromAddress, toAddress) {
    if (fromAddress == "")
        alert("Du måste ange varifrån du åker.");
    else
        gdir.load("from: " + fromAddress + " to: " + toAddress, { "getSteps": true, "getPolyline":true });
}

//
//  GDir onload 
//
function onGDirectionsLoad(){ 
    
	var groute = gdir.getRoute(0);
    
    // Clear old markers
    if (gmarkers.length > 0)
    {
        for (var i=0;i<gmarkers.length;i++)
            gmarkers[i].remove();
    }
    
    // Create html
    var html = "";
    html += "<p class='strong'>" + groute.getSummaryHtml() + "</p>";
    html += "<table id=\"routestops\">";

    // Loop steps
    for (var i=0;i<groute.getNumSteps();i++)
    {
        var gstep = groute.getStep(i);
        var count = i + 1;
        
        var description = gstep.getDescriptionHtml();
        var distance = gstep.getDistance();
        
        // Skapa markör
        var iconOptions = {};
        iconOptions.width = 32;
        iconOptions.height = 32;
        iconOptions.primaryColor = "#666666";
        iconOptions.label = count.toString();
        iconOptions.labelSize = 0;
        iconOptions.labelColor = "#FFFFFF";
        iconOptions.shape = "circle";
        var newIcon = MapIconMaker.createFlatIcon(iconOptions);
        var marker = new GMarker(gstep.getLatLng(), {icon: newIcon});
        map.addOverlay(marker);
        gmarkers[i] = marker;
    
        if (i%2 == 0)
            html += "<tr class=\"odd\">";
        else
            html += "<tr>";
        html += "<td><a href=# onclick=\"zoomWayPoint(" + i + ")\">" +  count + "</a></td><td>" + description + "</td><td>" + distance.html + "</td>";
        html += "</tr>";
    }
    html += "</table>";
    $('directions').innerHTML = html;
}

//
//  Zoom active waypoint
//
function zoomWayPoint(i) {
	/* get lat and lng from active marker, zoom and move */
	var lat = gmarkers[i].getLatLng().lat();
    var lng = gmarkers[i].getLatLng().lng();
    map.setZoom(17);
    map.panTo(new GLatLng( lat,lng));
}

//
//  Clear map
//
function clearMap() {
    gdir.clear();
    
    // remove all old markers
    if (gmarkers.length > 0)
    {
        for (var i=0;i<gmarkers.length;i++)
        {
            gmarkers[i].remove();
        }
	}
}

//
//  Errors
//
function handleErrors(){
    if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
    {
        var info = "";
        info += "Din sökning gav tyvärr ingen träff.\r\n\r\n";
        info += "Tips:\r\n";
        info += "- kontrollera din stavning\r\n";
        info += "- försök att lägga till ett tätsortnamn\r\n\r\n";
        alert(info);
    }
    else if (gdir.getStatus().code == G_GEO_SERVER_ERROR)
        alert("A geocoding or directions request could not be successfully processed, yet the exact reason for the failure is not known.\n Error code: " + gdir.getStatus().code);
       
    else if (gdir.getStatus().code == G_GEO_MISSING_QUERY)
        alert("The HTTP q parameter was either missing or had no value. For geocoder requests, this means that an empty address was specified as input. For directions requests, this means that no query was specified in the input.\n Error code: " + gdir.getStatus().code);

    //   else if (gdir.getStatus().code == G_UNAVAILABLE_ADDRESS)  <--- Doc bug... this is either not defined, or Doc is wrong
    //        alert("The geocode for the given address or the route for the given directions query cannot be returned due to legal or contractual reasons.\n Error code: " + gdir.getStatus().code);

    else if (gdir.getStatus().code == G_GEO_BAD_KEY)
        alert("The given key is either invalid or does not match the domain for which it was given. \n Error code: " + gdir.getStatus().code);

    else if (gdir.getStatus().code == G_GEO_BAD_REQUEST)
        alert("A directions request could not be successfully parsed.\n Error code: " + gdir.getStatus().code);

    else {
        var info = "";
        info += "Ett fel uppstod.\r\n\r\n";
        info += "Tips:\r\n";
        info += "- Ladda om sidan och försök igen\r\n";
        info += "- kontrollera din stavning\r\n";
        info += "- försök att lägga till ett tätsortnamn\r\n\r\n";
        alert(info);
     }
}
