var map;
var rendered = [];
var gmarkers = [];
var htmls = [];
var alltabs = [];
var icons = [];
var icons_ie = [];
var gmcount = 0;
var icbase="http://www.wedel-fuer-kinder.de/images/";

var baseIcon = new GIcon();
//baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
baseIcon.iconSize = new GSize(32, 32);
baseIcon.shadowSize = new GSize(59, 32);
baseIcon.iconAnchor = new GPoint(16, 32);
baseIcon.infoWindowAnchor = new GPoint(16, 2);
baseIcon.infoShadowAnchor = new GPoint(18, 25);

var ic=new Array();

for (var i=0;i<8;i++) {
    ic[i]=new GIcon(baseIcon);
    ic[i].image=icbase+icix_to_icid(i)+".png";
}

function icid_to_icix(icid) {
  switch (icid) {
   case "sp": return 0;
   case "spball": return 1;
   case "spballfoto": return 2;
   case "spballpano": return 3;
   case "spfoto": return 4;
   case "spnb": return 5;
   case "spnbball": return 6;
   case "sppano": return 7;
   default: return -1;
  }
}

function icix_to_icid(icix) {
  switch (icix) {
   case 0: return "sp";
   case 1: return "spball";
   case 2: return "spballfoto";
   case 3: return "spballpano";
   case 4: return "spfoto";
   case 5: return "spnb";
   case 6: return "spnbball";
   case 7: return "sppano";
   default: return "";
  }
}


function gmclick(i) {
  render(i);
  if (alltabs[i]) {
    gmarkers[i].openInfoWindowTabsHtml(alltabs[i],{maxWidth:430});
  } else {
    gmarkers[i].openInfoWindowHtml(htmls[i],{maxWidth:430});
  }
}

function render(count) {
	if (!rendered[count]) {		
	        var startmatch = /^((?:.|\n|\r)*?)<hr>[^<]*<img/i;
	        var imgmatch = /<hr>([^<]*<img[^>]*>[^<]*)/gi;

	        var firsttab = startmatch.exec(htmls[count]);
	        if (firsttab) { //multitab
			var tabs = [];
			var imgtabs;
			var i=0;
			tabs.push(new GInfoWindowTab("Info",firsttab[1]));

			while ((imgtabs = imgmatch.exec(htmls[count])) && (i<3)) {
				i++;
				tabs.push(new GInfoWindowTab("Bild "+i,imgtabs[1]));
			}
			if (imgtabs) { //sum remaining pictures in last tab
				var tabhtml=imgtabs[1];
				var j=0;
				while ((imgtabs = imgmatch.exec(htmls[count])) && (j<20)) {
					j++;
					tabhtml+="<hr>"+imgtabs[1];
				}
				if (j>0) { //if multiple, then enclose in div for scrolling
					tabhtml="<div style='width:425px; height:320px; overflow:scroll; border-style:none; border-width:0pt; margin:0px;'>"
						+tabhtml+"</div>";
				}
				tabs.push(new GInfoWindowTab("Bild "+(i+1),tabhtml));
			}

			alltabs[count] = tabs;
	        }		
		rendered[count]=true;		
	}
}

