//key = "ABQIAAAA_w84ntTz1ZjFLMnVVQ4cqBRmseRy5c531oK1pZeVkl3JJIkl0RRKL0wTJbRsMWVh7ScBIx725Ra9bw"; // prag.int
//key = "ABQIAAAAW7sk457DFEy5DT_tKNhs6xTqKgQkDrUlzLyR2prH9zBPNJ2GTBQ7bfQx_wy8K9UCrsU9KJVb8zBC2Q"; // s-is6.interaktiv-service.com
//key = "ABQIAAAAW7sk457DFEy5DT_tKNhs6xS6v8eHQSNmEZWIVa6PPKPFftQmTBQ2XrWgjqS19Yr9YodBvvb4h4-vCg"; // www.serview.de (old)
key = "ABQIAAAAW7sk457DFEy5DT_tKNhs6xRy1KF8shuUycBZDjNpDOtAz5a2qhSvDrc4mxsAB9ienUmiSSifmiqIQw"; // www.serview-institute.de
document.write('<'+'script type="text/javascript" src="http://maps.google.com/maps?file=api&amp;v=2&amp;key='+key+'"><'+'/script>');

var side_bar_html = "";
var gmarkers = [];
var htmls = [];
var i = 0;
// arrays to hold variants of the info window html with get direction forms open
var to_htmls = [];
var from_htmls = [];
var blueIcon = [];
var gelb = [];
var icons = [];
var map = [];
var gdir = [];
var reasons = [];


// ===== request the directions =====
function getDirections() {
    var saddr = document.getElementById("saddr").value
        var daddr = document.getElementById("daddr").value
        gdir.load("from: "+saddr+" to: "+daddr);
}

function myclick(i) {
    gmarkers[i].openInfoWindowHtml(htmls[i]);
}

// functions that open the directions forms
function tohere(i) {
    gmarkers[i].openInfoWindowHtml(to_htmls[i]);
}
function fromhere(i) {
    gmarkers[i].openInfoWindowHtml(from_htmls[i]);
}


