google.load("maps", "2");

var mngr = null;
var allmarkers = [];
var icons = {};
var geocoder = null;
var address = null;
var debug = 0;
var icoArray = [2];
var gdir = null;
var persMarker = null;
var filArtID = null;

function initKarte() {
    if(!google.maps.BrowserIsCompatible()) {
        alert("Browser nicht Kompatible!");
        return;
    }else {
        initialize();
    }
}

function initialize() {
    map = new google.maps.Map2(document.getElementById("mapDiv"));

    var showOsterreich = document.getElementById('osterreichShow').value;

    new google.maps.KeyboardHandler(map);

    map.addControl(new google.maps.LargeMapControl());
    map.addControl(new google.maps.ScaleControl());
    //map.addControl(new google.maps.OverviewMapControl());

    if(showOsterreich == 1 && !address)
        map.setCenter(new google.maps.LatLng(47.38000561,13.51153823), 6, G_NORMAL_MAP);
    else
        map.setCenter(new google.maps.LatLng(47.38000561,13.51153823), 17, G_NORMAL_MAP);

    map.enableDoubleClickZoom();

    gdir = new google.maps.Directions(map);

    google.maps.Event.addListener(map, "moveend", checkBounds);

    google.maps.Event.addListener(gdir, "error", handleErrors);

    markerMngrOption = { borderPadding: 50, maxZoom: 15, trackMarkers: true };

    mngr = new google.maps.MarkerManager(map, markerMngrOption);
    window.setTimeout(getFilMarker, 0);

    allowedBounds = new google.maps.LatLngBounds(new google.maps.LatLng(46.47,9.09), new google.maps.LatLng(49.13,17.,27));

    getAustriaPoly();
}

function checkBounds() {
    // check ob es im bereich ist
    if (allowedBounds.contains(map.getCenter())) {
      return;
    }
    // wenn nicht okay, tun wir was dagegen
    var C = map.getCenter();
    var X = C.lng();
    var Y = C.lat();

    var AmaxX = allowedBounds.getNorthEast().lng();
    var AmaxY = allowedBounds.getNorthEast().lat();
    var AminX = allowedBounds.getSouthWest().lng();
    var AminY = allowedBounds.getSouthWest().lat();

    if (X < AminX) {X = AminX;}
    if (X > AmaxX) {X = AmaxX;}
    if (Y < AminY) {Y = AminY;}
    if (Y > AmaxY) {Y = AmaxY;}
    map.setCenter(new google.maps.LatLng(Y,X));
  }

