/**
 * DealerMap
 * 
 * map.js
 *
 * Version history (please keep backward compatible):
 * 1.0, 2010-03-16: Cornelius Hansjakob
 *
 * @author Cornelius Hansjakob <cha@massiveart.com>
 * @version 1.0
 */

DealerMap = Class.create({

  initialize: function() {
	  this.map = null;
    this.geocoder = null;
    this.marker = null;
    
    this.blnValid = false;
    
    this.STR_BASE_PATH = '/zoolu-website/storefinder';
    
    this.longitude = 0;
    this.latitude = 0;
        
    /**
     * searchDealer field
     */    
    if($('searchDealer')) {
      $('searchDealer').observe('keydown', function(event){
        if(event.keyCode == 13){
          this.showDealer($('searchDealer').getValue()); 
        }    
      }.bind(this));  
    }
  },
  
  /**
   * initGMap
   */
  initGMap: function(lat, lng){
    /**
     * init google map
     */   
    if($('map')){
      if(typeof(lat) == 'undefined') lat = 47.22982711058905;
      if(typeof(lng) == 'undefined') lng = 9.897308349609375;
      
      if(GBrowserIsCompatible()) {
        this.map = new GMap2($('map'));
        var center = new GLatLng(lat, lng);
        this.map.setCenter(center, 6);        
        this.geocoder = new GClientGeocoder();
            
        var customUI = this.map.getDefaultUI();
        customUI.controls.scalecontrol = false;
        customUI.controls.largemapcontrol3d = false;
        customUI.controls.smallzoomcontrol3d = true;
        customUI.controls.maptypecontrol = false;        
        customUI.controls.menumaptypecontrol = false;
        customUI.maptypes.normal = true;
        customUI.maptypes.satellite = false;
        customUI.maptypes.hybrid = false;
        customUI.maptypes.physical = false;
        customUI.zoom.doubleclick = true; 
        customUI.zoom.scrollwheel = false;
        this.map.setUI(customUI);
      }
    }  
  },
  
  /**
   * initGMapSmall
   */
  initGMapSmall: function(lat, lng){
    /**
     * init google map
     */   
    if($('mapSmall')){      
      if(typeof(lat) == 'undefined') lat = 47.22982711058905;
      if(typeof(lng) == 'undefined') lng = 9.897308349609375;
        
      if(GBrowserIsCompatible()) {
        this.map = new GMap2($('mapSmall'));
        var center = new GLatLng(lat, lng);
        this.map.setCenter(center, 6);        
        this.geocoder = new GClientGeocoder();
            
        var customUI = this.map.getDefaultUI();
        customUI.controls.scalecontrol = false;
        customUI.controls.largemapcontrol3d = false;
        customUI.controls.smallzoomcontrol3d = false;
        customUI.controls.maptypecontrol = false;        
        customUI.controls.menumaptypecontrol = false;
        customUI.maptypes.normal = true;
        customUI.maptypes.satellite = false;
        customUI.maptypes.hybrid = false;
        customUI.maptypes.physical = false;
        customUI.zoom.doubleclick = true; 
        customUI.zoom.scrollwheel = false;
        this.map.setUI(customUI);
      }
    }  
  },
  
  /**
   * loadProductDealer
   */
  loadProductDealer: function(){
    if($('storefinder')){
      this.addBusyClass('storefinder');
      new Ajax.Updater('storefinder', this.STR_BASE_PATH + '/product', {
        parameters: { },
        evalScripts: false,
        onComplete: function(transport) {
          //problem: ajax.updater evalScripts = true was too late
          transport.responseText.evalScripts();         
          
          this.removeBusyClass('storefinder');
        }.bind(this)
      });
    }
  },
  
  /**
   * loadOfflineDealers
   */
  loadOfflineDealers: function(elementId, mode){
    if(typeof(mode) == 'undefined') mode = '';
    
    if($(elementId)){
      $(elementId).update('');
      this.addBusyClass(elementId);
      new Ajax.Updater(elementId, this.STR_BASE_PATH + '/offdealers', {
        parameters: { 
          lng: this.longitude,
          lat: this.latitude,
          viewMode: mode
        },
        evalScripts: false,
        onComplete: function() {
          this.removeBusyClass(elementId);
        }.bind(this)
      });
    }
  },
  
  /**
   * loadOnlineDealers
   */
  loadOnlineDealers: function(elementId, mode){
    if(typeof(mode) == 'undefined') mode = '';
    
    if($(elementId)){
      $(elementId).update('');
      this.addBusyClass(elementId);
      new Ajax.Updater(elementId, this.STR_BASE_PATH + '/ondealers', {
        parameters: { 
          lng: this.longitude,
          lat: this.latitude,
          viewMode: mode 
        },
        evalScripts: false,
        onComplete: function() {
          this.removeBusyClass(elementId);
        }.bind(this)
      });
    }
  },
  
  /**
   * showDealer
   */
  showDealer: function(address){    
    var clientGeoXY = '';
    
	  /**
	   * validate data
	   */
	  this.validateInput();
  
	  /**
	   * show addresses if valid
	   */
	  if(this.blnValid){	    
	    if(typeof(address) == 'undefined') address = $('searchDealer').getValue(); 

	    if(this.geocoder) {
	      var map = this.map;
	      var marker = this.marker;
	      var strBasePath = this.STR_BASE_PATH;
	  
	      this.geocoder.getLatLng(
	          address,
	          function(latLng) {
			      if (!latLng) {
			        alert(address + " not found");
			      } else {
				      map.clearOverlays();
				  
				      map.setCenter(latLng, 8);
				      marker = new GMarker(latLng);			    
				      clientGeoXY = marker.getLatLng();
				      
				      /**
				       * show offline and online dealers list
				       */
				      myMap.longitude = clientGeoXY.x;
				      myMap.latitude = clientGeoXY.y;				      
				      myMap.loadOfflineDealers('offDealersContainer');
				      myMap.loadOnlineDealers('onDealersContainer');
				      
				      new Ajax.Request(strBasePath + '/dealers', {
				        parameters: { 
				          lng: clientGeoXY.x,
				          lat: clientGeoXY.y 
  			        },
  			        evalScripts: true,
  			        onComplete: function(transport) {
  			          var xmlStores = GXml.parse(transport.responseText);    			        
  			          var markers = xmlStores.documentElement.getElementsByTagName('marker');		            
  
  		            var bounds = new GLatLngBounds();
  		            for (var i = 0; i < markers.length; i++) {
  		              var name = markers[i].getAttribute('name');
  		              var distance = parseFloat(markers[i].getAttribute('distance'));
  		              var point = new GLatLng(parseFloat(markers[i].getAttribute('lat')),
  		                                      parseFloat(markers[i].getAttribute('lng')));
  		              
  		              var customIcon = new GIcon(G_DEFAULT_ICON);
    			      	  /**
    			      	   * create own marker icon
    			      	   */		                        
  		              customIcon.image    = '/website/themes/experience/images/storefinder/pointer.png';
  		              customIcon.shadow   = '/website/themes/experience/images/storefinder/pointer_shadow.png';
  		              customIcon.iconSize = new GSize(62, 45);
  		              customIcon.shadowSize = new GSize(62, 45);
  		              customIcon.imageMap = [0,0,32,0,32,32,0,32];
  
  		              markerOptions = { icon:customIcon, title:name, draggable: false, bouncy:true};
  		              
  		              var dealerMarker = myMap.createMarker(point, markers[i], markerOptions);		              
  		              map.addOverlay(dealerMarker);			              
  		              bounds.extend(point);
  		            }
  		            map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds)-1);
  			      }.bind(this)
  			    });
		      }
        });
      }
    }
  },
  
  /**
   * showDealerProduct
   */
  showDealerProduct: function(lat, lng){ 
    if(typeof(lat) == 'undefined') lat = this.latitude;
    if(typeof(lng) == 'undefined') lng = this.longitude;

    if(this.geocoder) {
      this.latitude = lat;
      this.longitude = lng;
      
      /**
       * load online and offline dealers
       */
      this.loadOfflineDealers('offlineResult', 'sidebar');
      this.loadOnlineDealers('onlineResult','sidebar');
      
      var latlng = new GLatLng(lat, lng);      
      this.map.clearOverlays();          
      
      new Ajax.Request(this.STR_BASE_PATH + '/dealers', {
        parameters: { 
          lng: latlng.x,
          lat: latlng.y 
        },
        evalScripts: true,
        onComplete: function(transport) {
          var xmlStores = GXml.parse(transport.responseText);                 
          var markers = xmlStores.documentElement.getElementsByTagName('marker');               
  
          var bounds = new GLatLngBounds();
          for (var i = 0; i < markers.length; i++) {
            var name = markers[i].getAttribute('name');
            var distance = parseFloat(markers[i].getAttribute('distance'));
            var point = new GLatLng(parseFloat(markers[i].getAttribute('lat')),
                                    parseFloat(markers[i].getAttribute('lng')));
            
            var customIcon = new GIcon(G_DEFAULT_ICON);
            /**
             * create own marker icon
             */                           
            customIcon.image    = '/website/themes/experience/images/storefinder/pointer.png';
            customIcon.shadow   = '/website/themes/experience/images/storefinder/pointer_shadow.png';
            customIcon.iconSize = new GSize(62, 45);
            customIcon.shadowSize = new GSize(62, 45);
            customIcon.imageMap = [0,0,32,0,32,32,0,32];

            markerOptions = { icon:customIcon, title:name, draggable: false, bouncy: false};
            
            var dealerMarker = this.createSmallMarker(point, markers[i], markerOptions);                  
            this.map.addOverlay(dealerMarker);                   
            bounds.extend(point);
          }
          this.map.setCenter(bounds.getCenter(), this.map.getBoundsZoomLevel(bounds));
        }.bind(this)
      });
    }
  },
  
  /**
   * createMarker
   */
  createMarker: function(point, xml, markerOptions) {
    var marker = new GMarker(point, markerOptions);
    var html = '<h4>' + xml.getAttribute('name') + '</h4>';
  	if(xml.getAttribute('street') != ''){
  	  html += '<div class="gStreet">'+xml.getAttribute('street')+'</div>';
  	}
  	if(xml.getAttribute('zip') != '' || xml.getAttribute('city') != ''){
  	  html += '<div class="gCity">';
  	  if(xml.getAttribute('zip') != '') html += xml.getAttribute('zip')+' ';
  	  if(xml.getAttribute('city') != '') html += xml.getAttribute('city');
  	  html += '</div>';
  	}
	
  	if(xml.getAttribute('phone') != ''){
  	  html += '<div class="gPhone">'+xml.getAttribute('phone')+'</div>';
  	}
  	if(xml.getAttribute('email') != ''){
  	  html += '<div class="gEMail"><a href="mailto:'+xml.getAttribute('email')+'">'+xml.getAttribute('email')+'</a></div>';
  	}
  	if(xml.getAttribute('website') != ''){
  	  html += '<div class="gWeb"><a href="http://'+xml.getAttribute('website')+'">'+xml.getAttribute('website')+'</a></div>';
  	}
	
  	html+= '<div class="clear"></div><div style="padding:10px 0 0 0;">'  		  
  		  +'  <div style="float:left; padding:0 10px 0 0;"><a href="http://www.google.com/maps?source=uds&amp;daddr='+xml.getAttribute('street')+'+'+xml.getAttribute('zip')+'+'+xml.getAttribute('city')+'&amp;iwstate1=dir%3Ato" target="_blank">To this location</a></div>'
  		  +'  <div style="float:left; padding:0;"><a href="http://www.google.com/maps?source=uds&amp;saddr='+xml.getAttribute('street')+'+'+xml.getAttribute('zip')+'+'+xml.getAttribute('city')+'&amp;iwstate1=dir%3Afrom" target="_blank">From here</a></div>'
  		  +'  <div class="clear"></div>'
  		  +'</div><div class="clear"></div>';
	
  	GEvent.addListener(marker, 'click', function() {
  	  marker.openInfoWindowHtml(html);
  	});
    return marker;
  },
  
  /**
   * createSmallMarker
   */
  createSmallMarker: function(point, xml, markerOptions) {    
    var marker = new GMarker(point, markerOptions);
    GEvent.addListener(marker, 'click', function() {
      if(xml.getAttribute('website') != ''){
        var url = xml.getAttribute('website');
        if(url.indexOf('http://') <= 0) url = 'http://' + url;
        self.location.href = url;  
      }
    });
    return marker;
  },
  
  /**
   * validateInput
   */
  validateInput: function(){
    if($('searchDealer')){
      if($('searchDealer').getValue() != ''){
        this.blnValid = true;	  
      }else{
        this.blnValid = false;
      }	
    }	  
  },
  
  /**
   * addBusyClass
   */
  addBusyClass: function(busyElement) {
    if($(busyElement)){
      $(busyElement).addClassName('busy');
    }
  },

  /**
   * removeBusyClass
   */
  removeBusyClass: function(busyElement) {
    if($(busyElement)){
      $(busyElement).removeClassName('busy');
    }
  }
});
