/*
TODOs:
- your location
- route
- placeholder while loading
- smoothscroll zoom http://groups.google.com/group/Google-Maps-API/msg/916c10efa38d8a9a
*/

var myplacemarks = new Array(); //cache placemarks
var map;

try {
    var baseIcon = new GIcon();
    baseIcon.image = "http://www.riccione.nl/images/icon-map-house.png";
    baseIcon.iconSize = new GSize(30, 29);
    baseIcon.iconAnchor = new GPoint (15, 15);
    baseIcon.infoWindowAnchor = new GPoint (9, 2);
} catch(e){}

function loadGeo(){
    //document.getElementById("map").style.display = "none";
    //document.getElementById("mapplaceholder").style.display = "block";
    if (GBrowserIsCompatible()) {
        map = new GMap(document.getElementById("map"));
        map.enableContinuousZoom(); //smooth zoom
        overviewMapPosition();//load map controls
        map.setMapType(G_NORMAL_MAP); //G_NORMAL_MAP, G_SATELLITE_MAP, G_HYBRID_MAP

        showStartPosition();
        //showDebugInfo();//debug

        var khandler = new KMLHandler(map); //load placemarks
        khandler.addFeed("/Googleearth.kml");
    }

}

function showDebugInfo(){
    //show latitude and longitude in div "message"
    GEvent.addListener(map, "moveend", function() {
            var center = map.getCenter();
            var latLngStr = '<font face=Verdana size=1>( Lat/Long: ' + center.y + ', ' + center.x + ')</font>';
            debug(latLngStr);
        });
}
function debug(value){
    //Glog
    document.getElementById("debug").innerHTML = value;
}
function add2debug(value){
    //TODO Glog
    debug(document.getElementById("debug").innerHTML+value);
}

/* small control */
function overviewMapPosition() {
    ovmap = new GOverviewMapControl();
    map.addControl(ovmap,new GControlPosition(G_ANCHOR_BOTTOM_LEFT));
    map.addControl(new TextualZoomControl()); // text zoomin/zoomout
    map.addControl(new GMapTypeControl()); //type map
    var ovmap = document.getElementById("map_overview");
    if(ovmap) {
        ovmap.style.position = "absolute";
        // == restyling ==
        ovmap.firstChild.style.border = "1px solid gray";
        ovmap.firstChild.firstChild.style.left="4px";
        ovmap.firstChild.firstChild.style.top="4px";
        var mapdiv = document.getElementById("map");
        mapdiv.appendChild(ovmap);
    }
}

function showStartPosition(){
    var ctrLat = 44.009854751;
    var ctrLng = 12.668094;
    var ctrZoom = 4; //smaller is zoomin. 5=italy+NL, 13=riccione
    map.centerAndZoom(new GLatLng(ctrLat,ctrLng), ctrZoom );
}

function showWelcome(){
    var icon = new GIcon(baseIcon);
    var text = "Riccione (Italie).<br>Klik <a href='#showmap' onClick='zoomInToRiccione()'>hier</a> om in te zoomen.";
    icon.image = "http://www.riccione.nl/images/spacer.gif";
    welcomeMarker = new GxMarker( new GPoint(ctrLng,ctrLat),icon, text);
    welcomeMarker.showTooltip();
    GEvent.addListener(welcomeMarker, "click", function() {
        map.setCenter(new GLatLng(ctrLat,ctrLng), 5);
        //welcomeMarker.hideTooltip();
        //welcomeMarker.remove();
    });
    map.addOverlay(welcomeMarker);
    map.setCenter(new GLatLng(ctrLat,ctrLng), ctrZoom );
}
function zoomInToRiccione(){
    welcomeMarker.hideTooltip();
    //map.closeInfoWindow();
    var center = map.getCenter();
    map.setCenter(new GLatLng(center.x, center.y), zoom);
}

function createMarker(point, iconpath, info, address) {
    var icon = new GIcon(baseIcon);
    icon.image = iconpath;
    var marker = new GxMarker( point, icon, address );
    GEvent.addListener(marker, "click", function() {
        //map.setCenter(point, 17);
        //map.panTo(point);////
        marker.openInfoWindowHtml(info);
    });
    map.addOverlay(marker);
    return marker;
}

function KMLNSResolver(prefix) {
    if(prefix == 'kml') return "http://earth.google.com/kml/2.0";
    return null;
}