function InitMarker(point, pal,icid, name, description) {
    this.base = GMarker;
    var icix = icid_to_icix(icid);
//    var icon = new GIcon(baseIcon);
//    icon.image = "http://www.wedel-fuer-kinder.de/images/"+icid+".png";
    var iefname=icbase+icid+"_ie.png";
//    icon.image = "http://maps.google.com/mapfiles/kml/pal"+pal+"/icon"+icid+".png";
//    icon.shadow = "http://maps.google.com/mapfiles/kml/pal"+pal+"/icon"+icid+"s.png";
    var mtitle;
    if (description=="") {
      mtitle = name+" (noch nicht besucht)";
    } else {
      mtitle = name;
    }
    var marker = new GMarker(point,{icon:ic[icix],title:mtitle});
    var html;


    if (description!="") {
      html="<h1>" + name + "</h1>" + description;
      marker.destroy = function() {
          GEvent.clearListeners(this, 'click');
      }


  //    alert(description);

//      icons[gmcount] = icon.image;
      marker.mycount=gmcount;
      marker.onClick = function() {gmclick(this.mycount);};      
      icons_ie[gmcount] = iefname;
      rendered[gmcount] = false;
      gmarkers[gmcount] = marker;
      htmls[gmcount] = html;
      gmcount++;
      GEvent.bind(marker, 'click', marker, marker.onClick);
  }//description!=""
  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.handleEvent = function() {
        //Request completed?
        if(this.request.readyState == 4) {
            //Delete existing overlays
            for(var i in this.overlays) {
                this.overlays[i].destroy();
                this.map.removeOverlay(this.overlays[i]);
            }
            this.overlays = new Array();

            //Populate with elements in the updated feed
            var doc = this.request.responseXML;
            var sidebar_html="<table border='0'>";
            gmcount=0;

            placemarks = doc.documentElement.getElementsByTagName("Placemark");
//            alert("Placemarks: "+placemarks.length);
            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="";
                if (placemarks[i].getElementsByTagName("description") && placemarks[i].getElementsByTagName("description")[0]) {
                   description=placemarks[i].getElementsByTagName("description")[0].childNodes[0].nodeValue;
                }
                var ico=placemarks[i].getElementsByTagName("Icon")[0];
                var pal=0;
                var icid="";
                if (ico && ico.getElementsByTagName("x")) {
//                  var x = ico.getElementsByTagName("x")[0].childNodes[0].nodeValue;
//                  var y = ico.getElementsByTagName("y")[0].childNodes[0].nodeValue;
                  var ichref=ico.getElementsByTagName("href")[0].childNodes[0].nodeValue;
                  pal=0;
                  var slpos=ichref.indexOf("/");
                  var ppos=ichref.indexOf(".");
                  if ((slpos>0) && (ppos>0)) {
                     icid=ichref.substr(slpos+1,ppos-slpos-1);
                  }
                  //160,224 =5 und 160,192 = 13
                }

                var latln = new GLatLng(parseFloat(coords[1]), parseFloat(coords[0]),true);
                //alert("Name:"+name+" Lat/Long "+latln.lat()+","+latln.lng()+" IcId: "+icid);
                var marker = InitMarker(latln,pal,icid,name,description);
                if (description!="") {
                  sidebar_html += '<tr><td><a href="javascript:gmclick(' + (gmcount-1) + ')"><img border="0" src="'+ icons_ie[gmcount-1]+'"></a></td>'+
                      '<td valign="center"><a href="javascript:gmclick(' + (gmcount-1) + ')"> ' + name + '</a></td>'+
                      '</tr>';
                }

                map.addOverlay(marker);
                this.overlays.push(marker);
            }
            sidebar_html+='</table>';
            document.getElementById("sidebar").innerHTML=sidebar_html;

            //Free the request object
            this.request = undefined;
        }
    }

    //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() {
        //Trigger fetching the new map
        if(this.request != undefined) {
            this.request.abort();
        }

        url = this.url;
//        var bounds = map.getBounds();//GLatLngBounds
//        if(url.indexOf("?") == -1) {
//            url = url + "?BBOX=" + bounds.getSouthWest().toUrlValue() + "," + bounds.getNorthEast().toUrlValue();
//        } else {
//            url = url + "&BBOX=" + bounds.getSouthWest().toUrlValue() + "," + bounds.getNorthEast().toUrlValue();
//        }
//        alert(url);
        this.request = GXmlHttp.create();
        this.request.open('GET', url, true);
        var _this = this;
        //this.request.onreadystatechange = function(_this.handleEvent());
        this.request.onreadystatechange = function(){_this.handleEvent()};

        this.request.send(null);
    }

    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();

    //Add event handlers
    //not needed
    //this.moveendListener = GEvent.bind(map, 'moveend', this, this.onMapChange);
}

//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.removeFeed = function(url) {
        //Remove the feed from the feeds array
        this.feeds[url].destroy();
        delete this.feeds[url];
    }
}
