/**
 * map.js
 *
 * Version history (please keep backward compatible):
 * 1.0, 2009-07-01: Cornelius Hansjakob
 * 2.0, 2010-05-20: Cornelius Hansjakob : multilanguage (DE and EN)
 *
 * @author Cornelius Hansjakob <cha@massiveart.com>
 * @version 1.0
 */

StoreMap = Class.create({

  initialize: function() {
	  this.map = null;
    this.geocoder = null;
    this.marker = null;
    this.languageId = 1;
    this.languageCode = 'de';
    
    this.blnValid = false;
    
    /**
     * init google map
     */   
    if($('map')){
  	  if(GBrowserIsCompatible()) {
  	    this.map = new GMap2($('map'));
  	    var center = new GLatLng(47.22982711058905, 9.897308349609375);
  	    this.map.setCenter(center, 4);
  	    this.geocoder = new GClientGeocoder();  	  
  	    
  	    this.map.addControl(new GLargeMapControl());
  	    this.map.addControl(new GMapTypeControl());
  	    this.map.addControl(new GScaleControl());
  	    
  	    this.map.enableDoubleClickZoom();
  	  }
  	}
        
    /**
     * address field
     */    
    if($('address')) {
      $('address').setStyle({color: '#ccc'});
      $('address').observe('focus', function(){ 
        if($('address').value != '' && ($('address').value == 'Adresse, PLZ, Ort, Land' || $('address').value == 'Address, Postcode, City, Country')){
        	$('address').value = '';
        	$('address').setStyle({color: '#000'});
        }
      }.bind(this));
      
      $('address').observe('blur', function(){ 
    	if($('address').value == ''){
    		$('address').setStyle({color: '#ccc'});
          if(this.languageCode == 'en'){
            $('address').value = 'Address, Postcode, City, Country';  
          }else{
            $('address').value = 'Adresse, PLZ, Ort, Land';  
          } 	
        }    
      }.bind(this));
    }
    
    /**
     * 'enter' key search
     */
    document.observe('keydown', function(event){
      if(event.keyCode == 13){
        this.showAddress($('address').value);	
      }    
    }.bind(this));
  },
  
  /**
   * show address
   */
  showAddress: function(address){
  	if(typeof(address) != 'undefined') {
  	  var clientGeoXY = '';
  	  
  	  /**
  	   * validate data
  	   */
  	  this.validateInput();
  	  
  	  /**
  	   * show addresses if valid
  	   */
  	  if(this.blnValid){
  	    if(this.geocoder) {
  		  var map = this.map;
  		  var marker = this.marker;
  		  
  		  this.geocoder.getLatLng(
  		    address,
  		    function(latLng) {
    			  if (!latLng) {
    			    alert(address + " not found");
    			  } else {
    			    map.clearOverlays();
  				  
    			    map.setCenter(latLng, 13);
    			    marker = new GMarker(latLng);			    
    			    clientGeoXY = marker.getLatLng();
    			    
    			    new Ajax.Request('/zoolu-website/storesearch/stores', {
    			      parameters: { 
    			    	  lng: clientGeoXY.x,
    			    	  lat: clientGeoXY.y,
    			    	  category: $('brand').value 
    			      },
    			      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
    			      	   */
    		            var company = markers[i].getAttribute('company');
    		            if(company == '') company = 'kanz';
    		            customIcon.image    = 'http://www.kanz-babykleidung.de/website/themes/kanz/images/gmap/' + company + '_placer.png';
    		            customIcon.shadow   = 'http://www.kanz-babykleidung.de/website/themes/kanz/images/gmap/placer_shadow.png';
    		            customIcon.iconSize = new GSize(50, 40);
    		            customIcon.shadowSize = new GSize(50, 40);
    		            customIcon.imageMap = [0,0,30,0,30,30,0,30];
    
    		            markerOptions = { icon:customIcon, title:name, draggable: false, bouncy:true};
    		              
    		            var storeMarker = myMap.createMarker(point, markers[i], markerOptions);		              
    		            map.addOverlay(storeMarker);			              
    		            bounds.extend(point);
    		          }
    		          map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
    			      }.bind(this)
    			    });
    			  }
    			});
    		}
  	  }
    }
  },
  
  createMarker: function(point, xml, markerOptions) {
  	var marker = new GMarker(point, markerOptions);
  	var html = '<h5>' + xml.getAttribute('name') + '</h5>';
  	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('mobile') != ''){
  	  html += '<div class="gMobile">'+xml.getAttribute('mobile')+'</div>';
  	}
  	if(xml.getAttribute('fax') != ''){
  	  html += '<div class="gFax">'+xml.getAttribute('fax')+'</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>';
  	}
	
  	var dirTitle = 'Wegbeschreibung:';
  	if(this.languageCode == 'en'){
  	  dirTitle = 'How to find us:';
  	}
  	var dirTo = 'Nach hier';
  	if(this.languageCode == 'en'){
  	  dirTo = 'to here';
    }
  	var dirFrom = 'Von hier';
  	if(this.languageCode == 'en'){
  	  dirFrom = 'from here';
    }
	
	  html += '<div style="padding:10px 0 0 0;">'
  		   +'  <div style="float:left; padding:0 5px 0 0;">'+dirTitle+'</div>'
  		   +'  <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">'+dirTo+'</a></div>'
  		   +'  <div style="float:left;"><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">'+dirFrom+'</a></div>'
  		   +'  <div class="clear"></div>'
  		   +'</div>';
  	GEvent.addListener(marker, 'click', function() {
  	  marker.openInfoWindowHtml(html);
  	});
    return marker;
  },
  
  validateInput: function(){
    if($('address')){
      if($('address').value == '' || ($('address').value == 'Adresse, PLZ, Ort, Land' || $('address').value == 'Address, Postcode, City, Country')){
        this.blnValid = false;	  
      }else{
        this.blnValid = true;
      }	
    }	  
  }
});