function getAustriaPoly() {

    map.clearOverlays();

    map.setCenter(new google.maps.LatLng(47.38000561,13.51153823), 6, G_NORMAL_MAP);
    var points = [];

    points.push( new google.maps.LatLng(46.79253,11.05517) );
	points.push( new google.maps.LatLng(46.98025,11.18701) );
	points.push( new google.maps.LatLng(46.97275,11.71435) );
	points.push( new google.maps.LatLng(47.09256,12.20874) );
	points.push( new google.maps.LatLng(46.98774,12.12084) );
	points.push( new google.maps.LatLng(46.87521,12.26367) );
	points.push( new google.maps.LatLng(46.67205,12.49438) );
	points.push( new google.maps.LatLng(46.55886,13.30737) );
	points.push( new google.maps.LatLng(46.49082,13.96655) );
	points.push( new google.maps.LatLng(46.38483,14.53784) );
	points.push( new google.maps.LatLng(46.65697,15.05419) );
	points.push( new google.maps.LatLng(46.68713,15.62548) );
	points.push( new google.maps.LatLng(46.67205,16.03198) );
	points.push( new google.maps.LatLng(46.87521,16.11987) );
	points.push( new google.maps.LatLng(47.01771,16.53735) );
	points.push( new google.maps.LatLng(47.39834,16.47143) );
	points.push( new google.maps.LatLng(47.47266,16.64721) );
	points.push( new google.maps.LatLng(47.62097,16.68017) );
	points.push( new google.maps.LatLng(47.66723,16.42529) );
	points.push( new google.maps.LatLng(47.75409,16.54339) );
	points.push( new google.maps.LatLng(47.73932,16.71093) );
	points.push( new google.maps.LatLng(47.68573,16.76312) );
	points.push( new google.maps.LatLng(47.70976,17.08996) );
	points.push( new google.maps.LatLng(47.86661,17.02404) );
	points.push( new google.maps.LatLng(47.97153,17.0982) );
	points.push( new google.maps.LatLng(48.01013,17.16137) );
	points.push( new google.maps.LatLng(48.05421,17.07073) );
	points.push( new google.maps.LatLng(48.14043,17.057) );
	points.push( new google.maps.LatLng(48.26491,16.95538) );
	points.push( new google.maps.LatLng(48.44195,16.8565) );
	points.push( new google.maps.LatLng(48.54934,16.94165) );
	points.push( new google.maps.LatLng(48.71814,16.90045) );
	points.push( new google.maps.LatLng(48.73626,16.67797) );
	points.push( new google.maps.LatLng(48.81409,16.5324) );
	points.push( new google.maps.LatLng(48.74351,16.39782) );
	points.push( new google.maps.LatLng(48.84122,15.90344) );
	points.push( new google.maps.LatLng(48.87374,15.78533) );
	points.push( new google.maps.LatLng(48.8611,15.6892) );
	points.push( new google.maps.LatLng(48.98742,15.29644) );
	points.push( new google.maps.LatLng(48.94595,15.1701) );
	points.push( new google.maps.LatLng(49.01445,15.01354) );
	points.push( new google.maps.LatLng(48.77972,14.97235) );
	points.push( new google.maps.LatLng(48.78334,14.81854) );
	points.push( new google.maps.LatLng(48.59114,14.70043) );
	points.push( new google.maps.LatLng(48.64198,14.45324) );
	points.push( new google.maps.LatLng(48.55843,14.32965) );
	points.push( new google.maps.LatLng(48.64742,14.02203) );
	points.push( new google.maps.LatLng(48.67826,14.06048) );
	points.push( new google.maps.LatLng(48.77067,13.84075) );
	points.push( new google.maps.LatLng(48.52206,13.7254) );
	points.push( new google.maps.LatLng(48.5657,13.45623) );
	points.push( new google.maps.LatLng(48.29233,13.26672) );
	points.push( new google.maps.LatLng(48.13126,12.76135) );
	points.push( new google.maps.LatLng(47.85003,13.00305) );
	points.push( new google.maps.LatLng(47.72454,12.89868) );
	points.push( new google.maps.LatLng(47.63393,13.08819) );
	points.push( new google.maps.LatLng(47.47266,13.01678) );
	points.push( new google.maps.LatLng(47.57096,12.79156) );
	points.push( new google.maps.LatLng(47.67093,12.76684) );
	points.push( new google.maps.LatLng(47.63948,12.55535) );
	points.push( new google.maps.LatLng(47.74486,12.25872) );
	points.push( new google.maps.LatLng(47.62838,12.19006) );
	points.push( new google.maps.LatLng(47.58578,11.60778) );
	points.push( new google.maps.LatLng(47.50978,11.43749) );
	points.push( new google.maps.LatLng(47.40764,11.11889) );
	points.push( new google.maps.LatLng(47.52832,10.87994) );
	points.push( new google.maps.LatLng(47.55428,10.4652) );
	points.push( new google.maps.LatLng(47.44109,10.4707) );
	points.push( new google.maps.LatLng(47.27177,10.17956) );
	points.push( new google.maps.LatLng(47.37417,10.22351) );
	points.push( new google.maps.LatLng(47.36859,10.10266) );
	points.push( new google.maps.LatLng(47.4578,10.09167) );
	points.push( new google.maps.LatLng(47.5376,9.95983) );
	points.push( new google.maps.LatLng(47.58764,9.78405) );
	points.push( new google.maps.LatLng(47.52461,9.70166) );
	points.push( new google.maps.LatLng(47.5005,9.56158) );
	points.push( new google.maps.LatLng(47.39091,9.66595) );
	points.push( new google.maps.LatLng(47.30903,9.55609) );
	points.push( new google.maps.LatLng(47.22702,9.55609) );
	points.push( new google.maps.LatLng(47.13181,9.62475) );
	points.push( new google.maps.LatLng(47.05889,9.60278) );
	points.push( new google.maps.LatLng(47.01584,9.87194) );
	points.push( new google.maps.LatLng(46.84516,10.08892) );
	points.push( new google.maps.LatLng(46.99149,10.38006) );
	points.push( new google.maps.LatLng(46.86019,10.45971) );
	points.push( new google.maps.LatLng(46.87521,10.68218) );
	points.push( new google.maps.LatLng(46.79441,10.73162) );
	points.push( new google.maps.LatLng(46.76808,11.00354) );

    austriaPoly = new GPolygon(points,"#0167B1", 2, 1, '#F49401',.2);
    map.addOverlay(austriaPoly ) ;
}

