var geocoder;
var map;
var fleetArray =[];
var freightArray = [];
var directionsArray =[];
var directionsMarkersArray =[];
var myInfoWindow;
 


function initialize()
{
    var latlng = new google.maps.LatLng(41.34,12.50);
    var options = {
		zoom: 6,
		center: latlng,
		maxZoom:14,
		minZoom:4,
		streetViewControl: false,
		mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById("ggmap"), options);
	geocoder = new google.maps.Geocoder();
	  
}	  

function showAddress (campo)
{  var comp; 
   var actype =''; var actext=''; var acdetail='';
   var street_number='';
   var route='';
   var sublocality='';
   var locality='';
   var administrative_area_level_2='';
   var administrative_area_level_1='';
   var country='';
   var postal_code='';
   var address_type='';
  
   var indiri = document.getElementById(campo+'_frazione').value;
   if (indiri!=''){ 
	   geocoder.geocode( {'address': indiri}, function(results,status) {
			if (status == google.maps.GeocoderStatus.OK) {
			   if (results.length>0)
			   {  address_type=results[0].types[0];
			   
			      for (comp in results[0].address_components)
			      {  actype=results[0].address_components[comp].types[0];
				     actext=results[0].address_components[comp].long_name;
				     if (actype=='street_number')
					 { street_number=actext; }
					 else if (actype=='route')
					 { route=actext;}
					 else if (actype=='sublocality')
					 { sublocality=actext;}
					 else if (actype=='locality')
					 { locality=actext;}
					 else if (actype=='administrative_area_level_2')
					 { administrative_area_level_2=actext;}
					 else if (actype=='administrative_area_level_1')
					 { administrative_area_level_1=actext;}
					 else if (actype=='country')
					 { country=actext;}
					 else if (actype=='postal_code')
					 { postal_code=actext;}
                  }
				 
				  if (route!='')
			      { acdetail=route;
				    if (street_number!='')
					{acdetail=acdetail+' '+street_number;}
					acdetail=acdetail+', ';
				  }
				  if (postal_code!='')
			      { acdetail=acdetail+postal_code+' ';
				    document.getElementById(campo+'_cap').value=postal_code;
				  }
				  if (sublocality!='')
			      { acdetail=acdetail+sublocality+' '; }
				  if (locality!='')
			      { acdetail=acdetail+locality+', '; }
				  else if (administrative_area_level_2!='')
			      { acdetail=acdetail+administrative_area_level_2+', '; }
				  else if (administrative_area_level_1!='' && administrative_area_level_2!=administrative_area_level_1 )
			      { acdetail=acdetail+administrative_area_level_1+', '; }
				  
				  if (country!='')
			      { acdetail=acdetail+country+' '; }
				 
                  document.getElementById(campo+'_frazione').value=acdetail;

				  if (locality!='')
			      { document.getElementById(campo).value=locality; }
				  else if (administrative_area_level_2!='')
				  { document.getElementById(campo).value=administrative_area_level_2;}
				  else if (administrative_area_level_1!='')
				  { document.getElementById(campo).value=administrative_area_level_1;}
				  else
				  { document.getElementById(campo).value=country; }
				  
			      document.getElementById(campo+'_lat').value=results[0].geometry.location.lat();
				  document.getElementById(campo+'_lon').value=results[0].geometry.location.lng();
				  if (document.getElementById(campo+'_type'))
				  { 
				    document.getElementById(campo+'_type').value=address_type; 
					if (address_type=='route' || address_type=='sublocality' || address_type=='street_address' )
		            { jQuery("#"+campo+"_ok").val('OK');		}
					else
					{ jQuery("#"+campo+"_ok").val('');		}
				  }
				  clearDirections();
			      var marker = new google.maps.Marker({position: results[0].geometry.location, map: map}); 
				  directionsMarkersArray.push(marker);
                  map.setCenter(results[0].geometry.location);
	              map.setZoom(10);
				  
               }				
			 /*  else
			   { alert ("Attezione localita non univoca, si prega di specificarla seguendo i suggerimenti");
			     document.getElementById(campo).value='';
			    } */
			} else {
				alert("Problema nella ricerca dell'indirizzo: " + status);
				document.getElementById(campo).value='';
			}
		});
   }		
}


