/**
 * Custom GMap2 Object for Dealers
 */
Object.extend(GMap2.prototype, {
  markerList: new Array(),
  moveEndEventStop: new Boolean(),
  moveEndListener: '',
  startPoint:'',
  language:'nl',
  directions:'',
  markerActive: '',
 	/*
	 * Get the address tags from the form
	 */
  getAddress: function(){
	    var address = '';
	    if ($F('location_form_address') != '' ){
	        address += $F('location_form_address') + ' ';
	    }
	    if ($F('location_form_city') != '' ){
	        address += $F('location_form_city') + ' ';
	    }
	    if ($F('location_form_zipcode') != '' ){
	        address += $F('location_form_zipcode') + ' ';
	    }
	    if ($F('location_form_country') != '' && address !=''){
	        address += ',' + $F('location_form_country');
	    }
	    return address; 		
  },
  /*
   * Get the category from the form
   */	
	getCategory: function(){
        var category = '';
        if ($F('location_form_category') != '' ){
            category = $F('location_form_category');
        }
        return category;     		
	},
    /*
     * Create Overlay
     * Default starting point is Rotterdam.
     * Directions is coupled to the location_directions_wrapper div.
     */
    createOverlay: function(point) {
        if (!point) {
        	if ($F('location_form_country') == 'Belgium'){
                this.startPoint = new GLatLng(50.84508,4.363976);
        	} else {
        	    this.startPoint = new GLatLng(51.918226,4.477959);
        	}
       } else {
       	    this.startPoint= point;           
        }
        this.setCenter(this.startPoint,11);
        this.addControl(new GSmallMapControl());
        this.addControl(new GMapTypeControl(true));               
        this.getXML();            
        this.moveEndListener = GEvent.addListener(this, "moveend", this.moveEndHandler.bind(this)); 
        this.directions = new GDirections(this,$('location_directions_wrapper'));
    },  
    /*
     * Get XML data from the api
     * Parameters are the latitude and longitude of the 
     * lower left (SW) corner and the upper right (NE) corner.
     * The category parameter comes from the form.
     */
    getXML:function(){
        var bounds = this.getBounds();
        var url = "api/geodata/?type=xml"
        url += "&category=" + this.getCategory();
        url += "&sw_lat=" +  bounds.getSouthWest().lat();
        url += "&sw_lng=" +  bounds.getSouthWest().lng();
        url += "&ne_lat=" +  bounds.getNorthEast().lat();
        url += "&ne_lng=" +  bounds.getNorthEast().lng();
        GDownloadUrl(url, this.getMarkersXML.bind(this));
    },
    /*
     * EndHandler
     */    
    moveEndHandler: function() {
    	if (this.activeMarker == ''){
    		this.markerList.each(
    			function(marker){
    				this.removeOverlay(marker);
    			}
    		);
	        this.markerList.splice(0, this.markerList.length);
    	}
        this.getXML();
    },    
    /*
     * Create Dealer Overlay
     * Max markers = 75.
     */
    getMarkersXML: function(data, responseCode) {
    	var Icon = new GIcon(G_DEFAULT_ICON);
    	Icon.iconSize = new GSize(27,27);
        Icon.image = "/images/googlemaps/marker_normal.png";
        Icon.iconAnchor = new GPoint(14,14);
        Icon.shadowSize = new GSize(27,27);
        Icon.shadow = "/images/googlemaps/marker_shadow.png";
    	
        var xml = GXml.parse(data);
        var markers = xml.documentElement.getElementsByTagName("Placemark");
		
        
		if (markers.length > 0){
			// show map
			if (markers.length < 75){
				for (var i = 0; i < markers.length; i++) {
					var point = markers[i].getElementsByTagName("Point")[0];
					var coordinates = point.getElementsByTagName("coordinates")[0].firstChild.nodeValue.split(',');
					var name = markers[i].getElementsByTagName("name")[0].firstChild.nodeValue;
					var ID = markers[i].getElementsByTagName("ID")[0].firstChild.nodeValue;
					var description = markers[i].getElementsByTagName("description")[0].firstChild.nodeValue;
					var marker = new GMarker(new GLatLng(parseFloat(coordinates[1]), parseFloat(coordinates[0])),{'icon': Icon,'title': name });
					marker.openInfoWindowListener = GEvent.addListener(marker, "infowindowopen", this.openInfoWindowHandler.bind(this));
					marker.bindInfoWindowHtml('<h3>' + name + '</h3>' + '<span style="font-size: 0.7em;">' + description + '</span>');
					marker.name = name;
					this.markerList[ID] = marker;
					this.addOverlay(this.markerList[ID]);
					if (this.markerActive == name +' [' +  ID + ']'){
						marker.setImage("/images/googlemaps/marker_hover.png");
					}
				}
				this.updateHTML(markers);
			} else {
				if (this.language == 'be_fr'){
					$('location_results').innerHTML = '<li>Too many dealers on this zoomlevel!</li>';
				} else {
					$('location_results').innerHTML = '<li>Er zijn te veel dealers voor dit zoomlevel!</li>';
				}
			}
		} else {
			// if zoomlevel > 7 zoomOut & try again
			if (this.getZoom() > 7) {
				this.zoomOut();
				this.getXML();
			}
		}
    },
    /* 
     * Handle the infowindowopen call 
     */
    openInfoWindowHandler: function(e){
        this.markerActive = e.getTitle();
        this.toggleAll();
	    e.setImage("/images/googlemaps/marker_hover.png");    	    
    },    
    /*
     * Create HTML list of dealers
     * This creates a long list inside the location_results ul
     */    
    updateHTML: function(markers){
    	var html='';
    	if (markers.length > 0){
    		$A(markers).each(function(marker){
					//console.log(marker.getElementsByTagName("name")[0].firstChild.nodeValue);
				}.bind(this)
			);
    		markers = $A(markers).sortBy(
    				function(marker){
    					var point = marker.getElementsByTagName("Point")[0];
    					var coordinates = point.getElementsByTagName("coordinates")[0].firstChild.nodeValue.split(',');
    					var position = new GLatLng(parseFloat(coordinates[1]), parseFloat(coordinates[0]))
    					return Math.round(position.distanceFrom(this.startPoint)/100)/10;
    				}.bind(this)
    				
    		);
    		markers.each(function(marker){
    			var name = marker.getElementsByTagName("name")[0].firstChild.nodeValue;
	            var description = marker.getElementsByTagName("description")[0].firstChild.nodeValue;
	            var point = marker.getElementsByTagName("Point")[0];
				var coordinates = point.getElementsByTagName("coordinates")[0].firstChild.nodeValue.split(',');
				var position = new GLatLng(parseFloat(coordinates[1]), parseFloat(coordinates[0]))
				var i = marker.getElementsByTagName("ID")[0].firstChild.nodeValue;
				var distance =  Math.round(position.distanceFrom(this.startPoint)/100)/10;
                                          
	            html += '<li id="result_'+ i +'">';
                html += '<h3>' + name + '</h3>';
                html+= description; 
	            if (this.language == 'be_fr'){
                    html += 'Distance: ' + distance  + ' km<br/>';
	                html += '<a id="pan_' + i +'" href="#" class="pan param-i='+ i + '">Plan</a>'
	                html += '<a id="route_' + i +'" href="#" class="route param-i='+ i + '">Itinéraire</a>'
	            } else {         
                    html += 'Afstand: ' + distance  + ' km<br/>';
	                html += '<a id="pan_' + i +'" href="#" class="pan param-i='+ i + '">Toon op kaart</a>'
	                html += '<a id="route_' + i +'" href="#" class="route param-i='+ i + '">Bereken route</a>'
	            }         
	            html+=  '</li>'
    		}.bind(this)
    		);
    		
    	}  else {
            if (this.language == 'be_fr'){
                html = '<li>Pas de revendeurs.</li>';
            } else {
            	html = '<li>Geen dealers gevonden</li>';
            }

            if (this.getCategory() == 'empty'){
            	if (this.language == 'be_fr'){
	                html = '<li>Vous cherchez quel appareil?</li>';
	            } else {
	                html = '<li>Wat voor apparaat zoekt u?</li>';
	            }
            }
    	}
    	$('location_results').innerHTML = html; 	
    },
    /*
     * Click handler
     * Clicks from a pan click will highlight a marker
     * Clicks from a route click will calculate the directions. It will also attach a class to the list, to narrow its width.
     */    
    listClickHandler:function(e){
    	var me = Event.findElement(e,'A');
        Event.stop(e);       
        var params = Element.getClassParameters(me);        
        var c = me.id.replace('_' + params.i,'');
        if (c =='pan'){
	        this.toggleAll();               
            this.markerActive = '';
	        this.markerList[params.i].setImage("/images/googlemaps/marker_hover.png");        	
        }
        if (c == 'route'){       	
        	var dealerPoint = this.markerList[params.i].getLatLng();        	
            this.directions.clear();
            var route = 'from: ' + this.startPoint.lat() + ',' +this.startPoint.lng() + ' to: ' + dealerPoint.lat() + ',' + dealerPoint.lng();
            if (this.language == 'be_fr'){
                this.directions.load(route,{ "locale":'fr_FR' });
            } else {         
                this.directions.load(route,{ "locale":'nl_NL' });
            }
            $('location_results').addClassName('active_results');         
        }
    },
    /*
     * swich all markers to default.
     */    
    toggleAll:function(){
        this.markerList.each(function(marker) {
        		marker.setImage("/images/googlemaps/marker_normal.png");
        	}
        );
    }           
});