var map = null;
var mgr = null;
var zoom = null;
var geocoder = null;
var directionsPanel;
var directions;

var iconRD = null;
var icon = new Array();
var zoomLevel = new Array();
var gmarkers = [];

zoomLevel['radius'] = new Array();
zoomLevel['radius']['0'] = 13;
zoomLevel['radius']['5'] = 13;
zoomLevel['radius']['10'] = 12;
zoomLevel['radius']['25'] = 11;
zoomLevel['radius']['50'] = 10;

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

function isInt(x) {
   var y=parseInt(x);
   if (isNaN(y)) return false;
   return x==y && x.toString()==y.toString();
}

// Call this function when the page has been loaded
function initialize() {
  map = new google.maps.Map2(document.getElementById("map_canvas"));
  zoom = new google.maps.LargeMapControl();

  directionsPanel = document.getElementById('directions');
  directions = new GDirections(map, directionsPanel);

  map.addControl(zoom);
  
  
  icon['STD'] = new GIcon();
  icon['STD'].image = '/etc/sites/riverdale.nl/images/maps/pointer.png';
  icon['STD'].iconSize = new GSize(30, 30);
  icon['STD'].iconAnchor = new GPoint(6, 20);
  icon['STD'].infoWindowAnchor = new GPoint(5, 1);
  
  icon['RIF'] = new GIcon();
  icon['RIF'].image = '/etc/sites/riverdale.nl/images/maps/pointerRIF.png';
  icon['RIF'].iconSize = new GSize(30, 30);
  icon['RIF'].iconAnchor = new GPoint(6, 20);
  icon['RIF'].infoWindowAnchor = new GPoint(5, 1);
  
  icon['RIS'] = new GIcon();
  icon['RIS'].image = '/etc/sites/riverdale.nl/images/maps/pointerRIS.png';
  icon['RIS'].iconSize = new GSize(30, 30);
  icon['RIS'].iconAnchor = new GPoint(6, 20);
  icon['RIS'].infoWindowAnchor = new GPoint(5, 1);

  geocoder = new google.maps.ClientGeocoder();

  map.setCenter(new GLatLng(51.913779,4.833984), 5);

  $(":input[name='ww_postal_code']").bind("keyup", function(e) {
  	var key = e.keyCode || e.which;

  	if (key == 13) {
      retreiveNearByMarker();
  	}

  	var postal_code = $(this).val().replace(' ','');

  	if (strlen(postal_code) > 0) {
  	  if ($(":input[name='radius']").val() == 0) {
  	    $(":input[name='radius']").get(0).selectedIndex = 2;
  	  }
  	} else {
  	  $(":input[name='radius']").get(0).selectedIndex = 0;
  	}

  });
  
  $(":input[name='ww_postal_code']").bind("focus", function(e) {
    if($(this).val() == 'Postcode'){$(this).val('');}
  });

  $(":input[name='ww_city']").bind("keyup", function(e) {
  	var key = e.keyCode || e.which;

  	if (key == 13) {
      retreiveNearByMarker();
  	}
  });
  
  $(":input[name='ww_city']").bind("focus", function(e) {
    if($(this).val() == 'Plaats'){$(this).val('');}
  });
}

