var posicoes = new Array();
var directions;

function nav(id, praia_lat, praia_lon) {
	var local_lat = posicoes[id][document.getElementById("sel_" + id).selectedIndex][0];
	var local_lon = posicoes[id][document.getElementById("sel_" + id).selectedIndex][1];
	
	directions = new GDirections();
	directions.load("from: " + praia_lat + ","+ praia_lon + " to: " + local_lat + "," + local_lon);
	
	$("#link_" + id).attr("href", "http://maps.google.com.br/maps?saddr="+local_lat+","+local_lon+"&daddr="+praia_lat+","+praia_lon+"&hl=pt-BR"); 
	
	GEvent.addListener(directions, "load" , function() {                 
		document.getElementById("span_" + id).innerHTML = Math.round(directions.getDistance().meters/1000) + " km" ;
   	});  
}

function inicial(id, praia_lat, praia_lon) {
	var local_lat = posicoes[id][0][0];
	var local_lon = posicoes[id][0][1];
	
	directions = new GDirections();
	directions.load("from: " + praia_lat + ","+ praia_lon + " to: " + local_lat + ","+ local_lon);
	
	GEvent.addListener(directions, "load" , function() {   
		$("#link_" + id).attr("href", "http://maps.google.com.br/maps?saddr="+local_lat+","+local_lon+"&daddr="+praia_lat+","+praia_lon+"&hl=pt-BR");               
		document.getElementById("span_" + id).innerHTML = Math.round(directions.getDistance().meters/1000) + " km" ;
   	});  
}


function initialize() {

    if (GBrowserIsCompatible()) {  
      // arrays to hold copies of the markers used by the side_bar
      // because the function closure trick doesnt work there
      var gmarkers = [];
	   var map;
      // A function to create the marker and set up the event window
	  
      function createMarker(point,name,html,img,cidade, estado, width, height, locais, id) {
		var geourlIcon = new GIcon(G_DEFAULT_ICON);
		geourlIcon.image = img;
		curWidth = parseInt(width);
		curHeight = parseInt(height);
		geourlIcon.iconSize = new GSize(curWidth, curHeight);
		//geourlIcon.shadowSize = new GSize(22, 20);
		geourlIcon.iconAnchor = new GPoint((curWidth / 2),curHeight);
		geourlIcon.infoWindowAnchor = new GPoint((curWidth / 2), 1);
		geourlIcon.imageMap = [0,0, curWidth,0, curWidth,curHeight, 0,curHeight];
        
		var marker = new GMarker(point,geourlIcon);
		
		var pagina = "<div class='title'>&nbsp;&nbsp;" + name + "</div>"+
			"<div class='section2'><b>&nbsp;&nbsp;" + cidade + "<br>&nbsp;&nbsp;" + estado + "</b></div>"+
			"<div class='section1'><p>" + html + "</p></div>"+
			"<div class='section1'><FORM NAME='form_"+ id + "'><p>Distância de <SELECT id='sel_" + id + "' name='sel_" + id + "'  onChange='nav(" + id + ", " + point.y + ", " + point.x + ")'>";
			
		for (var i = 0; i < locais.length; i++) {
			pagina += "<OPTION VALUE='" + id + "_" + i + "'>" + locais[i] + "</option>";
		}
		
		pagina += "</SELECT> é igual à: <b><SPAN ID='span_" + id + "'></span></b></p></FORM></div>";
		pagina += "<div class='section1'><p><a href='#' target='_blank' id='link_" + id + "' class='a_dois'>Veja como Chegar!</a></p></div>";
		
		GEvent.addListener(marker, "click", function() {
			inicial(id, point.y , point.x);
			marker.openExtInfoWindow(
				map, 
				"custom_info_window_red",
				pagina,
				  {beakOffset: 3, paddingY: 20, paddingX: 20}
			); 
		});
	
		
		
        // save the info we need to use later for the side_bar
        gmarkers.push(marker);
        // add a line to the side_bar html
		//inicial(id, point.y, point.x);
        return marker;
      }

      // This function picks up the click and opens the corresponding info window
   

      // create the map
	  
      map = new GMap2(document.getElementById("map_canvas"));
	  map.enableScrollWheelZoom();
      map.addControl(new GLargeMapControl());
      map.addControl(new GMapTypeControl());
      map.setCenter(new GLatLng(-13.154376,-47.197266), 4);

      // Read the data from example.xml
      GDownloadUrl("xml/praias4.xml", function(doc) {
        var xmlDoc = GXml.parse(doc);
        var markers = xmlDoc.documentElement.getElementsByTagName("praia");
 
        for (var i = 0; i < markers.length; i++) {
          // obtain the attribues of each marker		
			var lat = parseFloat(markers[i].getElementsByTagName("lat")[0].childNodes[0].nodeValue);
			var lng = parseFloat(markers[i].getElementsByTagName("lon")[0].childNodes[0].nodeValue);
			var html = markers[i].getElementsByTagName("texto")[0].childNodes[0].nodeValue;
			var label = markers[i].getElementsByTagName("nome")[0].childNodes[0].nodeValue;
			var img = markers[i].getElementsByTagName("icone")[0].childNodes[0].nodeValue;
			var cidade = markers[i].getElementsByTagName("cidade")[0].childNodes[0].nodeValue;
			var estado = markers[i].getElementsByTagName("estado")[0].childNodes[0].nodeValue;
			var curHeight = markers[i].getElementsByTagName("iconeh")[0].childNodes[0].nodeValue;
			var curWidth = markers[i].getElementsByTagName("iconew")[0].childNodes[0].nodeValue;
			var dist = markers[i].getElementsByTagName("local");
			
			posicoes[i] = new Array();
			var locais = new Array();
			
			for (j=0; j<dist.length; j++)
			{
				posicoes[i][j] = new Array();
				posicoes[i][j][0] = dist[j].getAttribute("llat");
				posicoes[i][j][1] = dist[j].getAttribute("llon");
				locais[j] = dist[j].childNodes[0].nodeValue;
			}
		  		  
			var point = new GLatLng(lat,lng);
			// create the marker
			var marker = createMarker(point,label,html, img,cidade, estado, curWidth, curHeight, locais, i);
			map.addOverlay(marker);
        }
      });
    }

    else {
      alert("Sorry, the Google Maps API is not compatible with this browser");
    }
	
	
	$("#map_itens").load("includes/carrega_praias.php",function(responseText, textStatus, XMLHttpRequest){
        $("#map_itens > li > a").click(
			function(){
				//var myLatlng = new google.maps.LatLng($(this).attr('lat'),$(this).attr('lon'));
				//map.setCenter(myLatlng);			
				map.setZoom(12);
				GEvent.trigger(gmarkers[$(this).attr('index')], "click");
				
		});
		
		jQuery('#map_itens').jcarousel({ 
			vertical: true,
            scroll: 2,
            visible: 7,
            start: 1,
            wrap: 'last',
			initCallback: map_itens_initCallback
		}); 
    });
	
}
  
function map_itens_initCallback(carousel)
{
    // Disable autoscrolling if the user clicks the prev or next button.

    carousel.buttonNext.bind('click', function() {
        carousel.startAuto(0);
    });

    carousel.buttonPrev.bind('click', function() {
        carousel.startAuto(0);
    });

    // Pause autoscrolling if the user moves with the cursor over the clip.
    carousel.clip.hover(function() {
        carousel.stopAuto();
    }, function() {
        carousel.startAuto();
    });
};