function getFilMarker() {
    allmarkers.length = 0;
    makeIcons();

      for (var i=0;  i<officeLayer.length; i++) {
        var layer = officeLayer[i];
        var markers = [];
        var makerLenght = layer["places"].length;

        for (var j=0; j < makerLenght; j++) {
          var place = layer["places"][j];
          var title = place["name"];
          var navi = place["navi"];
          var filIndx = place["icon"][0];
          var filDID = place["filID"];
          var posn = new google.maps.LatLng(place["posn"][0], place["posn"][1]);
          var marker = createMarker(posn,title,icoArray[filIndx], navi, filDID);

          markers.push(marker);
          allmarkers.push(marker);
        }
        mngr.addMarkers(markers, layer["zoom"][0], layer["zoom"][1]);
      }
      mngr.refresh();
    }

function reloadMarker() {
    // 0 beide
    // 1 zielpunkt
    // 2 plus
    mngr = null;
    allmarkers.length = 0;
    mngr = new google.maps.MarkerManager(map, markerMngrOption);
    map.clearOverlays();

    for (var i=0;  i<officeLayer.length; i++) {
        var layer = officeLayer[i];
        var markers = [];
        var makerLenght = layer["places"].length;

        for (var j=0; j < makerLenght; j++) {
          var place = layer["places"][j];
          var title = place["name"];
          var navi = place["navi"];
          var filIndx = place["icon"][0];
          var posn = new google.maps.LatLng(place["posn"][0], place["posn"][1]);
          var filDID = place["filID"];
          if(filArtID == 1  || filArtID == 2){
              if(filArtID == 1)
                var selectIndex = 0;
              else
                var selectIndex = 1;


              if(selectIndex == filIndx){
                 var marker = createMarker(posn,title,icoArray[filIndx], navi, filDID);

                  markers.push(marker);
                  allmarkers.push(marker);
              }
          } else {
            var marker = createMarker(posn,title,icoArray[filIndx], navi, filDID);

            markers.push(marker);
            allmarkers.push(marker);
          }
        }
        mngr.addMarkers(markers, layer["zoom"][0], layer["zoom"][1]);
      }
    mngr.refresh();

    map.addOverlay(persMarker);
}

function createMarker(posn, title, icon, navi, showID) {
      var marker = new google.maps.Marker(posn, {icon: icon});
      google.maps.Event.addListener(marker, 'click', function() {
                                                                marker.openInfoWindowHtml(title+'<br><br><a href="#" onclick="planRoute(\''+navi+'\'); return false;" style="color:#000;">Route planen</a>');
                                                                showFilInfo(showID);
                                                             } );
      return marker;
    }

function getIcon(images) {
      var icon = null;
      if (images) {
        if (icons[images[0]]) {
          icon = icons[images[0]];
        } else {
          icon = new google.maps.Icon();
          icon.image = "image/" + images[0] + ".gif";
          var size = iconData[images[0]];
          icon.iconSize = new google.maps.Size(size.width, size.height);
          icon.iconAnchor = new google.maps.Point(size.width >> 1, size.height >> 1);
          icons[images[0]] = icon;
        }
      }
      return icon;
    }

