/*
    Class:      Locator
    Author:     Marco Dell'Anna
    Website:    #
    Version:    1.0
    Date:       23/10/2009
    Built For:  MooTools 1.2
*/
var locator = new Class({
    //implements
    Implements: [Options],
	i:1,
	ArrayMarker:Array(),
    //options
    options: {
		updatePage:  'update.php',            // File response
        textLoader:  'Caricamento contenuti', // Text sleep
        contenitore: 'ricerca',               // ID Form
        item: 'cap'                           // ID Valore
    },
    
    //initialization
    initialize: function(options) {
        //set options
        this.setOptions(options);
        //init elements
        this.initStage();
		this.map = this.load();
		// Esegue richiesta al drag
		GEvent.addListener(this.map, 'dragend', function() {
			this.ajaxRequest(this.map.getCenter());
		}.bind( this ));
		// Scarica
	    window.addEvent('onunload', function() {
			GUnload();
		});
    },
    
    // 
    initStage: function(){
		//
		var prefisso = this.options.contenitore;
		var submit   = prefisso + "-submit";
		// Ricerca
		$(prefisso).addEvent("submit", function(e){
			e.stop();
			// Centra mappa secondo nuovo indirizzo
			this.centerMap();
			// Rimuove tutti i possibili marker
			// this.removeAllMarkers( this.ArrayMarker, this.map);
			// Esegue richiesta asincrona
			this.ajaxRequest();
		}.bind( this ))
    },

	centerMap: function() {
		var address = "italy, " + $(this.options.item).get("value");

		if (address.length > 0) {
			var geocoder = new GClientGeocoder();
				geocoder.getLatLng(address,
					function(point) {
						if(!point){
							alert('Address "' + address + '" not found');
						}else{
							// Centra la mappa
							this.map.setCenter(point, 16);
						}
					}.bind( this ));
		}
	},
	
	load: function() {
		if (GBrowserIsCompatible()) {
		// Aggiunge Mappa
		var map = new GMap2($("map"));
			// Aggiunge Controllo Navigazione
			map.addControl(new GLargeMapControl3D());
			// Visualizza tipologie di mappa
			map.addControl(new GMapTypeControl());
			// Visualizza Minimappa Laterale		
			// map.addControl(new GOverviewMapControl(new GSize(200,200)));
			// Disabilita DBClick&Zoom
			map.disableDoubleClickZoom();
			// Abilita Rotella&Zoom
			//map.enableScrollWheelZoom();
			// Localizza la vista della Mappa
			map.setCenter(new GLatLng(46.49661971888299, 11.361923217773438), 16);
			//GEvent.addListener(map, "click", mapClick); 
			return map;
		}
	},
	
	
	/*
	Rimuove tutti i Marker da una mappa
	@ array marker, mappa
	*/
	removeAllMarkers:function( aMarker, map){
		for(i=0;i<aMarker.length;i++){
			map.removeOverlay(aMarker[i]);
		}
	},
	
	/*
	Aggiorna Coordinate elemento e le printa
	@latitudine
	@longitudine
	*/
	updateCoordinate:function(lat, lng){
		// Imposta Latitudine
		$('xcoord').set("value", lng );
		// Imposta Longitudine
		$('ycoord').set("value", lat );
	},
	
	/*
	Aggiunge Un marker Esistente
	@latitudine
	@longitudine
	@mappa
	*/
	addExistMarker:function(lat, lng, map){
		// Test Add mark
		map.setCenter(new GLatLng(lat, lng), 16);
		this.addMarker(map,new GLatLng(lat, lng));
		// Aggiorna posizione Marker
		this.updateCoordinate(lat, lng)
	},
	
	/*
	Aggiunge un Marker
	@map : mappa dove aggiungere il marker
	@point:Object
	*/
	addMarker: function(map, point, itemInfo){
		// Verifica se il Marker non è presente sulla mappa
		if( this.checkMarkerInArray(this.ArrayMarker, itemInfo.id) == false ){
			// Imposta Icon
			var icona = this.getIcon();
			// Crea un Marker secondo le coordinate del punto
			var marker = new GMarker(point, {
				draggable:false,
				icon:icona
			});
		
			marker.id = itemInfo.id;
			// Aggiunge Marker ad array
			this.ArrayMarker.push(marker);
		
			// marker.id = this.i++;
		
			// Aggiunge Marker alla mappa 
			this.map.addOverlay(marker);

			// Visualizza contenuto
			GEvent.addListener(marker, "click", function() {
				var string  = itemInfo.nome ? itemInfo.nome + "<br />" : "";
					string += itemInfo.indirizzo_it ? itemInfo.indirizzo_it + "<br />" : "";
					string += "<a href='/"+LANGUAGE+"/locator/contatta/?id=" + itemInfo.id + "'>Contatta</a><br />";
				// Inserisci info
				marker.openInfoWindowHtml(string ,{maxWidth:400});
			});
		}
	},
	
	getIcon: function() {
		var icona = new GIcon();
			icona.image            = "/assets/css/maps/pointer.png";
			icona.iconSize         = new GSize(25,  35);
			icona.shadowSize       = new GSize(16,  16);
			icona.iconAnchor       = new GPoint(13, 36);
			icona.infoWindowAnchor = new GPoint(9,  2);
			icona.infoShadowAnchor = new GPoint(18, 25);
		return icona;
	},
	
	checkMarkerInArray: function(myArray, idM){
		var ck = false;
		myArray.each( function(e, i ){
			// console.log(e.id + " ----- " + idM)
			if( e.id == idM )
			ck = true;
		})
		return ck;
	},
   
    ajaxRequest: function(point){
        // var contenitore         = this.options.contenitore;
        // var textLoader          = this.options.textLoader;
        // var loader              = this.printLoading(this.options.textLoader);
        // var incrementStartValue = this.options.incrementStartValue;
		data = { "address" : $(this.options.item).get("value") };
		if(point){
			data.lat = point.Md;
			data.lon = point.Ha;
		}
        var req = new Request.JSON({
                    method: 'post',
                    url: this.options.updatePage,
                    data: data,
                    evalScripts: true,
                    evalResponse: true,
                    onRequest: function() {
                    	// Append Loading
                       // loader.inject( $(contenitore), 'bottom');
                    },
                    onComplete: function( response ) {
						// Rimuove tutti i possibili marker
						// this.removeAllMarkers( this.ArrayMarker, this.map);
						// Inserisce nuovi Marker
						response.each( function(item, i){
							if( item.xcoordinate && item.ycoordinate ){
								this.addMarker(this.map,new GLatLng(item.ycoordinate, item.xcoordinate), item);
							}
						}.bind( this ))
                    }.bind(this)
                  }).send();
    }
});
