var geocoder;

var markersArray = [];
var infosArray = [];
var ret ='';

var directionDisplay;
var directionsService = new google.maps.DirectionsService();


var origin = null;
var destination = null;

						
function initialize() {
	  geocoder = new google.maps.Geocoder();
	  geocoder.firstItem = {};
	  directionsDisplay = new google.maps.DirectionsRenderer();
	  var latlng = new google.maps.LatLng(41.8954656, 12.4823243); //rome
	  var myOptions = {
	    zoom: 6,
	    center: latlng,
	    mapTypeId: google.maps.MapTypeId.ROADMAP
	  }
	  map = new google.maps.Map(document.getElementById('map'), myOptions);
	  directionsDisplay.setMap(map);
	  directionsDisplay.setPanel(document.getElementById("directionsPanel"));
	  return map;
}
 
function centerMap(){
		var bound = new google.maps.LatLngBounds();

		//marker.setMap(map);
		//dist(); 
		 if(markersArray.length>=1){
		
		  
		  i = 0;
		  for (i=0;i<markersArray.length;i++)
		  {
		  		var tempcoords = markersArray[i].getPosition();
	    	bound.extend(tempcoords);
	    	map.fitBounds(bound);
		  	
		  }
		
		
		 } 
}

function gozoom(num){
	map.setZoom(parseInt(num));
}

function gotype(num){
	map.setMapTypeId(eval("google.maps.MapTypeId."+num));
}



function geocodePosition(pos) {
	
	  geocoder.geocode({
	    latLng: pos
	  }, function(responses) {
	    if (responses && responses.length > 0) {
	      ret = responses[0].formatted_address;
	    } else {
	      ret = "Cannot determine address at this location.";
	    }
	  });
	  return ret;
}

 function toLatLng(lat,lon){
		latLang = new google.maps.LatLng(lat,lon);
		return  latLang;
 }
  
function deleteOverlays() {
	  if (markersArray) {
	    for (i in markersArray) {
	      markersArray[i].setMap(null);
	    }
	    markersArray.length = 0;
	  }
}
//Removes the overlays from the map, but keeps them in the array
function clearOverlays() {
    if (markersArray) {
      for (i in markersArray) {
        markersArray[i].setMap(null);
      }
    }
}
function save_point(){
	for (i in markersArray) {

    }
}

function clearIcon(){
	for (i in markersArray) {
    	markersArray[i].setIcon();
    }
}

function clearInfos(){
	
	for (i in infosArray) {
    	infosArray[i].close();
    }
    
}
  // Shows any overlays currently in the array
  function showOverlays() {
    if (markersArray) {
      for (i in markersArray) {
        markersArray[i].setMap(map);
      }
    }
  }

  // Deletes all markers in the array by removing references to them
  function deleteOverlays() {
    if (markersArray) {
      for (i in markersArray) {
        markersArray[i].setMap(null);
      }
      markersArray.length = 0;
    }
  }

function createMarker(name, latlng,txt,icon) {
	//map.setZoom(16);
	draggabile = false;
	if(icon)
		icona = icon;
	else
		icona='';
	ombra='';
	var marker = new google.maps.Marker({
		map: map,
		draggable: draggabile,
		position:latlng,
		title:name,
		icon:icona,
		shadow:ombra
	});
	markersArray.push(marker);
	google.maps.event.addListener(marker, 'click', function() {
		clearInfos();
	    clearIcon();
	    var infowindow = new google.maps.InfoWindow({
	        content: txt
	    });
		infowindow.setPosition(marker.getPosition());
//		infowindow.setContent(txt);
		infowindow.open(map);
		//Create our 'tiny' marker icon
		blueIcon = 'http://maps.google.com/mapfiles/ms/micons/blue-pushpin.png';	                
		//Set up our GMarkerOptions object
		//marker.setIcon(blueIcon);
		//marker.setDraggable(true);		
		infosArray.push(infowindow);
		destination = marker.getPosition();
	});
//	google.maps.event.addListener(marker, 'dragend', function() {
//		clearInfos();
//	    updateMarkerStatus('Drag ended');
//	    geocodePosition(marker.getPosition());
//	  });
}
 
function calcRoute() {
	clearInfos();
	var mode;
    switch ($("#mapp0_directions .selected").attr("id")) {
      case "bicycling":
        mode = google.maps.DirectionsTravelMode.BICYCLING;
        break;
      case "driving":
        mode = google.maps.DirectionsTravelMode.DRIVING;
        break;
      case "walking":
        mode = google.maps.DirectionsTravelMode.WALKING;
        break;
    }

    var start = document.getElementById("mapp0_saddr").value;
    var end = document.getElementById("mapp0_daddr").value;
    var request = {
        origin:start, 
        destination:end,
        travelMode: mode
    };
    directionsService.route(request, function(response, status) {
      if (status == google.maps.DirectionsStatus.OK) {
        directionsDisplay.setDirections(response);
      }
    });
}



function printDirections(target){
	html = '';	
	html += '<div class="mapp-directions" id="mapp0_directions" style="display: block;">';
	html += '<div class="map_buttons"><span id="driving" title="By car" class="mapp-car-button mapp-travelmode selected"></span>';
	html += '<span id="walking" title="Walking" class="mapp-walk-button mapp-travelmode" ></span>';
	html += '<span id="bicycling" title="Bicycling" class="mapp-bike-button mapp-travelmode"></span></div>';
	html += '<div class="map_start"><span title="Start" class="mapp-a"></span>';
	html += '<input type="text" value="" id="mapp0_saddr" class="mapp-address-error">';
	html += '<span title="Swap start and end" id="mapp0_addrswap" class="mapp-swap"></span></div>';
	html += '<div class="map_end"><span class="mapp-address-corrected" id="mapp0_saddr_corrected">Enter address</span>';
	html += '<span title="End" class="mapp-b"></span></td><td><input type="hidden" value="" id="mapp0_daddr">';
	html += '<span class="mapp-address-corrected" id="mapp0_daddr_corrected"></span>';
	html += '<input type="submit" id="mapp0_get_directions" value="Get Directions" onclick="calcRoute()"></div>';
	
	targetObj = document.getElementById(target);
	targetObj.innerHTML = html;
	$("#mapp0_daddr").val(destination);
	$("#mapp0_saddr").autocomplete({
	      //This bit uses the geocoder to fetch address values
	      source: function(request, response) {
	        geocoder.geocode( {'address': request.term }, function(results, status) {
	          response($.map(results, function(item) {
	            return {
	              label:  item.formatted_address,
	              value: item.formatted_address,
	              latitude: item.geometry.location.lat(),
	              longitude: item.geometry.location.lng()
	            }
	          }));
	        });
	      }
	    });
	$('.mapp-travelmode').click( function(){
		$('.mapp-travelmode').removeClass("selected");
		$(this).addClass("selected");
		calcRoute();
	});
}
function updateMode() {
    if (directionsVisible) {
      calcRoute();
    }
}



	  