function showLocality (campo)
{  var indiri = document.getElementById(campo).value;
   if (indiri!=''){ 
	   geocoder.geocode( {'address': indiri}, function(results,status) {
			if (status == google.maps.GeocoderStatus.OK) {
			   if (results.length>0)
			   {  document.getElementById(campo).value=results[0].address_components[0].long_name;
			      document.getElementById(campo+'_lat').value=results[0].geometry.location.lat();
				  document.getElementById(campo+'_lon').value=results[0].geometry.location.lng();
				  clearDirections();
			      var marker = new google.maps.Marker({position: results[0].geometry.location, map: map}); 
				  directionsMarkersArray.push(marker);
                  map.setCenter(results[0].geometry.location);
	              map.setZoom(10);
				  
               }				
			 /*  else
			   { alert ("Attezione localita non univoca, si prega di specificarla seguendo i suggerimenti");
			     document.getElementById(campo).value='';
			    } */
			} else {
				alert("Problema nella ricerca dell'indirizzo: " + status);
				document.getElementById(campo).value='';
			}
		});
   }		
}


function adddirections(plat,plon,alat,alon)
{   
    var infowindow = new google.maps.InfoWindow();
	
    var directionsService = new google.maps.DirectionsService();
	var options = {
		suppressMarkers: true,
		suppressInfoWindows: true
    };
	var directionsDisplay = new google.maps.DirectionsRenderer(options);
	var origin = new google.maps.LatLng(plat,plon);
	var destination = new google.maps.LatLng(alat,alon);
	var mode = mode = google.maps.DirectionsTravelMode.DRIVING;
	var request = {
        origin: origin,
        destination: destination,
        travelMode: mode
		};
		
	directionsService.route(request, function(response, status) {
      if (status == google.maps.DirectionsStatus.OK) {
        directionsDisplay.setDirections(response);

		clearDirections();
		directionsArray.push(directionsDisplay);
		directionsDisplay.setMap(map);
		
		var lastpoint = response.routes[0].overview_path[response.routes[0].overview_path.length-1];
		var distance = response.routes[0].legs[0].distance.text;
        var duration = response.routes[0].legs[0].duration.text;
		var marker = new google.maps.Marker({
            position: lastpoint
        });
		
		google.maps.event.addListener(marker, 'click', function() {
           infowindow.setContent(" distanza: "+distance+"<br> tempo: "+duration+" ");
           infowindow.open(map,this);
        });
		// marker.setMap(map);  
		directionsMarkersArray.push(marker);
		marker.setMap(map);
		
		
		
      } else { alert ('error'); 
	  }
    });
    
}

function addfreight(glat,glon,icona,alias)
{       
        var infowindow = new google.maps.InfoWindow();
        var myLatlng = new google.maps.LatLng(glat, glon);
	    var image = new google.maps.MarkerImage(icona);
		var marker = new google.maps.Marker({
            position: myLatlng,
			animation: google.maps.Animation.DROP,
            title:alias,
			icon:image
        });
		
		google.maps.event.addListener(marker, 'click', function() {
           infowindow.setContent("<strong>" + alias + "</strong>");
           infowindow.open(map,this);
        });
		// marker.setMap(map);  
		 freightArray.push(marker);
		 
		
}  

function load_content(marker,tipo, id){
  jQuery.ajax({
    url: '/trace/ajax_content.php?tipo='+tipo+'&id=' + id,
    success: function(data){
      infowindow.setContent(data);
      infowindow.open(map, marker);
    }
  });
}


function addtruck(glat,glon,icona,alias,id_mezzo)
{       
        var infowindow = new google.maps.InfoWindow();
        var myLatlng = new google.maps.LatLng(glat, glon);
	    var image = new google.maps.MarkerImage(icona);
		var marker = new google.maps.Marker({
            position: myLatlng,
			animation: google.maps.Animation.DROP,
            title:alias,
			icon:image
        });
		
	/*	google.maps.event.addListener(marker, 'click', function() {
           infowindow.close();
           load_content(marker,'vei',id_mezzo);
        }); */
		// marker.setMap(map);  
		 fleetArray.push(marker);
		 
		
}  