function subAdress() {
    showAddress(document.getElementById('postPlz').value, document.getElementById('postStr').value);
    filArtID = document.getElementById('filArt').value;
    window.setTimeout(reloadMarker, 200);
}

function showMe() {
    showAddress(document.getElementById('plz').value, document.getElementById('str').value);
    varFilArt = document.getElementsByName('art');
    for(var i=0; i<varFilArt.length; i++) {
        if(varFilArt[i].checked){
            filArtID = varFilArt[i].value;
        }
    }
    window.setTimeout(reloadMarker, 200);
}

function showAddress(plz, str) {

    var errorText = '';
    var bLand = '';

    //alert(bLand);

    if(plz && plz.length == 4 && !isNaN(plz)) {
        address = 'A-'+plz+', Austria';
        addressAlternative = +plz+', '+bLand+', Austria';
        if(str){
            address = str+', '+plz+', '+bLand+', Austria';
        }

        address.replace(/ß/gi, 'ss');

        //log(address);

        if(persMarker != null)
            map.removeOverlay(persMarker);

        geoDataURL = 'http://maps.google.com/maps/geo?q='+escape(address)+'&output=csv&key=ABQIAAAAvjjSx2Rzxc9ybxMKepdocBT2yXp_ZAY8_ufC3CFXhHIE1NvwkxQG5o45B7_QyBsPzSxt1n60G7EOKg';

        geocoder = new GClientGeocoder();
          if (geocoder) {
            geocoder.getLatLng(
              address,
              function(point) {
                if (!point) {
                  alert('Keine Filiale gefunden.\nBitte überprüfen Sie Ihre Eingabe.');
                  checkBounds();
                } else {
                    if(plz.charAt(0) == '1')
                        map.setCenter(point, 14);
                    else
                        map.setCenter(point, 12);

                  persMarker = new google.maps.Marker(point, {icon: icoArray['pers']});
                  var varLat = persMarker.getLatLng().lat();
                  var varLng = persMarker.getLatLng().lng();

                  google.maps.Event.addListener(persMarker, 'click', function() {
                                                                    persMarker.openInfoWindowHtml('Ihr Standort');
                                                                    });

                  map.addOverlay(persMarker);
                  saveAdr(address, varLat, varLng);
                  searchLocationsNear(point);

                }
              }
            );
            }
    } else {

        if(!plz)
            errorText +='Es muss mindestens eine Postleitzahl eingetragen werden\n';
        if(plz.length != 4)
            errorText +='PLZ muss 4 Stellen haben!\n';
        if(isNaN(plz))
            errorText += 'Postleitzahl darf nur aus zahlen bestehen!\n';
        alert(errorText);
    }
}

function planRoute (toAddress) {
    toAddress = unescape(toAddress);
    gdir.load("from: " + address + " to: " + toAddress,
                { "locale": "de_DE" });

}


function makeIcons() {
    // zeilpunkt ico
    icoArray['0'] = new google.maps.Icon();
    icoArray['0'].image = 'image/marker/logo_zp_filialen.gif';
    icoArray['0'].iconSize = new google.maps.Size(21,22);
    icoArray['0'].iconAnchor = new google.maps.Point(21,22);
    icoArray['0'].infoWindowAnchor = new google.maps.Point(10,10);
    // plus
    icoArray['1'] = new google.maps.Icon();
    icoArray['1'].image = 'image/marker/logo_plus_filialen.gif';
    icoArray['1'].iconSize = new google.maps.Size(36,25);
    icoArray['1'].iconAnchor = new google.maps.Point(36,25);
    icoArray['1'].infoWindowAnchor = new google.maps.Point(18,12);
    //persönlich
    icoArray['pers'] = new google.maps.Icon();
    icoArray['pers'].image = 'image/marker/ich.gif';
    icoArray['pers'].iconSize = new google.maps.Size(17,16);
    icoArray['pers'].iconAnchor = new google.maps.Point(17,16);
    icoArray['pers'].infoWindowAnchor = new google.maps.Point(8,8);
}

