var map;
var geocoder;

function initialize() {
	

	if ($("#map_canvas").length){
	
	    var latlng = new google.maps.LatLng(42.634611,8.937639);
	    var myOptions = {
	      zoom: 12,
	      center: latlng,
	      mapTypeId: google.maps.MapTypeId.ROADMAP
	    };
	    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
	        
	     var marker = new google.maps.Marker({
		      position: latlng,
		      title:"Ile Rousse"
		  });
		  
		  // To add the marker to the map, call setMap();
		  marker.setMap(map);
	  }
}



	  
function var_dump(obj) {
	   if(typeof obj == "object") {
	      return "Type: "+typeof(obj)+((obj.constructor) ? "\nConstructor: "+obj.constructor : "")+"\nValue: " + obj;
	   } else {
	      return "Type: "+typeof(obj)+"\nValue: "+obj;
	   }
	}
  

function showMap(typee, dataa, zoom, addMarker ,tableau) { // typee : 0 = regions / 1 = adresse / 2 = coordonnées / 3 = itinéraire
			
	
	
		if (typee == 1) {
			geocoder = new google.maps.Geocoder();					
		}		
		if (typee == 3) {
			$$("roadmap").innerHTML = "";
			itin($$("address1").value, $$("address2").value, map);
			if (addMarker) {
				markers(typee, map, new Array(0, 0));
			}
			return 1;
		}
		
		if (geocoder) { //retourne les coordonnées en fonction de l'adresse et affiche la carte
			geocoder.geocode( { 'address': dataa}, function(results, status) {
				if (status == google.maps.GeocoderStatus.OK) {
			        map.setCenter(results[0].geometry.location);
			        var marker = new google.maps.Marker({
			            map: map, 
			            position: results[0].geometry.location
			        });
			        latlng = results[0].geometry.location;
			        latlng[0]=latlng.lat();
			        latlng[1]= latlng.lng();
			        markers(typee, map, latlng,tableau);
				} 
		    });

		}  else { //affiche la carte avec les coordonnées fournies
			var point = new google.maps.LatLng(dataa[0], dataa[1]);
			var optionsPoints = {
		      zoom: 12,
		      zoomControl: true,
		      mapTypeControl: true,	      
		      center: point,
		      mapTypeId: google.maps.MapTypeId.ROADMAP
		    };
			map = new google.maps.Map(document.getElementById("map_canvas"), optionsPoints);
			var marker = new google.maps.Marker({
				map: map,
				position: point			      
			  });  
			markers(typee, map, dataa,tableau);
			
		}
	
}

	  
	  
/* ----------------------------------- */
/* --- itin : AFFICHE L'ITINERAIRE --- */
/* ----------------------------------- */
function itin(address1, address2, map) {
	
	
	var directionsService = new google.maps.DirectionsService();

	var directionsDisplay = new google.maps.DirectionsRenderer();
	directionsDisplay.setMap(map);
	directionsDisplay.setPanel(document.getElementById("roadmap"));
  
	var start = address1;
	var end = address2;
	var request = {
	    origin:start, 
	    destination:end,
	    travelMode: google.maps.DirectionsTravelMode.DRIVING
	  };
	  directionsService.route(request, function(response, status) {
	    if (status == google.maps.DirectionsStatus.OK) {
	      directionsDisplay.setDirections(response);
	    }
	  });

}


/* ------------------------------------- */
/* --- $$ : RACCOURCI GETELEMENTBYID --- */
/* ------------------------------------- */
function $$(element) {
	return document.getElementById(element);
}
/* ----------------------------------------------------------- */
/* --- checkFields :                                       --- */
/* --- checkFields2 : VERIFI SI LES CHAMPS SONT RENSEIGNES --- */
/* ----------------------------------------------------------- */
function checkFields(typee, field) {
	if (field == "") {
		alert("Le champs est vide... ");
		return false;
	}
	else {
		if (typee == '1') showMap(1, field, 15, 1);
		if (typee == '0' && field != '1') showMap(0, field, 9, 1) ;
        if (typee == '0' && field == '1') showMap(0, field, 8, 1) ;
        if (typee == '2') showMap(2, field, 12, 1);
	}
}

function checkFields2(field, field2) {
	if (field == "" || field2 == "") {
		alert("Veuillez remplir les deux champs!");
		return false;
	}
	else {
		showMap(3, '', 8, 1);
	}
}

