// <![CDATA[
var geosuggests=['/percorsi/address-lookup.jsp','/percorsi/address-suggest.jsp'];
var geosuggest=geosuggests[1]; 
/**
 * toggle opzioni avanzate
 */
$('ap-tipo').hide();
$('mezzopubblico').addEvent('click', function(){
	$('mp-tipo').show(); $('ap-tipo').hide();
});
$('auto').addEvent('click', function(){
	$('mp-tipo').hide(); $('ap-tipo').show();
});
$('apiedi').addEvent('click', function(){
	$('mp-tipo').hide(); $('ap-tipo').hide();
});
/* global variables */
var contextPath=g5t.contextPath;
var selectedRoute=0;
var journeys=null;
/**
 * toggle map
 */
function toggleMap() {
	var width;
	width= !$("toggleBtn").open? "878px": "440px";
	$("toggleBtn").set("html", !$("toggleBtn").open? "apri" : "chiudi" );
	$("divider").set("class", !$("toggleBtn").open? "open" : "close" );
	$("toggleBtn").open = !$("toggleBtn").open;
	$('mapContainer').get("morph").start({
		width: width
	}).chain(function(){
		gmap.checkResize();
	});
}

gmap=null;
var routeIndex=0;
function findAddressDelay(type){
	findAddressTimer=(function(){
		findAddress(type);
	}).delay(500);
}
/***
 * clear the address.
 */
clearAddress=function(type){
	$(type+'Lat').value='';
	$(type+'Lng').value='';
	$(type+'Category').value='indirizzo';
	$(type+'Name').value='';
	if($(type+"Error")){
		$(type+"Error").set("html","");
	}
};
/**
 * cerca indirizzi per tipo (type=origin/destination)
 */
var findAddressTimer=0;
function findAddress(type,element){
	if(findAddressTimer)
		findAddressTimer=0;
	if($(type+'FullAddress').value=="")
		return;	
	var fullAddress=$(type+'FullAddress').value.trim();
	var request={
			fullAddress : fullAddress
	};
	var object;
	if (element && element.get("g5t-latLng")){
		try{
			object=JSON.decode(element.get("g5t-latLng"));
		}catch(e){}
	}
	if(object && object.lat && object.lng){
		var placemark=object;
		if(object.category=='')
			object.category='indirizzo';
		if(type=="origin"){
			placemark.name=placemark.id="Partenza";
			placemark.bgColor="#6fc315";
			placemark.icon=g5t.contextPath+'/img/ico-start.png';
		}else{
			placemark.name=placemark.id="Arrivo";
			placemark.bgColor="#e42323";
			placemark.icon=g5t.contextPath+'/img/ico-end.png';
		}	
		$(type+"Lat").value=object.lat;
		$(type+"Lng").value=object.lng;
		$(type+"Category").value=object.category;		
		placemark=new g5t.geo.Placemark(placemark);
		journeyCtrl.loadData(placemark,'Placemark');
		return;
	}else {
		var geocoder=new g5t.geo.Geocoder();
		geocoder.getLocations(request,function(response){
			try {
				if(!response || !response.results || response.results.length!=1)
					return;
				var placemark=response.results[0];
				if(type=="origin"){
					placemark.name=placemark.id="Partenza";
					placemark.bgColor="#6fc315";
					placemark.icon=g5t.contextPath+'/img/ico-start.png';
					$("originCategory").value='indirizzo';
				}else{
					placemark.name=placemark.id="Arrivo";
					placemark.bgColor="#e42323";
					placemark.icon=g5t.contextPath+'/img/ico-end.png';
					$("destinationCategory").value='indirizzo';
				}	
				journeyCtrl.loadData(placemark,'Placemark');
			}catch(e){}
		});
	}
}
/***
 * get address by point coordinates (lat-lng).
 * @param latLng
 * @param type
 * @return
 */