function retreiveNearByMarker(postal_code, city, country, radius, storeType) {
  // Alle oude resultaten verbergen
  $("div.store_result").hide();

  // Alle reeds weergegevens routes weghalen
  directions.clear();

  // Alle reeds aanwezige markers weghalen
  map.clearOverlays();
  
  // De gmarker array weer legen
  gmarkers = [];

  // De doorgegeven waardes in lokale variabele plaatsen
  var postal_code = postal_code ? postal_code : (($(":input[name='ww_postal_code']").val() != 'Postcode' && $(":input[name='ww_postal_code']").val() != 'Code Postal' && $(":input[name='ww_postal_code']").val() != 'Postleitzahl' && $(":input[name='ww_postal_code']").val() != 'Postleitzahl')?$(":input[name='ww_postal_code']").val():'');
  var city = city ? city : (($(":input[name='ww_city']").val() != 'Plaats' && $(":input[name='ww_city']").val() != 'Ville' && $(":input[name='ww_city']").val() != 'Ort' && $(":input[name='ww_city']").val() != 'City')?$(":input[name='ww_city']").val():'');
  var country = country ? country : $(":input[name='ww_country']").val();
  var radius = radius ? radius : $(":input[name='radius']").val();  
  var storeType = storeType ? storeType : $(":input[name='storeType']").val();  
  
  if (postal_code.length == 0 && city.length == 0) {
  	return false;
  }
  
  // Controleren of er een postcode/plaats is ingevuld en er een geldige radius is opgegeven
  if ((postal_code || city || storeType) && (radius && radius >=0 && radius <= 50)) {
    // Ajax pagina aanroepen om de dichtsbijzijnde winkels op te halen
    GDownloadUrl("/ajax/store-locator/"+ ((postal_code && postal_code.length > 0)?postal_code:'null') +"/"+ ((city && city.length > 0)?city:'null') + "/" + ((country && country.length > 0)?country:'null') + "/" + ((storeType && storeType.length > 0)?storeType:'null') + "/" + radius + "/", function(data) {
      if (data.length > 0) {
        // Google de XMLdata laten parsen in een variabele
        var xml = GXml.parse(data);

        // De XML data plaatsen in een variabele
        var markers = xml.documentElement.getElementsByTagName("marker");

        // Alle oude resultaten weghalen behalve de eerste - verborgen - regel
        $("div.rule").not(":first").remove();

        if (markers.length > 0) {
          /* Loop door de gevonden XML Data */
          for (var i = 0; i < markers.length; i++) {
            // De regels achter de vorige regel invoegen
            $("div.rule:first").clone().insertAfter($("div.rule:last"));

            // De naam ophalen voor in het resultaat overzicht en deze inkorten indien nodig
            var name = ((strlen(markers[i].getAttribute("name")) > 20)?substr(markers[i].getAttribute("name"), 0, 20) +'...':markers[i].getAttribute("name"));

            // De resultaat lay-out genereren
            $("div.rule:last").attr("id", markers[i].getAttribute("id"))
            $("div.rule:last").children("div").eq(0).text(name);

            /* Afstand niet tonen als geen straal is opgegeven */
            if (markers[i].getAttribute("distance")) {
              $("div.rule:last").children("div").eq(1).text(number_format(markers[i].getAttribute("distance"), 2) + ' km');
            }

            $("div.rule:last").show();

            // Loop de XML data door en haal de verschillende criteria op en plaats deze in variabele
            var id = markers[i].getAttribute("id");
            var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),
                              parseFloat(markers[i].getAttribute("lng")));

            var name = markers[i].getAttribute("name");
            var address = markers[i].getAttribute("address");
            var postal_code = markers[i].getAttribute("postal_code");
            var city = markers[i].getAttribute("city");
            var country = markers[i].getAttribute("country");
            var storeType = markers[i].getAttribute("storeType");
            var telephone = markers[i].getAttribute("telephone");
            var url = markers[i].getAttribute("url");
            var distance = markers[i].getAttribute("distance");

            // Creeer een marker. Parameter 1: Coordinaat, Parameter 2: HTML inhoud
            var marker = createMarker(point, createMarkerContent(null, name, address, postal_code, city, country, storeType, telephone, url, id), storeType);

            // Plaats de marker in een array zodat deze straks gemakkelijk via een ID is aan te roepen
            gmarkers[id] = marker;

            // Voeg te marker toe aan de map
            map.addOverlay(marker);
          }

          // Centreer de map naar het meest dichtsbijzijnde resultaat
          geocoder.getLatLng(markers[0].getAttribute("postal_code") + ', '+ markers[0].getAttribute("city") + ', '+ markers[0].getAttribute("country"), function(point) {
            map.setCenter(point, zoomLevel['radius']['' + radius + '']);
          });

          // Open info window voor meest dichtsbijzijnde winkel
          GEvent.trigger(gmarkers[markers[0].getAttribute("id")], "click");

          // Toon resultaten
          resultInitialize();
        }

      } else {

        alert('Er zijn geen resultaten gevonden bij uw zoekopdracht.');

//         Als er er geen resultaten gevonden zijn bij de opgegeven straal, dan automatisch de eerst volgende straal hanteren
//        var radiusNextValue = $(":input[name='radius']").children("option").eq(($(":input[name='radius']").get(0).selectedIndex) + 1).val();
//
//        retreiveNearByMarker(postal_code, city, radiusNextValue);
//
//        $(":input[name='radius']").children("option").eq(($(":input[name='radius']").get(0).selectedIndex) + 1).attr("selected", "selected");
      }
    });
  }
}

function showStore() {
  var html = $("div#store_html").html();
  var point = $("input[type='hidden'][name='point']").val();
  point = point.split(',');
  point = new GLatLng(parseFloat(point[0]), parseFloat(point[1]));

  var marker = createMarker(point, html);

  if (map) {
  	map.clearOverlays();
  	
    // Voeg te marker toe aan de map
    map.addOverlay(marker);
    map.setCenter(point, 13);

    GEvent.trigger(marker, "click");
  }
}

// Een marker aanmaken op de doorgegeven coordinaten met als window de doorgegeven HTML
function createMarker(point, html, storeType) {
  var marker = new google.maps.Marker(point, icon[storeType]);

  GEvent.addListener(marker, 'click', function() {
    // Alle reeds weergegevens routes weghalen
    directions.clear();

    // Info window koppelen aan de marker
    if (html && html.length > 0) {
      marker.openInfoWindowHtml(html);
    }
  });

  return marker;
}

