var map;
var maps = Array();
var initFunctions = Array();
	
	function getMyMap(mapid){		
		for(k=0;k<mapOptions.length;k++){			
			if(mapOptions[k].id==mapid){
				return(mapOptions[k].data);
				}
			}
		}
		
	function getOption(obj,param){
		for(k=0;k<obj.length;k++){			
			if(typeof(eval("obj[k]."+param))!="undefined"){
				return(eval("obj[k]."+param));
				}
			}		
		}
	
	function RouteMe(mapid,oggetto,indirizzo){
		if(typeof(indirizzo)=='undefined'){
			
			directionsService = new google.maps.DirectionsService();
			directionsDisplay = new google.maps.DirectionsRenderer();t
			
			
			oggetto=$(oggetto).parent()[0];
			$(oggetto).fadeTo(200,0.5,function(){
				//$(oggetto).html('Calcola percorso fino a<br><b>' + MDBActiveMarker.title + '</b><br/><br/>Partenza:<br/><input type=\'text\' id=\'RouteAddressFrom\' value=\'Inserisci indirizzi di partenza\' onfocus=\'this.value=""\' style=\'width:90%;color:#999;\'/> <a href=\'#\' onclick=\'RouteMe(null,document.getElementById("RouteAddressFrom").value)\'>Calcola percorso</a>');
				$(oggetto).html('');
				$(oggetto).fadeTo(200,1);
				});
			}
		else{
  			  maps[mapid].clearDirections();
			  maps[mapid].clearMarkers();
			  
			  directionsDisplay.setMap(map);
			  if($('#map_directions').length>0){
				  directionsDisplay.setPanel(document.getElementById("map_directions"));
				  }
			  
			  var request = {
				origin:indirizzo,
				destination:MDBActiveMarker.position,
				travelMode: google.maps.TravelMode.DRIVING
			  };
			  
			  directionsService.route(request, function(result, status) {
				if (status == google.maps.DirectionsStatus.OK) {
				  directionsDisplay.setDirections(result);	
				  $("#RouteAddressFrom").val('Calcola altra partenza');			  
				  maps[mapid].MDBdirections.push(directionsDisplay);
				}
				else{
					$("#RouteAddressFrom").after('Non trovato<br/>');
					}
			  });
			}
		}
	
	function PrintMarker(mapid,posizione,markerIcon,contentString,titolo,route,around,setAsActive,idlocation){		
	
			opzioni=getMyMap(mapid);
	
			if(markerIcon.indexOf("spacer.gif")>0){return false;}
				
			if(typeof(posizione)=="string"){
				ll=posizione.split(",");	
				var myLatlng = new google.maps.LatLng(eval(ll[0]),eval(ll[1]));
				}
			else{
				var myLatlng=posizione.geometry.location;
				}
			
			showme=true;
			
			if(showme==true){
			google.maps.Marker.prototype.ShowMyMarker=function(){
				try{
				this.MYinfoWidow[0].open(maps[mapid],this);
				}catch(e){}
				}
	
			var marker = new google.maps.Marker({
				map: maps[mapid], 
				position: myLatlng,
				title:titolo+' ',
				icon:((typeof(markerIcon) != 'undefined' && markerIcon.length>0) ? markerIcon : '')
			});
			
			//contentString+=((typeof(route) != 'undefined' && route=='1')? '&nbsp;<a href=\'#routeme\' onclick=\'RouteMe(this);\'>Calcola Percorso</a>&nbsp;':'') + ((typeof(around) != 'undefined' && around==1)? '&nbsp;<a href=\'#aroundme\' id=\'aroundmelink\' onclick=\'AroundMe()\'>In zona</a>&nbsp;':'')
			contentString+=((typeof(route) != 'undefined' && route=='1')? '':'')
			
			if(contentString!="" && (getOption(opzioni,"MDBNOShowInfo")==false || typeof(getOption(opzioni,"MDBNOShowInfo"))=="undefined")){
				var infowindow = new google.maps.InfoWindow({
					content: contentString+' '
				});
				
				marker.MYinfoWidow.push({"id":idlocation,"window":infowindow});
				
				google.maps.event.addListener(marker, 'click', function() {				
					try{
					maps[mapid].myMDBActiveWindow.close();}catch(e){};
				  	maps[mapid].myMDBActiveMarker=marker;
					maps[mapid].myMDBActiveWindow=infowindow;
				    infowindow.open(maps[mapid],marker);
				});
				}

			maps[mapid].MDBmarkers.push(marker);
			
			if(typeof(setAsActive)!="undefined" && (getOption(opzioni,"MDBShowInfoByDef")=="true" || getOption(opzioni,"MDBShowInfoByDef")==1)){			
				marker.ShowMyMarker();
				maps[mapid].myMDBActiveWindow=infowindow;
				}			
			
			if(typeof(maps[mapid].mylatlngbounds)=="undefined" || maps[mapid].mylatlngbounds.isEmpty()==true){
				maps[mapid].mylatlngbounds = new google.maps.LatLngBounds(marker.getPosition());
				}
			else{
				maps[mapid].mylatlngbounds.extend(marker.getPosition());
				}
				
			if(maps[mapid].MDBmarkers.length==1){
				opzioni=getMyMap(mapid);
				maps[mapid].setZoom(parseInt((typeof(getOption(opzioni,"MDBdetailZoom"))=='undefined' || getOption(opzioni,"MDBdetailZoom")=='') ? 16 : getOption(opzioni,"MDBdetailZoom")));
			}
				
			}
		}
	
	function AroundMe(mapid){
			maps[mapid].myMDBActiveWindow.close();
			maps[mapid].setZoom(MDBdetailZoom);
			enableAround(1);
			loadData(); 			
		}

	function ShowSingleAddress(mapid,address,markerIcon,contentString,titolo,route,around,idlocation){	
				
		maps[mapid].clearMarkers();
		maps[mapid].setZoom(getMyMap(mapid).MDBdetailZoom);
		delete maps[mapid].mylatlngbounds;
		maps[mapid].mylatlngbounds=new google.maps.LatLngBounds();
		codeAddress(mapid,address,markerIcon,contentString,titolo,route,around,1,idlocation);
		}

	 function codeAddress(mapid,address,markerIcon,contentString,titolo,route,around,setAsActive,idlocation) {	
	 	 		 
		geocoder = new google.maps.Geocoder();		
		geocoder.geocode( { 'address': address}, function(results, status) {	
		  if (status == google.maps.GeocoderStatus.OK) {
			  PrintMarker(mapid,results[0],markerIcon,contentString,titolo,route,around,setAsActive,idlocation);
			  if(maps[mapid].MDBmarkers.length>1){			  
				  maps[mapid].setCenter(maps[mapid].mylatlngbounds.getCenter(),maps[mapid].panToBounds(maps[mapid].mylatlngbounds));
				  maps[mapid].fitBounds(maps[mapid].mylatlngbounds);
			  }
			  else{
				  maps[mapid].setCenter(maps[mapid].MDBmarkers[0].position);
				  }
		  }
		});

	  }
	  
	  
	  function codeLocation(mapid,idlocation,pos,nome,contentString,markerIcon,idlocation){	 	  
			PrintMarker(mapid,pos,markerIcon,contentString,nome,1,1,1,idlocation);
		  	MDBGlobaltipo="locations";
			MDBGlobalID=idlocation;
		  }
	
	function showMarkerByID(mapid,id){	
		try{maps[mapid].myMDBActiveWindow.close();}catch(e){}	
		maps[mapid].myMDBActiveMarker=maps[mapid].MDBmarkers[id];
		
		for(j=0;j<maps[mapid].MDBmarkers.length;j++){
			if(maps[mapid].MDBmarkers[j].MYinfoWidow[j].id==id){
			
					maps[mapid].myMDBActiveWindow=maps[mapid].MDBmarkers[j].MYinfoWidow[j].window;
					maps[mapid].MDBmarkers[j].MYinfoWidow[j].window.open(maps[mapid],maps[mapid].MDBmarkers[j]);			
				
				}
			}
		}  

	function initialize() {
			  
		var myLatlng = new google.maps.LatLng(45.4712536, 9.1670580999999629);			

		google.maps.Map.prototype.MDBmarkers = new Array();		
		google.maps.Map.prototype.MDBdirections = new Array();
		google.maps.Map.prototype.MDBActiveMarker = new google.maps.Marker();
		google.maps.Map.prototype.MDBActiveWindow = new google.maps.InfoWindow();
		google.maps.Map.prototype.mydirectionsService = new google.maps.DirectionsService();
		google.maps.Map.prototype.mydirectionsDisplay = new google.maps.DirectionsRenderer();
		google.maps.Map.prototype.dintorni=0;
		
		google.maps.Marker.prototype.MYinfoWidow = new Array();

		google.maps.Map.prototype.clearMarkers = function() {
			for(var i=0; i < this.MDBmarkers.length; i++){
				this.MDBmarkers[i].setMap(null);
			}
		};
		
		google.maps.Map.prototype.mylatlngbounds = new google.maps.LatLngBounds();
	
		google.maps.Map.prototype.clearDirections = function() {
			for(var i=0; i < this.MDBdirections.length; i++){
				this.MDBdirections[i].setMap(null);
			}
		};

		$('.gMaps').each(function(){
			mapid=this.id;
			
			opzioni=getMyMap(mapid);
	
			//try{
			var myOptions = {
			  zoom: parseInt((typeof(getOption(opzioni,"MDBdefZooom"))=='undefined' || getOption(opzioni,"MDBdefZooom")=='') ? 16 : getOption(opzioni,"MDBdefZooom")),
			  center: myLatlng,
			  mapTypeId: google.maps.MapTypeId.ROADMAP,
			  disableDefaultUI: true,
			  streetViewControl:getOption(opzioni,"MDBIcons_Street"),
			  mapTypeControl:getOption(opzioni,"MDBIcons_SatTerr"),
			  zoomControl:getOption(opzioni,"MDBIcons_Zoom"),
			  rotateControl:getOption(opzioni,"MDBIcons_Pan"),
			  scrollwheel:getOption(opzioni,"MDBScrollable"),
			  draggable:getOption(opzioni,"MDBDraggable")
			}				
			map = new google.maps.Map(document.getElementById(mapid), myOptions);
			maps[mapid]=map;
			//}catch(e){}
		if(typeof(initFunctions)!="undefined" && initFunctions.length>0){
			for(i=0;i<initFunctions.length;i++){
				initFunctions[i]();
			}
		}
		});
		
		/*if(dintorni==1){
			enableAround();
			window.setTimeout('loadData()',1000);
			}*/
	  }

	  
	  /*function storeData(sezione,id,html){		  	  
		  $.ajax({
			  url:'/controllo/ros/ajax/mappe/ajaxTools.asp',
			  type:'POST',
			  data:'action=storedata&sezione=' + sezione + '&id=' + id +'&data=' + ((typeof(html)=="undefined") ? escape($('#map_results').html()) : escape(html))
			  });
		   }*/
	  
	  function enableAround(mapid,shownow){
		  google.maps.event.addListener(maps[mapid], 'dragend', function(event) { 
		  	  maps[mapid].clearMarkers();		  
			  delete maps[mapid].mylatlngbounds;
		  	  maps[mapid].mylatlngbounds=new google.maps.LatLngBounds();			  
			  loadData(); 
			});
		if(typeof(shownow)!="undefined"){
		  maps[mapid].clearMarkers();
		  delete maps[mapid].mylatlngbounds;
		  maps[mapid].mylatlngbounds=new google.maps.LatLngBounds();			  
		  loadData(); 			
		  }
	   }
		  
	  function loadData(mapid,store,nomap){
		  
		  if(typeof(maps[mapid].mylatlngbounds)=='undefined' || maps[mapid].mylatlngbounds.isEmpty()){
			  if(maps[mapid].getBounds()==null){
				  window.setTimeout('loadData()',1000);
				  return false
				  }
			  maps[mapid].mylatlngbounds=map.getBounds();
			  }
		  
		  if($('#map_results').length>0){tipo='html';}
		  else{tipo='script';}
		  
		  $.ajax({
			  url:'/controllo/ros/ajax/mappe/ajaxTools.asp?action=geocodeAddressesAround&ne='+ maps[mapid].mylatlngbounds.getNorthEast() + '&sw=' + maps[mapid].mylatlngbounds.getSouthWest() + '&pos=' + maps[mapid].getCenter() +  '&idcat=' +(( typeof(idcat)=='undefined')?'':idcat) + '&nomap=' +(( typeof(nomap)=='undefined')?'':nomap),
			  dataType:tipo,
			  complete:function(resp){
				  if($('#map_results').length>0){
					  delete maps[mapid].mylatlngbounds;
		  			  maps[mapid].mylatlngbounds=new google.maps.LatLngBounds();
					  //map.clearMarkers();
					  $('#map_results').html(resp.responseText);
					  if(typeof(store)!="undefined"){
						  storeData(mapid,MDBGlobaltipo,MDBGlobalID);	
						  }
					  }
				  }			  
			  });
		  }
	  

	  function loadScript() {
		if($('.gMaps').length>0){
			var script = document.createElement("script");
			script.type = "text/javascript";
			
			script.src = "http://maps.google.com/maps/api/js?sensor=false&language=it&callback=initialize&key=AIzaSyDHARkB0qjvzfxSRL5uLIQQtcGCxS2nsd0 ";
			document.body.appendChild(script);
		}		
	  }

	  