function getAddress(latLng,type){
	type = type || 'Partenza';
	var geocoder=new g5t.geo.Geocoder();
	geocoder.getLocations(latLng,function(response){
		var placemark=response[0];
		placemark.name=placemark.id=type;
		if(type=='Partenza'){
			placemark.bgColor="#6fc315";
			placemark.icon=g5t.contextPath+'/img/ico-start.png';			
		}else{
			placemark.bgColor="#e42323";
			placemark.icon=g5t.contextPath+'/img/ico-end.png';			
		}	
		journeyCtrl.loadData(placemark,'Placemark');
	});
}
//Transport type enumeration
TransportType = {
	/*"mot_1"		:	{color: "#A52A2A", name: "metro", icon: "${webPath}img/percorsi/mot_1.png"},*/
	"mot_1"		:	{color: "#e40e0e", name: "metro", icon: "${webPath}img/percorsi/mot_1.png"},
	"mot_2"		:	{color: "#8B4513", name: "train", icon: "${webPath}img/percorsi/mot_2.png"},
	/*"mot_4"		:	{color: "#009900", name: "tram", icon: "${webPath}img/percorsi/mot_4.png"},*/
	"mot_4"		:	{color: "#FFA500", name: "tram", icon: "${webPath}img/percorsi/mot_4.png"},
	"mot_5"		:	{color: "#FFA500", name: "bus", icon: "${webPath}img/percorsi/mot_5.png"},
	"mot_6"		:	{color: "#1E90FF", name: "extra-bus", icon: "${webPath}img/percorsi/mot_6.png"},
	"mot_7"		:	{color: "#1E90FF", name: "special-bus", icon: "${webPath}img/percorsi/mot_7.png"},
	"mot_105"	:	{color: "#FFFF00", name: "taxi", icon: "${webPath}img/percorsi/mot_105.png"},
	"mot_106"	:	{color: "#1E90FF", name: "car", icon: "${webPath}img/percorsi/mot_106.png"},  // auto
	"mot_100"	:	{color: "#4682B4", name: "foot", icon: "${webPath}img/percorsi/mot_100.png"},  // piedi
	"mot_99"	:	{color: "#4682B4", name: "foot", icon: "${webPath}img/percorsi/mot_100.png"}  // piedi
};
var placemarkInfoTpl=[
   '<p><span style="background-color:{bgColor};color:white;padding:2px 5px" ><b>{name}</b></span></p>',                		 
   '<p>{fullAddress}</p>',
   '<p style="text-align:right;">',
   '<a href="javascript: journeyCtrl.removeOverlay(null,\'{id}\',\'Placemark\');">cancella</a>',
   '</p>'
];

window.addEvent("domready",function(){
	/***
	 * build google map.
	 */	
	var zoomCtlOpt = {
			position: google.maps.ControlPosition.RIGHT_TOP,
			style:	google.maps.ZoomControlStyle.SMALL
	};
	
	var mapOptions = {
		      zoom		: 13,
		      mapTypeControlOptions: {
				mapTypeIds	: ['_5T',google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.SATELLITE]
			  },
			  mapTypeId	: google.maps.MapTypeId.ROADMAP,
			  zoomControl:true,
			  zoomControlOptions: zoomCtlOpt,
			  panControl:false
			};
	
	gmap = new g5t.geo.Map("map-jp",mapOptions);
	gmap.mapTypes.set('_5T', styledMapType5T);
    gmap.setMapTypeId('_5T');
	locationControl=new g5t.maps.GeocoderControl({map: gmap});
	var contextMenu=new g5t.maps.ContextMenu('contextMenu',{
		map: gmap,
		handles : {
			getOrigin: function(latLng) {
			    getAddress(latLng,'Partenza');
			},
			getDestination: function(latLng) {
				getAddress(latLng,'Arrivo');
			}
		}
	});
	/***
	 *  journey controller
	 */
	journeyCtrl=new g5t.TransportCtrl(gmap,{
	  categories: {
		Placemark: {
			baseCategory: 'Marker',
			options	: {
				infoTpl		: placemarkInfoTpl,
				zoomLevel	: 13,
				draggable	: true,
				binding 	: {
		 			infoTpl : "infoTpl",
		 			id		: "id",
		 			icon	: "icon"
				}
			}
		},
		Route: {
			options: {
				clickable	  : false,
				strokeOpacity : 0.0
			}
		},
		Journey: {
			options: {
				clickable	  : false
			}
		}
	  }
	});
	journeyCtrl.addEvents({
		"PlacemarkAdded"	: function(overlay){
			overlay.openInfoWindowHtml();
			var marker=overlay;
			var type = marker.object.name=="Partenza"? 'origin' : 'destination';
			$(type+'FullAddress').value=marker.object.address;
			$(type+'City').value=marker.object.locality.LocalityName || marker.object.locality;
			if(marker.object.number)
				$(type+'FullAddress').value=marker.object.address+", "+marker.object.number;
			$(type+'FullAddress').value += ($(type+'FullAddress').value!=""?", ":"") + $(type+'City').value;
			$(type+'Lat').value=marker.object.lat;
			$(type+'Lng').value=marker.object.lng;
			$(type+'Category').value=marker.object.category || 'indirizzo';
			google.maps.event.addListener(marker,"dragend", function(){
				//me.getPlacemark(null, marker.getPoint(), plmarkIndex);
				getAddress(marker.getPosition(),marker.object.name);
			});			
		}
	});	
	
	  /***
	   * extends the transport controller
	   */
	Jobject.extend(journeyCtrl, {
		  /***
		   * open route point info window.
		   */
		  openRoutePointInfo: function(id){
		     id=journeys[selectedRoute].id+"-"+id;
		     var overlay=this.getOverlay(id,"RoutePoint");
		     if(!overlay)
			     overlay=this.getOverlay(id,"RouteStopPoint");
		     if(overlay)
			     overlay.openInfoWindowHtml();
	  	  }
	});
	if(journeys && journeys.length>0)
		journeyCtrl.loadData([journeys[0]],'Journey');
	/** 
	 * crea autocompleter per la pagina. 
	 */
	[
	 {field:'originFullAddress',		name:'geo.address', link: {field: 'originCity', 		name: 'geo.city'}},
	 {field:'destinationFullAddress', 	name:'geo.address', link: {field: 'destinationCity', 	name: 'geo.city'}}
	].each(function(el){
		 var postData = {action: 'resolve',/* 'use-geocoding': true, */ type: el.type};
		 
		 var auto=new Autocompleter.Request.HTML(el.field, contextPath+geosuggest, 
		 {
			 selectMode	: false,
			 postData	: postData,
			 postVar	: el.name,
			 //forceSelect: false,//false è il default
			 injectChoice: function(choice) {
			 	value = choice.innerHTML;
			 	choice.inputValue = value;
			 	choice.set('html', this.markQueryValue(value));
			 	this.addChoiceEvents(choice);
		 	}		    	 
		 });
		 auto.addEvent("onSelection", function(element, selected, value, input){
			 if(findAddressTimer){
				clearTimeout(findAddressTimer);
				findAddressTimer=0;
			 }
			 if(element.id == "originFullAddress"){
				 findAddress("origin",selected);
			 }else if(element.id == "destinationFullAddress"){
				 findAddress("destination",selected);
			 }	 
		 });
		 if(el.link){
			 var link=el.link;
			 auto.addEvent("onRequest",function(element, req, data, qvalue){
				 data[link.name]=$(link.field).value;  
			 });
		 }
	 });	
});
/***
 * loads route detail.
 */