// De HTML content genereren voor een window
function createMarkerContent(html, name, address, postal_code, city, country, storeType, telephone, url, id) {
  var to = postal_code + ', ' + city;
  var telephone = telephone ? telephone : '<i>Geen telefoonnummer</i>';

  custom_html = null;

  custom_html  = '<div style="width: 300px;" class="maps_info_window">';
  custom_html += '<div style="float: left;"><img src="/etc/sites/riverdale.nl/images/maps/thumb'+storeType+'.jpg" width="105" height="105" /></div>';
  custom_html += '<div style="float: left; margin-left: 5px;">';
  custom_html += '<h3 style="background-color: #FFFFFF !important;">'+ name +'</h3>';
  custom_html += '<p>'+ address + '<br />' + postal_code + ' '+ city +'<br />'+ country +'</p><p>'+ telephone +'</p>';
  custom_html += ((url && url.length > 5)?'<a href="http://'+ url +'" target="target-blank">Bekijk de website</a> | ':'');
//  custom_html += '<a href="#" onclick="showDirectionMap(\'\', \''+ to +'\');">Toon route</a> | <a href="#" onclick="showDirectionText(\'\', \''+ to +'\', \''+ id +'\');">Toon routebeschrijving</a>';
  custom_html += '</div>';
  custom_html += '</div>';
  
  //+ '<a href="#" onclick="showDirectionText(\'\', \''+ to +'\', \''+ id +'\');">Routebeschrijving</a>'

  var html = html ? html : custom_html;

  return html;
}

// Resultaten initializeren
function resultInitialize() {
  $("div.rule").not(":first").bind("mouseover mouseout", function(e) {
    $(this).toggleClass("hover");
  });

  $("div.rule").not(":first").bind("click", function() {
    var id = $(this).attr("id");
    id = id.replace('store_');

    GEvent.trigger(gmarkers[parseInt(id)], "click");
  });

  $("div.store_result").show();
}

/* Toon route op de Google Map */
function showDirectionMap(from, to) {
  var from = from ? from : $(":input[name='ww_postal_code']").val();

  from = from +","+ $(":input[name='ww_city']").val();

  directions.load("from: "+ from +" to: "+ to, {locale : 'nl_NL'});
}

// Laat $.window zien met tekstuele routebeschrijving
function showDirectionText(from, to, id) {
  var from = from ? from : $(":input[name='ww_postal_code']").val();

  $.window({
    src: 'http://maps.google.com/maps?f=d&saddr='+ from +'&daddr='+ to +'&hl=nl&geocode=&mra=ls&sll='+ gmarkers[id].getLatLng().toUrlValue() +'&ie=UTF8&z=10&pw=2',
    height: 600,
    width: 800,
    overflow: 'visible',
    header: true,
    close: true
  });
}

// Google domload
//google.setOnLoadCallback(initialize);

$(document).ready(function() {
	initialize();
});































//
//
//function showAddress(id, address, initial, radius, html) {
//  if (address) {
//   geocoder = new google.maps.ClientGeocoder();
//
//   geocoder.getLatLng(address, function(point) {
//      if (!point) {
//        alert(address + " not found");
//      } else {
//        if (radius) {
//          map.setCenter(point, zoomLevel['radius']['' + radius + '']);
//        } else {
//          map.setCenter(point, zoomLevel['radius']['5']);
//        }
//
////        if (initial) {
////          html  = '<div style="width: 275px;">';
////          html += '<div style="float: left;"><img src="/etc/sites/riverdale.nl/images/Tenbos.JPG" width="105" height"55" /></div>';
////          html += '<div style="float: left; margin-left: 5px;">';
////          html += '<h3>Tenbos B.V.</h3>';
////          html += '<p>Donau 92<br />2491BC Den Haag</p><p>+31(0)70-3177100</p>';
////          html += '</div>';
////          html += '</div>';
////
//////          /* RETREIVE ALL MARKERS */
//////          mgr = new MarkerManager(map);
//////          mgr.addMarkers(, 13);
//////          mgr.refresh();
////
////
////        }
//
//        retreiveAllMarkers();
//
//        html = html ? html : null;
//
//        if (id != null) {
//          GEvent.trigger(gmarkers[id], "click");
//        }
//      }
//    });
//  }
//}
//
//function retreiveAllMarkers() {
//  GDownloadUrl("/ajax/store-locator/", function(data) {
//    var xml = GXml.parse(data);
//    var markers_temp = xml.documentElement.getElementsByTagName("marker");
//
//    for (var i = 0; i < markers_temp.length; i++) {
//      var id = markers_temp[i].getAttribute("id");
//      var name = markers_temp[i].getAttribute("name");
//      var address = markers_temp[i].getAttribute("address");
//      var postal_code = markers_temp[i].getAttribute("postal_code");
//      var city = markers_temp[i].getAttribute("city");
//      var telephone = markers_temp[i].getAttribute("telephone");
//      var url = markers_temp[i].getAttribute("url");
//      var point = new GLatLng(parseFloat(markers_temp[i].getAttribute("lat")),
//                              parseFloat(markers_temp[i].getAttribute("lng")));
//
//
//      var marker = createMarker(point, null, name, address, postal_code, city, telephone, url, id);
//      map.addOverlay(marker);
//
//      gmarkers[id] = marker;
//    }
//  });
//}
//