var map = null;
var iconA = null;
var iconB = null;
var iconB2 = null;
function initMap() {
  if (GBrowserIsCompatible()) {
    map = new GMap2(document.getElementById("dealers_map"));
    map.setCenter(new GLatLng(46.9, 8.0), 8);
    map.addMapType(G_PHYSICAL_MAP);
    map.setMapType(G_PHYSICAL_MAP);
//    map.addControl(new GSmallMapControl());
//    map.addControl(new GLargeMapControl());
//    map.addControl(new GLargeMapControl3D());
//    map.addControl(new GSmallZoomControl3D());
//    map.addControl(new GMapTypeControl());
//    map.addControl(new GMenuMapTypeControl());
    map.setUIToDefault();
    map.enableScrollWheelZoom();
    updateDealers();
    GEvent.addListener(map, "move", function(){ updateDealers(); }); 
    GEvent.addListener(map, "zoomend", function(o,n){ updateDealers(); }); 
  }
}
var clatlng = null;
function dealersSort(a,b) {
  da = clatlng.distanceFrom(a.getLatLng());
  db = clatlng.distanceFrom(b.getLatLng());
  return da - db;
}
var dealers = null;
function updateDealers() {
  if((dealers != null) && (map != null)) {
    clatlng = map.getCenter();
    if(map.getZoom() >= 10) map.setMapType(G_NORMAL_MAP);
    else map.setMapType(G_PHYSICAL_MAP);
    var mb = map.getBounds();
    var listA = new Array();
    var listB = new Array();
    var listC = new Array();
    for(var i = 0; i < dealers.length; i++) {
      if(((map.getZoom() <= dealers[i].maxZoom) && (map.getZoom() >= dealers[i].minZoom)) && (mb.containsLatLng(dealers[i].getLatLng()))) {
	if(!(dealers[i].visible)) { dealers[i].visible = true; map.addOverlay(dealers[i]); }
        if(dealers[i].group=="A") listA.push(dealers[i]);
        else if(dealers[i].group=="B") listB.push(dealers[i]);
        else if(dealers[i].group=="C") listC.push(dealers[i]);
      } else { if(dealers[i].visible) {dealers[i].visible = false; map.removeOverlay(dealers[i]); } }
    }
    listA.sort(dealersSort);
    listB.sort(dealersSort);
    listC.sort(dealersSort);

    if(listA.length > 0) document.getElementById("dealers_title_a").style.display="block";
    else  document.getElementById("dealers_title_a").style.display="none";
    var html = "<table width='99%'><colgroup><col width='25%'><col width='35%'><col width='15%'><col width='25%'></colgroup>";
    for(var i = 0; i < listA.length; i++) html += listA[i].tableRow;
    document.getElementById("dealers_table_a").innerHTML = html;

    if(listB.length > 0) document.getElementById("dealers_title_b").style.display="block";
    else  document.getElementById("dealers_title_b").style.display="none";
    var html = "<table width='99%'><colgroup><col width='25%'><col width='35%'><col width='15%'><col width='25%'></colgroup>";
    for(var i = 0; i < listB.length; i++) html += listB[i].tableRow;
    document.getElementById("dealers_table_b").innerHTML = html;

    if(listC.length > 0) document.getElementById("dealers_title_c").style.display="block";
    else  document.getElementById("dealers_title_c").style.display="none";
    var html = "<table width='99%'><colgroup><col width='25%'><col width='35%'><col width='15%'><col width='25%'></colgroup>";
    for(var i = 0; i < listC.length; i++) html += listC[i].tableRow;
    document.getElementById("dealers_table_c").innerHTML = html;
  }
}
function readTagContent(obj, name) {
  try { return obj.getElementsByTagName(name)[0].firstChild.data; } catch(e) { return null; }
}
var r = null;
try { r = new XMLHttpRequest(); } catch(e) {
  try { r = new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {
    try { r = new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) { r = null; } } }
if(r) {
  r.open('GET', '/dealers.xml', true);
  r.onreadystatechange = function () {
    if(r.readyState == 4) {
      var n = r.responseXML.documentElement;
      if((n != null) && (n.nodeName == "kml")) {
        var d = n.getElementsByTagName("Document")[0];
        var pms = d.getElementsByTagName("Placemark");

	var icon0 = new GIcon(G_DEFAULT_ICON);
        icon0.image = "http://www.dynavox.ch/dealers0.png";
        icon0.iconSize = new GSize(8, 8);
        icon0.shadow = "";
        icon0.iconAnchor = new GPoint(4, 4);

	var icon1 = new GIcon(G_DEFAULT_ICON);
        icon1.image = "http://www.dynavox.ch/dealers.png";
        icon1.iconSize = new GSize(20, 20);
        icon1.shadow = "http://www.dynavox.ch/dealers_sdw.png";
        icon1.shadowSize = new GSize(40, 20);
        icon1.iconAnchor = new GPoint(10, 20);

	var icon2 = new GIcon(G_DEFAULT_ICON);
        icon2.image = "http://www.dynavox.ch/dealers.png";
        icon2.iconSize = new GSize(30, 30);
        icon2.imageMap = [0,0, 29,0, 29,29, 0,29];
        icon2.shadow = "http://www.dynavox.ch/dealers_sdw.png";
        icon2.shadowSize = new GSize(45, 30);
        icon2.iconAnchor = new GPoint(15, 30);

	var icon3 = new GIcon(G_DEFAULT_ICON);
        icon3.image = "http://www.dynavox.ch/dealersR.png";
        icon3.iconSize = new GSize(40, 40);
        icon3.imageMap = [0,0, 39,0, 39,39, 0,39];
        icon3.shadow = "http://www.dynavox.ch/dealers_sdw.png";
        icon3.shadowSize = new GSize(60, 40);
        icon3.iconAnchor = new GPoint(20, 40);

        dealers = new Array();
        for(var i=0; i<pms.length; i++) {
          var coords = pms[i].getElementsByTagName("Point")[0].getElementsByTagName("coordinates")[0].firstChild.data.split(",");
          var latlng = new GLatLng(coords[1],coords[0]);
          var group = pms[i].getElementsByTagName("dyn_group")[0].firstChild.data;
          if(group=="A") {
            var m = new GMarker(latlng, {icon:icon3});
            m.minZoom = 0; m.maxZoom = 100;
          } else if(group=="B") {
            var m = new GMarker(latlng, {icon:icon2});
//            m.minZoom = 10; m.maxZoom = 100;
            m.minZoom = 0; m.maxZoom = 100;
          } else {
            var m = new GMarker(latlng, {icon:icon1});
            m.minZoom = 10; m.maxZoom = 100;
          }
          m.name = readTagContent(pms[i], "name");
          m.address = readTagContent(pms[i], "address");
          m.phoneNumber = readTagContent(pms[i], "phoneNumber").replace(/^\+41 /,"0");
          m.url = readTagContent(pms[i], "url");
          m.dynPoints = readTagContent(pms[i], "dyn_points");
          m.group = group;
          m.tableRow = "<tr><td><a href='javascript:openMarker("+dealers.length+");'>"+m.name+"</a></td><td>"+m.address+"</td><td>"+m.phoneNumber+"</td><td>";
          if(m.url) m.tableRow += "<a target='_blank' href='http://"+m.url+"'>"+m.url+"</a>";
          m.tableRow += "</td></tr>\n";
          var html = "<div><b>"+m.name+"</b><br/>"+m.address+"<br/>"+m.phoneNumber+"</div>";
          if(m.url) html += "<div><a target='_blank' href='http://"+m.url+"'>"+m.url+"</a></div>";

          var gml = "http://maps.google.ch/maps?hl="+encodeURIComponent(lang)+"&daddr="+encodeURIComponent(m.name+"@"+coords[1]+","+coords[0])+"&saddr=";
          html += "<div style='font-size:80%;'>";
          if(lang=="fr") html += "itin&eacute;raire de: ";
          else html += "Route berechnen von: ";
          html += "<input type='text' size='10' name='saddr'> "+
                  "<img src='http://maps.gstatic.com/intl/de_ch/mapfiles/transit/iw/3/drive.gif' style='cursor:pointer;' onclick='window.open(\""+gml+"\"+encodeURIComponent(this.parentNode.getElementsByTagName(\"input\")[0].value))' /> "+
                  "<img src='http://maps.gstatic.com/intl/de_ch/mapfiles/transit/iw/3/tram.gif' style='cursor:pointer;' onclick='window.open(\""+gml+"\"+encodeURIComponent(this.parentNode.getElementsByTagName(\"input\")[0].value)+\"&dirflg=r\")' /> "+
                  "<img src='http://maps.gstatic.com/intl/de_ch/mapfiles/transit/iw/3/walk.gif' style='cursor:pointer;' onclick='window.open(\""+gml+"\"+encodeURIComponent(this.parentNode.getElementsByTagName(\"input\")[0].value)+\"&dirflg=w\")' /></div>";

          var mclick = function(c,h) { return function() { map.openInfoWindowHtml(c, h); } }
          GEvent.addListener(m, "click", mclick(latlng, html));
          dealers.push(m);  
/*
          if(group == "B") {
            var m2 = new GMarker(latlng, {icon:icon1});
            m2.minZoom = 0; m2.maxZoom = 9;
            m2.name = m.name; m2.address = m.address; m2.phoneNumber = m.phoneNumber; m2.url=m.url;
            m2.group = m.group; m2.tableRow = m.tableRow;
            GEvent.addListener(m2, "click", mclick(latlng, html));
            dealers.push(m2);  
          }
*/
          if(group == "C") {
            var m2 = new GMarker(latlng, {icon:icon0, clickable:false});
            m2.minZoom = 0; m2.maxZoom = 9;
            dealers.push(m2);  
          }
        }
        updateDealers();
      } else alert("kml not found");
    }
  };
  r.send(null);
}
function openMarker(index) { GEvent.trigger(dealers[index], "click"); }
var plzmarker = null;
function showPLZ(plz) {
  var gc = new GClientGeocoder();
  gc.getLatLng("switzerland, "+plz, function(p) {
    if((!p) || (p.distanceFrom(new GLatLng(46.9, 8.0))>200000)) alert("not found"); else {
      map.setCenter(p,10);
      if(plzmarker) map.removeOverlay(plzmarker);
      plzmarker = new GMarker(p);
      map.addOverlay(plzmarker);
    }
  } );
}
