// JavaScript Document
var geocoder;
var map;
$(function(){
	geocoder = new google.maps.Geocoder();
	var	latlng = new google.maps.LatLng(46.95,1.85);
   	var myOptions = {zoom: 6,center: latlng,mapTypeId: google.maps.MapTypeId.ROADMAP,navigationControl: true,navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL,position: google.maps.ControlPosition.TOP_RIGHT},mapTypeControl: false,scaleControl: false,scrollwheel:false};
		map = new google.maps.Map(document.getElementById("map"), myOptions);
		setMarkers(map,$(".agence"));
	$("#findDepart .check").click(function(){var v=$("#findDepart .txt").val();if(v!='')geoCoding(v);})
	$("#findArrivee .check").click(function(){var v=$("#findArrivee .txt").val();if(v!='')geoCoding(v);})	   
})


function selectAgence(id){
		fd="#"+id;nom=$(fd).find(".name").text();
		
	if($("#depart:has('p.vide')")[0]){
		recupAgence(id.substr(6),"#depart address");
		html="<p>Au départ de "+nom+"<input id='codeDepart' name='codeDepart' value='"+id.substr(6)+"' type='hidden'/></p>";
		html+="<address class=\"vcard\">chargement en cours</address>";
		$("#depart").html(html);
		$("#arrivee p").toggleClass("B");
	}else{
		html="<p>Vers "+nom+"<input id='codeArrivee' name='codeArrivee' value='"+id.substr(6)+"' type='hidden'/></p>";
		html+="<address class=\"vcard\">chargement en cours</address>";
		$("#arrivee").html(html);
		self.location.href="choix-de-la-date-pour-une-location-utilitaire-de-agence-"+$("#codeDepart").val()+"-a-agence-"+$("#codeArrivee").val()+".html";
	}
	
	
}

function unSelectAgence(id){
		c="div [style*='picrouge.png']"
		$(c).remove()
		$("#depart").html("<p class=\"vide\">Cliquez sur l'agence la plus proche de votre point de départ.</p>");
		$("#findDepart .txt").removeClass("sel");
		$("#arrivee p").addClass("B");
		
}



function setMarkers(map,agence){
	var image = new google.maps.MarkerImage('design/fond/picbleu.png',new google.maps.Size(31, 27),new google.maps.Point(0,0),new google.maps.Point(16,27));
	
	
	agence.each(function(){
			coord=$(".location",this).val();
			coord=coord.split(',');
			
			var newCoord = new google.maps.LatLng(coord[0], coord[1]);
			var nomAgence=$(".name",this).text();
			var id=$(this).attr('id');
			
			
		 	var marker = new google.maps.Marker({clickable:true,position: newCoord,map: map,icon: image,title: nomAgence,flat:true,id:id});
		
			google.maps.event.addListener(marker, 'click', function() {
												
					this.setOptions({clickable:false,visible:false});
  					selectAgence(this.id);
					if($("#findDepart .txt.sel")[0]){
					$("#findArrivee .txt").addClass("sel").val(this.title);c="#"+this.id;
					}else{
					$("#findDepart .txt").addClass("sel").val(this.title);c="#"+this.id;
					}
					setMarkersRed(map,$(c));
				
			});
	})
	
}

function setMarkersRed(map,agence){
	
	
	var image2 = new google.maps.MarkerImage('design/fond/picrouge.png',new google.maps.Size(31, 27),new google.maps.Point(0,0),new google.maps.Point(16,27));
	
	agence.each(function(){
			coord=$(".location",this).val();
			coord=coord.split(',');
			
			var newCoord = new google.maps.LatLng(coord[0], coord[1]);
			var nomAgence=$(".name",this).text();
			var id=$(this).attr('id');
			
			
			
		 	var marker = new google.maps.Marker({clickable:true,position: newCoord,map: map,icon: image2,title: nomAgence,flat:true,id:id});
		
			google.maps.event.addListener(marker, 'click', function() {
																	
																	
							
					this.setOptions({clickable:false,visible:false});							
					unSelectAgence(marker.id);c="#"+this.id;setMarkers(map,agence);
					
				
			});
	})
	
}



function recupAgence(idVille,lacible){
	var lacible
	$.ajax({type: "GET",url: "ajax.php?action=detailAgence&codeVille="+idVille,success:function(xml){
			if($('pointlocation',xml)[0]){
				
				
				var html=	"<strong class=\"fn\" onclick=\"unSelectAgence()\">"+$('pointlocation',xml).attr('a1')+"</strong>";
					html+=	"<span class=\"adr\">"+$('pointlocation',xml).attr('a2')+" "+$('pointlocation',xml).attr('a3')+"</span>";
					html+=	"<span class=\"locality\">"+$('pointlocation',xml).attr('a4')+"</span>";
					//if($('pointlocation',xml).attr('tel')!=""){html+=	"<span class=\"tel\"><em class=\"type\">Tél.</em> "+$('pointlocation',xml).attr('tel')+"</span>";}
					//if($('pointlocation',xml).attr('tel')!=""){html+=	"<span class=\"tel\"><em class=\"type\">FAX</em> "+$('pointlocation',xml).attr('fax')+"</span>";}
					
				$(lacible).html(html);
				
			}
	}})
	
	
}



function geoCoding(nomVille){
	var cp = new Array("13000","69000","75000");
	var cp2 = new Array("13001","69001","75001");
	var nomVille2;
		//if(cp.indexOf(nomVille) > -1){
	if(jQuery.inArray(nomVille,cp) > -1){
		nomVille = cp2[cp.indexOf(nomVille)];
	}
	
	if (geocoder) {
      geocoder.geocode( { 'address': nomVille+", France"}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
 
		 	lonLat=results[0].geometry.location.toString().split(",")
			lat=lonLat[0].substr(1)
			lon=lonLat[1].substring(0,lonLat[1].length-1)
			$.ajax({type: "GET",url: "ajax.php?action=agenceplusproche&geolat="+lat+"&geolon="+lon,success:function(xml){
				if($('ville',xml)[0]){
			

					var htmlLi=""
																		
																													
																													
				$('ville',xml).each(function(i){
				   htmlLi+="<li id=\"v"+$(this).attr("codeville")+"\" class=\"a"+Number(i+1)+"\"><span class=\"proximite\">"+$(this).attr("proximite")+"km</span><span class=\"nomville\">"+$(this).attr("villep")+"</span><span>"+$(this).attr("adresse")+"</span></li>"
				})
				
				if($("#recherche ul")[0]){
					$("#recherche ul").remove();
				}
				   $("#recherche").prepend("<ul>"+htmlLi+"</ul>").find("li").click(function(){
													if($("#findArrivee .txt").val()==""){unSelectAgence();}
													
													selectAgence("agence"+$(this).attr("id").substr(1));
													obj="#agence"+$(this).attr("id").substr(1)
													 
													setMarkersRed(map,$(obj))
													 
													$("#recherche ul").remove();
													
													if($("#findDepart .txt").hasClass('sel')){
														$("#findArrivee .txt").addClass("sel").val($(".nomville",this).text())
													}else{
														$("#findDepart .txt").addClass("sel").val($(".nomville",this).text())
													}
					
					
					})
					
				
				}
			}})
	
         
        } else {
          alert("Nous n'avons pas trouvé la ville \nou le code postal demandé en France. \nMerci de vérifier sa validité");
        }
      });
    }

}