function popupInfoWindow(html, glat,glng) {
    if (myInfoWindow) { myInfoWindow.close(); }
    var cent=new google.maps.LatLng(glat, glng);
	
	myInfoWindow = new google.maps.InfoWindow({
          content: html,
          position: cent,
		  maxWidth:50,
		  pixelOffset: new google.maps.Size(-8, -12)

        });
    myInfoWindow.open(map);
	map.setCenter(cent);
}


function pubblishAllMarkers(freight,fleet,nofit) {
   var count;
   var bounds = new google.maps.LatLngBounds();
   if (freight) {
	  if (freightArray) {
		for (i in freightArray) {
		  freightArray[i].setMap(map);
		  count=count+1;
		  bounds.extend(freightArray[i].getPosition());
		}
	  }
   }
   if (fleet) {
	  if (fleetArray) {
		for (i in fleetArray) {
		  fleetArray[i].setMap(map);
		  count=count+1;
		  bounds.extend(fleetArray[i].getPosition());
		}
	  }
   }
   if (nofit!='no')
   { map.fitBounds(bounds);}
}


function clearDirections() {
  if (directionsArray) {
	for (i in directionsArray) {
	  directionsArray[i].setMap(null);
	}
  }
  directionsArray.length = 0;
  if (directionsMarkersArray) {
	for (i in directionsMarkersArray) {
	  directionsMarkersArray[i].setMap(null);
	}
  }
  directionsMarkersArray.length = 0;
}

function clearFleet() {
  if (fleetArray) {
	for (i in fleetArray) {
	  fleetArray[i].setMap(null);
	}
  }
  fleetArray.length = 0;
}

function clearFreights() {
  if (freightArray) {
	for (i in freightArray) {
	  freightArray[i].setMap(null);
	}
  }
  freightArray.length = 0;
}


function resizeMap(){
		var map_obj=document.getElementById("ggmap");
		var list_obj=document.getElementById("carichi");
		var list1_obj=document.getElementById("page");
		var dw = jQuery(document).width();
		var dh = jQuery(document).height()
		if (map_obj!=null)
		{
		  map_obj.style.width=(dw - 630)+"px";
		  map_obj.style.height=(dh - 35)+"px";
		}  
		if (list_obj!= null)
		{ 
		  list_obj.style.height=(dh - 65)+"px"; 
		}
		if (list1_obj!= null)
		{
		  list1_obj.style.height=(dh - 45)+"px";
		}
}

function resizeMapFlotta(){
		var map_obj=document.getElementById("ggmap");
		var car_obj=document.getElementById("carichi");
		var fleet_obj=document.getElementById("flotta");
		var page_obj=document.getElementById("page");
		var dw = jQuery(document).width();
		var dh = jQuery(document).height();
		if (map_obj!=null)
		{
		  map_obj.style.width=(dw - 630)+"px";
		  map_obj.style.height=(dh - 70)+"px";
		}  
		if (page_obj!= null)
		{
          page_obj.style.height=(dh - 70)+"px"; 
		}
		if (car_obj!= null)
		{ 
		  if (fleet_obj!= null)
		  {car_obj.style.height=(dh - 155)+"px"; }
		  else
		  {car_obj.style.height=(dh - 75)+"px";}
		}
		
}

function resizeMapTrasp(){
		var map_obj=document.getElementById("ggmap");
		var car_obj=document.getElementById("tabs-container");
		var fleet_obj=document.getElementById("flotta");
		
		var dw = jQuery(document).width();
		var dh = jQuery(document).height()
		if (map_obj!=null)
		{
		  map_obj.style.width=(dw - 630)+"px";
		  map_obj.style.height=(dh - 70)+"px";
		}  
		if (car_obj!= null)
		{ 
		  if (fleet_obj!= null)
		  {car_obj.style.height=(dh - 155)+"px"; }
		  else
		  {car_obj.style.height=(dh - 70)+"px";}
		}
		
}


