(function($) {
	var map;
	var mapEl;
	$.fn.mappaContatti = function(options) {
		
		var opts = $.extend({}, $.fn.mappaContatti.defaults, options);

		directionsEl=$('#'+opts.directionsEl+'');
		mapEl=$(this);
		arrivo=opts.arrivo;
		locale=opts.locale;
		
		if(directionsEl.css('display')=='block'){
//			larg_originale=(mapEl.width()+5)*2;

			directionsEl.hide();
			
			mapEl.css({float:'none'});
//			mapEl.width(larg_originale);
		}

		var latlng = new google.maps.LatLng(opts.centro_lat, opts.centro_lon);
		
		var mapOptions = {
			zoom: opts.zoom,
			center: latlng,
			mapTypeId: google.maps.MapTypeId.SATELLITE,
			mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU}
		};
		
		var map = new google.maps.Map(mapEl.get(0), mapOptions);

		addMarker(map,latlng,opts.testo_box);
		
		addDirections(map);
	}
	
	$.fn.mappaContatti.defaults = {
			centro_lat:   '44.455058',
			centro_lon:   '11.507149',
			zoom:   17,
			testo_box:    '',
			directionsEl: 'directions',
			arrivo:'',
			locale:'it'
	};
	
	function addMarker(map,latlng,testo_box){
		var infowindow = new google.maps.InfoWindow({
			content:testo_box
		});

		var marker = new google.maps.Marker({
			position: latlng, 
			map: map,
			title:'cips'
		}); 
		
		google.maps.event.addListener(marker, 'click', function() {
			infowindow.open(map,marker);
		});
	}
	
   function addDirections(map){
		directionsService = new google.maps.DirectionsService();
		
		directionsDisplay = new google.maps.DirectionsRenderer();
		directionsDisplay.setMap(map);
		directionsDisplay.setPanel(directionsEl.get(0));
		
		$('#submitDirections').bind('click', {mapEl: mapEl, directionsEl: directionsEl}, $.fn.mappaContatti.addDirectionsCallback);

//		$('#submitDirections').click($.fn.mappaContatti.addDirectionsCallback);
	}
	
	$.fn.mappaContatti.addDirectionsCallback=function(event){
		event.data.directionsEl.html('');
		alt_finale=mapEl.height();
		larg_finale=(mapEl.width()/2)-5;
	
		if(directionsEl.css('display')!='block'){
			event.data.mapEl.width(larg_finale);
			event.data.directionsEl.width(larg_finale);
			event.data.directionsEl.height(alt_finale);
			
			event.data.directionsEl.css({overflow:'auto',display:'block'});
			
			event.data.mapEl.css({float:'left'});
			
			event.data.directionsEl.show();
		}
		
		$('#map').mappaContatti.setDirections($('#indirizzo').val(), arrivo,locale);
	}
	
	$.fn.mappaContatti.setDirections=function(fromAddress, toAddress, locale) {
//      alert("from: " + fromAddress + " to: " + toAddress)
		
		var start = fromAddress;
		var end = toAddress;
		var request = {
			origin:start, 
			destination:end,
			travelMode: google.maps.DirectionsTravelMode.DRIVING
		};
		
		directionsService.route(request, function(response, status) {
			if (status == google.maps.DirectionsStatus.OK) {
				directionsDisplay.setDirections(response);
			}else{
				handleErrors(status);
			}
		});
   }
	 
	function handleErrors(status){
		if (status == google.maps.DirectionsStatus.NOT_FOUND)
			directionsEl.html("<p class=\"mapError\">Non sono state trovate le coordinate geografiche dell'indirizzo inserito. Questo puo' dipendere dal fatto che l'indirizzo e' relativamente nuovo oppure non e' corretto.</p><p class=\"mapError\">Codice errore: " + status+"</p>");
		else if (status == google.maps.DirectionsStatus.UNKNOWN_ERROR)
			directionsEl.html("<p class=\"mapError\">La richiesta di indicazioni stradali o di coordinate geografiche non e' andata a buon fine, ma la ragione e' sconosciuta (???).</p><p class=\"mapError\">Codice errore: " + status+"</p>");
//		else if (status == google.maps.DirectionsStatus.G_GEO_MISSING_QUERY)
//			directionsEl.html("<p class=\"mapError\">Manca il parametro HTTP 'q' oppure e' privo di valore. Nel caso di richieste di coordinate geografiche vuol dire che non e' stato immesso un indirizzo. Nel caso di richieste di indicazioni stradali che la rihiesta e' vuota.</p> Codice errore: " + status+"</p>");
//		else if (status == google.maps.DirectionsStatus.G_GEO_BAD_KEY)
//			directionsEl.html("<p class=\"mapError\">La Google Map Key non e' valida o non corrisponde al dominio corrente.</p><p class=\"mapError\">Codice errore: " + status+"</p>");
		else if (status == google.maps.DirectionsStatus.ZERO_RESULTS)
			directionsEl.html("<p class=\"mapError\">La richiesta di indicazioni stradali non e' stata letta correttamente.</p><p class=\"mapError\">Codice errore: " + status+"</p>");
		else 
			directionsEl.html("<p class=\"mapError\">Errore sconosciuto.</p>");
	}
})(jQuery);