//Represents a KML feed. Used internally by KMLHandler.
function KMLFeed(map, url) {
    this.map = map;
    this.url = url;
    this.overlays = new Array();
    this.request = undefined;

    this.handleKML = function(data, response) {
        //Delete existing overlays
        for(var i in this.overlays) {
            //this.overlays[i].destroy();
            //map.removeOverlay(this.overlays[i]);
        }
        this.overlays = new Array();

        //Populate with elements in the updated feed
        var doc = GXml.parse(data);

        var bounds = undefined;
        var thedocument = doc.documentElement.getElementsByTagName("Document")[0];

        icons = thedocument.getElementsByTagName("Style");
        var IconsArray = new Array();
        for(var i = 0; i < icons.length; i++) {
            IconsArray[icons[i].getAttribute("id")] = icons[i].childNodes[1].childNodes[1].childNodes[1].childNodes[0].nodeValue;
        }

        var folders = thedocument.getElementsByTagName("Folder");
        for(var f = 0; f < folders.length; f++) {
            placemarks = folders[f].getElementsByTagName("Placemark");
            groupname = folders[f].getElementsByTagName("name")[0].firstChild.nodeValue
            myplacemarks[groupname] = new Array();
            for(var i = 0; i < placemarks.length; i++) {
                var point = placemarks[i].getElementsByTagName("Point")[0];
                var coords = point.getElementsByTagName("coordinates")[0].childNodes[0].nodeValue;
                coords = coords.split(",");
                var name = placemarks[i].getElementsByTagName("name")[0].childNodes[0].nodeValue;
                var description = placemarks[i].getElementsByTagName("description")[0].childNodes[0].nodeValue;
                var iconUrl = placemarks[i].getElementsByTagName("styleUrl")[0].childNodes[0].nodeValue;
                iconUrl = iconUrl.substr(1, iconUrl.length);
                var point = new GLatLng(parseFloat(coords[1]), parseFloat(coords[0]));

                var marker = new Object();
                marker.point = point;
                marker.icon = IconsArray[iconUrl];
                marker.info = name;
                marker.gxmarker = createMarker(point, IconsArray[iconUrl], description, name);
                myplacemarks[groupname][i] = marker;

                map.addOverlay(marker.gxmarker);
                if (!bounds) {
                    bounds = GBounds(point);
                } else {
                    bounds.extend(point);
                }
                this.overlays.push(marker.gxmarker);
            }
            fillMenu(myplacemarks[groupname],groupname);
        }
        //map.setCenter(new GLatLng((bounds.maxX-bounds.minX)/2, (bounds.maxY-bounds.minY)/2));
        //document.getElementById("mapplaceholder").style.display = "none";
        //document.getElementById("mapplaceholder").style.visibility = "hidden";
        //document.getElementById("map").style.display = "block";
    }

    //Triggers whenever the map is moved or zoomed.
    //Also manually invoked when the feed is first created to initially populate
    //the feed.

    //this.onMapChange = function() {
    this.reloadContent = function() {
        //Trigger fetching the new map
        if(this.request != undefined) {
            this.request.abort();
        }

        url = this.url;
        bounds = map.getBounds();

        var _this = this;
        GDownloadUrl(url, _this.handleKML);

    }


    this.destroy = function() {
        GEvent.removeListener(this.moveendListener);

        //for(var i in this.overlays) this.overlays[i].destroy();
    }

    //Fetch the feed for the first time
    //this.onMapChange();
    this.reloadContent();

    //Add event handlers
    this.moveendListener = GEvent.bind(map, 'moveend', this, this.onMapChange);
}

function getChildrenByTagName(node,tag) {
    var l = new Array();
    for(var i = 0; i < node["chd"].length; i++) {
        var child = node["chd"][i];
        if (child["tag"] == tag) {
            l.push(child);
        }
    }
    return l;
}

//A KMLHandler handles (fetching, updating) KML feeds for a map
function KMLHandler(map) {
    this.map = map;
    this.feeds = [];

    this.addFeed = function(url) {
        //Add the feed to the feeds array
        this.feeds[url] = new KMLFeed(this.map, url);
    }

    this.addKML = function(url) {
        //Add the feed to the feeds array
        this.feeds[url] = new KMLFeed(this.map, url);
    }

    this.addJSON = function(url) {
        //Add the feed to the feeds array
        this.feeds[url] = new JSONFeed(this.map, url);
    }

    this.removeFeed = function(url) {
        //Remove the feed from the feeds array
        this.feeds[url].destroy();
        delete this.feeds[url];
    }
}