// carica, se non già fatto, il dettaglio del percorso e lo visualizza del div dettaglio
function loadRouteDetail(index,hide){
	 $$(".dettaglio-percorso").each(function(e,i){
		 if(i!=index)
			 e.hide();
		 else {
			 if(e.getAttribute("g5t:loaded")!="true"){
				 e.load("calcolo-percorsi-dettagli.jsp?routeIndex="+index);
				 e.setAttribute("g5t:loaded",true);
			 }
			 e.show();
		 }
	 });
}
/***
 * show the specified journey.
 */
function showJourney(index){
	  if(selectedRoute!=index){
		var journey=Jobject.clone(journeys[index]);
		journey.partialRoutes=null;
		journey.routePoints=null;
		journey.color="#9999FF";
	  	journeyCtrl.createJourney(journey,null,null,true);
		
	  }
}
/***
 * remove the specified journey.
 */
function removeJourney(index) {
	  if(selectedRoute!=index){
		var journey=Jobject.clone(journeys[index]);
		journey.partialRoutes=null;
		journey.routePoints=null;

		journeyCtrl.removeOverlay(journey,journey.id,'Journey');
	  }
}
/***
 * toggle the specified journey.
 */
function toggleJourney(index,anchor){
	  
	  selectedRoute=index;
	  
	  $$('#lista-percorsi li.selected]').removeClass("selected");
	  $(anchor).addClass("selected");
	  journeyCtrl.clearOverlays('Journey');
	  journeyCtrl.loadData([journeys[index]],'Journey');
	  loadRouteDetail(index);
}
/* icon based radio button  */  
window.addEvent('domready', function(){
		FancyForm.start([$('mezzopubblico'),$('autoprivata'),$('apiedi')]);
});

/* main code */
window.addEvent("domready", function(){
	  if(routesNumber){
	  var request = new Request.JSON({
		  url: contextPath+"/percorsi/journey.js.jsp?open-route-info=journeyCtrl.openRoutePointInfo",
		  noCache: true,
		  onSuccess: function(response, responseText) {
				if(!response){
					response=eval(responseText);
				}
				journeys=response;
				if(journeys && journeys.length>0){
				  //loadRouteDetail(0);
				  journeyCtrl.loadData([journeys[0]],'Journey');	
				}		
		   }
	  });
	  request.get();
	  }
});


//]]>
