var Map = new Class({
  map: null,
  driver: null,
  locations: null,
  initialize: function(source){
    if (!GBrowserIsCompatible())
      return;
    
    var locations = this.locations = new Object();
    var driver = this.driver = new MapDriver(this);

    var map = this.map = new GMap2(document.getElementById("map"));
    map.setCenter(new GLatLng(52.091262, 5.122748), 9);
    map.addControl(new GLargeMapControl());
    map.addControl(new GMapTypeControl());
    
    GDownloadUrl(source, function(data) {
      var xml = GXml.parse(data);
      var list = xml.documentElement.getElementsByTagName("location");
      var location;
      for (index = 0; index < list.length; index++){
        location = new Location(map, list.item(index));
        locations[location.identifier] = location;
      }
    });
    
    jQuery('#check').submit(function(event){
      var form = jQuery(event.target);
      var zip = form.find('input[@name=zip]').val();
      driver.map(zip);
      return false;
    });
    
    jQuery('.trigger').click(function(event){
      var href = jQuery(this).attr("href");
      var identifier = href.substr(Math.max(href.indexOf('#') + 1, 0));
      var location = locations[identifier];
      
      if (location == undefined)
        return false;
      
      location.focus();
      
      return false;
    });
  },
  process: function(response){
    var location = this.locations[response.result];
    
    if (location == undefined)
    {
	    tb_show(null,'#TB_inline?height=115&amp;width=300&amp;inlineId=mapError&amp;modal=true',false);
      return false;
    }
      
    location.focus();

  }
});

var Location = new Class({
  identifier: null,
  map: null,
  point: null,
  marker: null,
  title: null,
  description: null,
  initialize: function(map, node){
    var location = this;
    var element;
    var index;
    var list;
    
    this.map = map;
    this.identifier = jQuery(node).children("identifier").text();
    
    element = jQuery(node).children("marker")[0];
    
    var icon = new GIcon();
    icon.image = "/images/marker.gif";
    icon.iconSize = new GSize(14, 18);
    icon.iconAnchor = new GPoint(14, 18);
    icon.infoWindowAnchor = new GPoint(14, 18);
    
    this.point = new GLatLng(
        parseFloat(jQuery(element).attr("lat")),
        parseFloat(jQuery(element).attr("lng")));
    this.marker = new GMarker(this.point, icon);
    
    element = jQuery(node).children("description")[0];
    this.description = jQuery(element).text();
    
    this.map.addOverlay(this.marker);
    
    GEvent.addListener(this.marker, "click", function() {
      location.marker.openInfoWindowHtml(location.description);
      location.focus();
    });
  },
  focus: function(){
    this.map.panTo(this.point);
    this.marker.openInfoWindow(this.description);	
    jQuery('.store').removeClass('bgstripe'); 
    jQuery('#' + this.identifier).addClass('bgstripe');
  }
});