function fillMenu(markerArray,groupname){
    var items = "";
    //items
    for (var i = 0; i < markerArray.length; i++) {
            try {
                img = markerArray[i].icon;
            } catch(e) {
                img = "/images/icon-map-flag.png";
            }
            items += '<img src="/images/spacer.gif" width="20" height="15"/>'+
                    '<img src="'+img+'" width="15" height="15" align="bottom"/>'+
                    '<img src="/images/spacer.gif" width="2" height="15"/>'+
                    '<a href="#showmap" onclick="showLocation(\''+groupname+'\','+i+');" '+
                    'onmouseover="myMouseOver(\''+groupname+'\','+i+');" '+
                    'onmouseout="myMouseOut(\''+groupname+'\','+i+');" id="'+groupname+i+'">'+
                    markerArray[i].info+
                    '</a><br class="noclear"/>';
    }
    //header
    try {
        imgurl = markerArray[markerArray.length-1].icon;
    } catch (e) {
        imgurl = "/images/icon-map-flag.png";
    }
    container = '<img src="/images/spacer.gif" width="20" height="5" border=0/> ' +
             '<span onclick="OpenClose(\''+groupname+'\')" style="display: block;">'+
             '<img src="/images/spacer.gif" width="8" height="20" border=0/> ' +
             '<img src="/images/expand.gif" alt="open" id="expand_'+groupname+'" width="11" height="11"/> ' +
             '<img src="/images/spacer.gif" width="4" height="20" border=0/> ' +
             '<img src="'+imgurl+'" width="20" height="20" border=0 align="bottom"/>'+
             '<img src="/images/spacer.gif" width="4" height="2" border=0><b>'+groupname+'</b> ' +
             '</span> <div id="div_'+groupname+'" style="display: none;">'+items+'</div>';
    add2sidebar(container);
}

function add2sidebar(value){
    document.getElementById("sidebar").innerHTML = document.getElementById("sidebar").innerHTML+value;
}

function myMouseOver(groupname,indexnr) {
    myMarker = myplacemarks[groupname][indexnr];
    myMarker.gxmarker.showTooltip();
    showStartPosition();
}
function myMouseOut(groupname,indexnr) {
    myMarker = myplacemarks[groupname][indexnr];
    myMarker.gxmarker.hideTooltip();
}
function showLocation(groupname,indexnr){
    document.getElementById(groupname+indexnr).style.fontWeight = "bold";
    myMarker = myplacemarks[groupname][indexnr];
    //todo show marker and tooltip it
    map.setCenter(new GLatLng(myMarker.point.y,myMarker.point.x),13);
    //myMarker.gxmarker.openInfoWindowHtml(myMarker.info);
    //map.panTo(myMarker.gxmarker);
}

/**
 * A TextualZoomControl is a GControl that displays textual "Zoom In" and "Zoom Out" buttons (as opposed to the iconic buttons used in Google Maps).
 */

function TextualZoomControl() {}
TextualZoomControl.prototype = new GControl();

// Creates a one DIV for each of the buttons and places them in a container
// DIV which is returned as our control element. We add the control to
// to the map container and return the element for the map class to
// position properly.
TextualZoomControl.prototype.initialize = function(map) {
  var container = document.createElement("div");

  var zoomInDiv = document.createElement("div");
  this.setButtonStyle_(zoomInDiv);
  container.appendChild(zoomInDiv);
  zoomInDiv.appendChild(document.createTextNode("Zoom In"));
  GEvent.addDomListener(zoomInDiv, "click", function() {
    map.zoomIn(false,true);
  });

  var zoomOutDiv = document.createElement("div");
  this.setButtonStyle_(zoomOutDiv);
  container.appendChild(zoomOutDiv);
  zoomOutDiv.appendChild(document.createTextNode("Zoom Out"));
  GEvent.addDomListener(zoomOutDiv, "click", function() {
    map.zoomOut(false,true);
  });

  map.getContainer().appendChild(container);
  return container;
}

// By default, the control will appear in the top left corner of the
// map with 7 pixels of padding.
TextualZoomControl.prototype.getDefaultPosition = function() {
  return new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(7,7));
}

// Sets the proper CSS for the given button element.
TextualZoomControl.prototype.setButtonStyle_ = function(button) {
  button.style.textDecoration = "underline";
  button.style.color = "black";
  button.style.backgroundColor = "white";
  button.style.font = "small Arial";
  button.style.border = "1px solid black";
  button.style.padding = "2px";
  button.style.marginBottom = "3px";
  button.style.textAlign = "center";
  button.style.width = "6em";
  button.style.cursor = "pointer";
}

/* auto resize window */
/*window.onresize = autoResizeHeights;
function autoResizeHeights() {
    var NS = getWindowSize();
    document.getElementById("map").style.height = (NS.height - 200) + 'px';
    document.getElementById("map").style.width  = (NS.width  - 415) + 'px';
}
function getWindowSize() {
    var e = new Object();
    if(window.self && self.innerWidth) {
      e.width = self.innerWidth;
      e.height = self.innerHeight;
    } else if(document.documentElement && document.documentElement.clientHeight) {
      e.width = document.documentElement.clientWidth;
      e.height = document.documentElement.clientHeight;
    } else {
      e.width = document.body.clientWidth;
      e.height = document.body.clientHeight;
    }
    return e;
}*/