function log(varText) {
    if(debug == 1)
        google.maps.Log.write(varText);
}

function searchLocationsNear(center) {

     var searchUrl = 'data/getNear.php?lat=' + center.lat() + '&lng=' + center.lng()+'&fileArt='+filArtID;
     google.maps.DownloadUrl(searchUrl, function(data) {
       var xml = google.maps.Xml.parse(data);
       var markers = xml.documentElement.getElementsByTagName('marker');

       var sidebar = document.getElementById('sidebar');
       sidebar.style.display = 'block';

       var sidebarEntry = createSidebarEntry('', '0', '0', '0');
       sidebar.appendChild(sidebarEntry);

       sidebar.innerHTML = '';
       if (markers.length == 0) {
         sidebar.innerHTML = 'Keine Filiale gefunden.<br>Bitte &uuml;berpr&uuml;fen Sie Ihre Eingabe.';
         getAustriaPoly();
         return;
       }

       var bounds = new google.maps.LatLngBounds();
           for (var i = 0; i < markers.length; i++) {
               if(i==1) {
                   map.setCenter(center);
               }
             var name = markers[i].getAttribute('name');
             var names = markers[i].getAttribute('names');
             // address = markers[i].getAttribute('address');
             var distance = parseFloat(markers[i].getAttribute('distance'));
             var xmlLat = parseFloat(markers[i].getAttribute('lat'));
             var xmlLng = parseFloat(markers[i].getAttribute('lng'));
             var filID = parseFloat(markers[i].getAttribute('id'));
             var filArt = parseFloat(markers[i].getAttribute('fil'));

             var filImg = '<img src="image/marker/logo_zp_filialen.gif">';

             var beschreibung = '<table width="100%"  border="0" cellspacing="0" cellpadding="0">'+
                                  '<tr>'+
                                    '<td rowspan="2" width="38" align="center">'+filImg+'</td>'+
                                    '<td><b>'+name+'</b></td>'+
                                  '</tr>'+
                                  '<tr>'+
                                    '<td>'+names+' ('+distance.toFixed(1)+'km)</td>'+
                                  '</tr>'+
                                '</table>';

             var sidebarEntry = createSidebarEntry(beschreibung, xmlLat, xmlLng, filID);
             sidebar.appendChild(sidebarEntry);
           }
     });
   }

function createSidebarEntry(name, lat, lng, filID) {
      var div = document.createElement('div');
      var markerIndex = null;
      var html = name;
      div.innerHTML = html;
      div.style.cursor = 'pointer';

      for (var i=0; i<allmarkers.length; i++) {
          if((allmarkers[i].getLatLng().lat() == lat)
          && (allmarkers[i].getLatLng().lng() == lng)) {
              markerIndex = i;
              break;
          }
      }
      google.maps.Event.addDomListener(div, 'click', function() {
          map.setCenter(allmarkers[markerIndex].getLatLng());
          window.setTimeout("google.maps.Event.trigger(allmarkers["+markerIndex+"], 'click');", 500);
      });
      return div;
    }

function showFilInfo(filalID) {
    var filDataURL = 'data/gefFilInfo.php?id='+ filalID;
     google.maps.DownloadUrl(filDataURL, function(data) {
       document.getElementById('filInfo').innerHTML = data;
     });
}

function saveAdr(address, varLat, varLng) {
    var xmlRequestObj = google.maps.XmlHttp.create();

    xmlRequestObj.open('POST', 'ajax/ajax.php', true);

    xmlRequestObj.setRequestHeader("Content-Type",
                               "application/x-www-form-urlencoded");
    xmlRequestObj.send('action=saveAdr&adr='+address+'&lat='+varLat+'&lng='+varLng);
}



function handleErrors(){
	   if (gdir.getStatus().code == G_GEO_UNKNOWN_ADDRESS)
	     alert("No corresponding geographic location could be found for one of the specified addresses. This may be due to the fact that the address is relatively new, or it may be incorrect.\nError code: " + gdir.getStatus().code);
	   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 alert("An unknown error occurred.");

	}

google.setOnLoadCallback(initialize);