function load() {
    window.onunload = GUnload;
    if (GBrowserIsCompatible()) {
        // Create some custom icons

        // This icon uses the same shape as the default Google marker
        // So we can use its details for everything except the image 
        blueIcon = new GIcon();
        blueIcon.image = "coldmarker.png";
        blueIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
        blueIcon.iconSize = new GSize(20, 34);
        blueIcon.shadowSize = new GSize(37, 34);
        blueIcon.iconAnchor = new GPoint(9, 34);
        blueIcon.infoWindowAnchor = new GPoint(9, 2);
        blueIcon.infoShadowAnchor = new GPoint(18, 25);
        blueIcon.transparent = "http://www.google.com/intl/en_ALL/mapfiles/markerTransparent.png";
        blueIcon.printImage = "coldmarkerie.gif";
        blueIcon.mozPrintImage = "coldmarkerff.gif";


        // This icon is a different shape, so we need our own settings       
        gelb = new GIcon();
        gelb.image = "google-serview-logo.png";
        gelb.iconSize = new GSize(107, 56);
        gelb.iconAnchor = new GPoint(9, 56);
        gelb.infoWindowAnchor = new GPoint(8, 35);


        // An array of GIcons, to make the selection easier
        icons = [];
        icons[0] = blueIcon;
        icons[1] = gelb;

        // the icon information is passed to this function
        function createMarker(point,name,html,icontype) {
            var marker = new GMarker(point,icons[icontype]);
            GEvent.addListener(marker, "click", function() {
                    marker.openInfoWindowHtml(html);
                    });


            // The info window version with the "to here" form open
            to_htmls[i] = html + '<'+'br><'+'br><'+'b>Route berechnen:<'+'/b> <'+'b>Hierher<'+'/b> - <'+'a href="javascript:fromhere(' + i + ')">Von hier<'+'/a>' +
                '<'+'br>Startadresse:<'+'form action="javascript:getDirections()">' +
                '<'+'input type="text" SIZE=40 MAXLENGTH=40 name="saddr" id="saddr" value="" /><'+'br>' +
                '<'+'INPUT value="Route berechnen" TYPE="SUBMIT">' +
                '<'+'input type="hidden" id="daddr" value="'+name+"@"+ point.lat() + ',' + point.lng() + 
                '"/>';
            // The info window version with the "to here" form open
            from_htmls[i] = html + '<'+'br><'+'br><'+'b>Route berechnen:<'+'/b> <'+'a href="javascript:tohere(' + i + ')">Hierher<'+'/a> - <'+'b>Von hier<'+'/b>' +
                '<'+'br>Zieladresse:<'+'form action="javascript:getDirections()">' +
                '<'+'input type="text" SIZE=40 MAXLENGTH=40 name="daddr" id="daddr" value="" /><'+'br>' +
                '<'+'INPUT value="Route berechnen" TYPE="SUBMIT">' +
                '<'+'input type="hidden" id="saddr" value="'+name+"@"+ point.lat() + ',' + point.lng() +
                '"/>';
            // The inactive version of the direction info
            html = html + '<'+'br><'+'br><'+'b>Route berechnen:<'+'/b> <'+'a href="javascript:tohere('+i+')">Hierher<'+'/a> - <'+'a href="javascript:fromhere('+i+')">Von hier<'+'/a>';

            GEvent.addListener(marker, "click", function() {
                    marker.openInfoWindowHtml(html);
                    });

            // save the info we need to use later for the side_bar
            gmarkers[i] = marker;
            htmls[i] = html;
            // add a line to the side_bar html
            side_bar_html += '<'+'li><'+'a href="javascript:myclick(' + i + ')">' + name + '<'+'/a><'+'/li>';
            i++;
            return marker;
        }


        // create the map
        map = new GMap2(document.getElementById("map"));
        map.addControl(new GLargeMapControl());
        map.addControl(new GMapTypeControl());
        map.setCenter(new GLatLng(50.213616,8.653536), 5);

        // === create a GDirections Object ===
        gdir=new GDirections(map, document.getElementById("directions"));

        // === Array for decoding the failure codes ===
        reasons=[];
        reasons[G_GEO_SUCCESS]            = "Erfolg";
        reasons[G_GEO_MISSING_ADDRESS]    = "Adresse fehlt.";
        reasons[G_GEO_UNKNOWN_ADDRESS]    = "Unbekannte Adresse.";
        reasons[G_GEO_UNAVAILABLE_ADDRESS]= "Adresse nicht verfügbar.";
        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 geocoding request could not be successfully processed.";
        reasons[G_GEO_BAD_REQUEST]        = "Routenberechnung fehlerhaft.";
        reasons[G_GEO_MISSING_QUERY]      = "Keine Suchanfrage angegeben..";
        reasons[G_GEO_UNKNOWN_DIRECTIONS] = "Route kann zwischen diesen Punkten nicht berechnet werden.";

        // === catch Directions errors ===
        GEvent.addListener(gdir, "error", function() {
                var code = gdir.getStatus().code;
                var reason="Code "+code;
                if (reasons[code]) {
                reason = reasons[code]
                } 

                alert("Keine Routenberechnung möglich: "+reason);
                });


        // Read the data from xml
        var request = GXmlHttp.create();
        request.open("GET", "standorte.xml", true);
        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("marker");

                for (var i = 0; i < markers.length; i++) {
                    // obtain the attribues of each marker
                    var lat = parseFloat(markers[i].getAttribute("lat"));
                    var lng = parseFloat(markers[i].getAttribute("lng"));
                    var point = new GLatLng(lat,lng);
                    var html = markers[i].getAttribute("html");
                    var label = markers[i].getAttribute("label");
                    var icontype = parseInt(markers[i].getAttribute("icontype"));
                    // create the marker
                    var marker = createMarker(point,label,html,icontype);
                    map.addOverlay(marker);
                }
                // put the assembled side_bar_html contents into the side_bar div
                document.getElementById("side_bar").innerHTML = side_bar_html;
            }
        }
        request.send(null);
    } else {
        alert("Sorry, the Google Maps API is not compatible with this browser");
    }
}

window.onload = load;