/* ------------------------------------------------------------------------------ */
/* --- markers : OBTIENT ET ANALYSE LE XML ET PLACE LES MARKEURS SUR LA CARTE --- */
/* ------------------------------------------------------------------------------ */
function markers(typee, map, dataa, tableau) {
	
	
	$("#loadingAJAX").innerHTML = "<br /><img src='/design/atc/images/pictos/gmap/loading.gif' />";
	
	/*
	if ($$("accommodations").checked==true){
		var accommodations=$$("accommodations").value;
	} else {
		var accommodations=0;
	}
	if ($$("todoTopractice").checked==true){
		var todoTopractice=$$("todoTopractice").value;
	} else {
		var todoTopractice=0;
	}
	if ($$("taste").checked==true){
		var taste=$$("taste").value;
	} else {
		var taste=0;
	}*/
	

	$.post("/atc_user/layout/set/xml/infotour/rechercheCarto_ajax", {
		Recherche: "Recherche",
		accommodations: $$("accommodations").value,
		todoTopractice: $$("todoTopractice").value,
		taste: $$("taste").value,
		lat: dataa[0],
		lng: dataa[1],
		typee: typee,
        tenpoints: ""+tableau
	}, function(xml) {
		var item = new Array();
		var i = 1;
		$("item", xml).each(function(i) {
			
 
		    if ($(this).attr("description"))
				desc = $(this).attr("description") + "<br />";
			desc = truncateString(desc);
			
			var contentString = "<div id='mapinfos'><strong>" + $(this).attr("nom") + "</strong><br /><div style='width: 350px;'>" + desc + "</div><a href='" + "/infotour/" + $(this).attr("chemin_detail") + "/id/" + $(this).attr("id_infotour") + "'>&gt; + d\'infos</a></div>" ;
			
			var infowindow = new google.maps.InfoWindow({
			    content: contentString
			});
			
			var cheminshadow = 'http://www.ot-ile-rousse.fr/design/atc/images/pictos/gmap/ombre.png';
			
			
			switch ($(this).attr("type_objet").substr(0, 1)) {
				case "1":
					var cheminimage = 'http://www.ot-ile-rousse.fr/design/atc/images/pictos/gmap/se-loger.png';
				break;
				case "2":
					var cheminimage = 'http://www.ot-ile-rousse.fr/design/atc/images/pictos/gmap/faire-pratiquer.png';
				break;
				case "6":
					var cheminimage = 'http://www.ot-ile-rousse.fr/design/atc/images/pictos/gmap/deguster.png';
				break;
				default :
					var cheminimage = 'http://www.ot-ile-rousse.fr/design/atc/images/pictos/gmap/gm_center.png';
					var cheminshadow = 'http://www.ot-ile-rousse.fr/design/atc/images/pictos/gmap/gm_center_s.png';
			}

			var image = new google.maps.MarkerImage(cheminimage,
				      new google.maps.Size(33, 40),
				      new google.maps.Point(0,0),
				      new google.maps.Point(16, 40));
			var shadow = new google.maps.MarkerImage(cheminshadow,
				      new google.maps.Size(33, 40),
				      new google.maps.Point(0,0),
				      new google.maps.Point(16, 40));
			var point = new google.maps.LatLng($(this).attr("latitude"), $(this).attr("longitude"));
			var marker = new google.maps.Marker({
			      position: point,
			      map: map,
			      icon: image,
			      shadow: shadow
			  });
			google.maps.event.addListener(marker, 'click', function() {
				  infowindow.open(map,marker);
				});
			  
			
			i++;
		});
		
		$("#loadingAJAX").innerHTML = "";
	}, "xml");
}
/* ----------------------------------------------------------------------------------------------- */
/* --- truncateString : RACCOURCISSEMENT D'UNE CHAINE                                          --- */
/* ----------------------------------------------------------------------------------------------- */
function truncateString(chaine) {
    var maxLength = 500; // en nb de caracteres
    var end = maxLength;
    if(chaine != null && chaine.length > maxLength) {
        while(chaine.substr(end,1) != " " && end < chaine.length) {
            end +=1;
        }
        return chaine.substr(0,end)+"...";
    } else {
        return chaine;
    }
}


/* ------------------------------------------------------------------------------ */
/* --- display_10 : affiche les 10 resultats de la recherche sur la carte --- */
/* ------------------------------------------------------------------------------ */
function showtenPoints() {
    var tableau=new Array();
    $('p.nom a').each(function(){
        tableau.push(this.href);
    });
    showMap(1,'', 8, 1,tableau);
}



/* ----------------------------------- */
/* --- itinLatLong : renvoie les coordonnÃ©es d'un point pour itinÃ©raire --- */
/* ----------------------------------- */
function itinLatLong(lat,long,champ) {
	$$("address"+champ).value=lat+","+long;
}

/* -------------------------------- */
/* --- showMap : AFFICHE LA MAP --- */
/* -------------------------------- */


