
function afficherResultats(obj) {      // Construction des noeuds 

var tabResult = obj.responseXML.getElementsByTagName('resultat');
formulaire_auto = '';

var tabLatitude = new Array();
var tabLongitude = new Array();
var tabIdentifiant = new Array();

document.getElementById('listePointRetrait').innerHTML='';
		if (tabResult.length > 0) {           
		// On définit la hauteur de la liste en fonction du nombre de rsultats et de la hauteur de ligne
		var hauteur = tabResult.length * 22;
		       
				for (var i = 0; i < tabResult.length; i++) {                
				resultat = tabResult.item(i);                 
			
				tabLatitude[i]=resultat.getAttribute('latitude');
				tabLongitude[i]=resultat.getAttribute('longitude');
				tabIdentifiant[i]=resultat.getAttribute('identifiant');
				
				}  

			} 

//Coordonnees domicile
var tabDomicile = obj.responseXML.getElementsByTagName('domicile');
resultat_domicile = tabDomicile.item(0);  

document.getElementById('latOrigine').value = resultat_domicile.getAttribute('latitude');
document.getElementById('longOrigine').value = resultat_domicile.getAttribute('longitude');


//Centre de la carte
var tabOrigine = obj.responseXML.getElementsByTagName('origine');
resultat_origine = tabOrigine.item(0);  

calcul_dist(resultat_origine.getAttribute('latitude'),resultat_origine.getAttribute('longitude'),tabLatitude,tabLongitude,tabIdentifiant);

}


function afficherResultats2(obj) {  // Construction des noeuds 

var tabResult = obj.responseXML.getElementsByTagName('resultat');
formulaire_auto = '';

var tabLibelle = new Array();
var tabAdresse = new Array();
var tabAdresse2 = new Array();
var tabCP = new Array();
var tabCommune = new Array();
var tabLatitude = new Array();
var tabLongitude = new Array();
var tabPicto = new Array();
var tabDistance = new Array();
var tabMobred = new Array();
var tabIdentifiant= new Array();
var tabHoLundi= new Array();
var tabHoMardi= new Array();
var tabHoMercredi= new Array();
var tabHoJeudi= new Array();
var tabHoVendredi= new Array();
var tabHoSamedi= new Array();
var tabHoDimanche= new Array();


document.getElementById('listePointRetrait').innerHTML='';
		if (tabResult.length > 0) {           
		// On définit la hauteur de la liste en fonction du nombre de rsultats et de la hauteur de ligne
		var hauteur = tabResult.length * 22;
		       
				for (var i = 0; i < tabResult.length; i++) {                
				resultat = tabResult.item(i);                 
				
				
				tabCommune[i]=resultat.getAttribute('commune');
				tabLatitude[i]=resultat.getAttribute('latitude');
				tabLongitude[i]=resultat.getAttribute('longitude');
				tabPicto[i]=resultat.getAttribute('type_point');
				tabLibelle[i]=resultat.getAttribute('libelle');
				tabAdresse[i]=resultat.getAttribute('adr_num_lib');
				tabAdresse2[i]=resultat.getAttribute('adr_num_lib_2');
				tabCP[i]=resultat.getAttribute('code_postal');
				tabDistance[i]=resultat.getAttribute('distance');
				tabMobred[i]=resultat.getAttribute('mobilite_reduite');
				tabIdentifiant[i]=resultat.getAttribute('identifiant');
				tabHoLundi[i]=resultat.getAttribute('ho_lundi');
				tabHoMardi[i]=resultat.getAttribute('ho_mardi');
				tabHoMercredi[i]=resultat.getAttribute('ho_mercredi');
				tabHoJeudi[i]=resultat.getAttribute('ho_jeudi');
				tabHoVendredi[i]=resultat.getAttribute('ho_vendredi');
				tabHoSamedi[i]=resultat.getAttribute('ho_samedi');
				tabHoDimanche[i]=resultat.getAttribute('ho_dimanche');
				}  

			} 


//Centre de la carte
initialize(resultat_origine.getAttribute('latitude'),resultat_origine.getAttribute('longitude'),tabCommune,tabLatitude,tabLongitude,tabPicto,tabLibelle,tabAdresse,tabAdresse2,tabCP,tabDistance,tabMobred,tabIdentifiant,tabHoLundi,tabHoMardi,tabHoMercredi,tabHoJeudi,tabHoVendredi,tabHoSamedi,tabHoDimanche);
}





// Déclaration de la fonction qui lance la recherche
function loadData(monDomicile, telMobile) {

	// Création de l'objet
	var XHR = new XHRConnection();
	//XHR.appendData("recherche", document.getElementById('recherche').value);
	
	if(telMobile.length > 0)
	{
		
		parent.document.getElementById('tel_portable_soco').value = telMobile;
	}
	
	
	adresse='';
	var adresse_soco = document.getElementById('adresse_soco').value;
	var ville_soco = document.getElementById('ville_soco').value;
	var cp_soco = document.getElementById('cp_soco').value;
	
	if(adresse_soco.length > 4 || ville_soco.length > 4 || cp_soco.length > 4)
	{
		adresse = adresse_soco+' '+cp_soco+' '+ville_soco;
	}
	

	XHR.appendData("monDomicile", monDomicile);
	XHR.appendData("origine", adresse);
	
	// On soumet la requête
	// 	+ On indique à l'objet qu'il faut appeler le fichier SoColissimo.php, que la méthode est POST et que la fonction appelé lorsque l'action est faite
	XHR.sendAndLoad("./script/SoColissimo/SoColissimo.php", "POST", afficherResultats);
	
	
	
	parent.document.getElementById('divOpaqueSoColissimo').className='display';
	parent.document.getElementById('divPopupSoColissimo').className='display';
	
}


// Déclaration de la fonction qui lance la recherche
function loadData2(tabDistance) {

	// Création de l'objet
	var XHR = new XHRConnection();

	XHR.appendData("tabDistance", tabDistance);
	XHR.appendData("tabIdentifiant", document.getElementById('SoCoIdent').value);
	XHR.appendData("session_id", document.getElementById('SoCoId').value);
	XHR.appendData("latOrigine", document.getElementById('latOrigine').value);
	XHR.appendData("longOrigine", document.getElementById('longOrigine').value);
	
	// On soumet la requête
	// 	+ On indique à l'objet qu'il faut appeler le fichier SoColissimo.php, que la méthode est POST et que la fonction appelé lorsque l'action est faite
	XHR.sendAndLoad("./script/SoColissimo/SoColissimo_dist.php", "POST", afficherResultats2);
}
	
	
	
	
	
	
	
var gmarkers = [];
var infoWindows = [];
function initialize(lat,long,tabCommune,tabLatitude,tabLongitude,tabPicto,tabLibelle,tabAdresse,tabAdresse2,tabCP,tabDistance,tabMobred,tabIdentifiant,tabHoLundi,tabHoMardi,tabHoMercredi,tabHoJeudi,tabHoVendredi,tabHoSamedi,tabHoDimanche) {
	  // *** *** Creation de la carte *** ***
	  // *** Centrage sur le centre de la France ***
	 
	  latlng_c=[lat,long] //"Centrage"
	 
	  var latlng = new google.maps.LatLng(latlng_c[0],latlng_c[1]);
	  var myOptions = {
		zoom: 14,
		center: latlng,
		mapTypeId: google.maps.MapTypeId.ROADMAP
	  };
	  var map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
	 
	  // *** Ajout des marqueur ***
	tMark = '';  
	for (i=0; i<tabCommune.length; i++){	
		mark_Address(map,tabCommune[i],tabLatitude[i],tabLongitude[i],tabPicto[i],tabLibelle[i],tabAdresse[i],tabAdresse2[i],tabCP[i],tabDistance[i],tabMobred[i],tabIdentifiant[i],tabHoLundi[i],tabHoMardi[i],tabHoMercredi[i],tabHoJeudi[i],tabHoVendredi[i],tabHoSamedi[i],tabHoDimanche[i]);
	}  
	
	 
 
} // fin de la fonction initialize ()
 
 
 
// ******  Fonction marquage ******
function mark_Address(map,Commune,latitude,longitude,Picto,Libelle,address,address2,CP,Distance,Mobred,Identifiant,tabHoLundi,tabHoMardi,tabHoMercredi,tabHoJeudi,tabHoVendredi,tabHoSamedi,tabHoDimanche) {
	 
	 
	 
	 
	 var divCont = document.getElementById("listePointRetrait");
	 
		 
	  var latlng = new google.maps.LatLng(latitude,longitude);
	  
	  var HoLundi = formatHoraire(tabHoLundi);
  	  var HoMardi = formatHoraire(tabHoMardi);
  	  var HoMercredi = formatHoraire(tabHoMercredi);
  	  var HoJeudi = formatHoraire(tabHoJeudi);
  	  var HoVendredi = formatHoraire(tabHoVendredi);
  	  var HoSamedi = formatHoraire(tabHoSamedi);
  	  var HoDimanche = formatHoraire(tabHoDimanche);	  
	  
	  
	  
	  picto_gauche = '';
	  if(Picto == "A2P"){picto_gauche = "picto-commerce.png";}
	  else if(Picto == "MD"){picto_gauche = "picto-home.png";}
	  else if(Picto == "CIT"){picto_gauche = "picto-cityssimo.png";}
	  else{picto_gauche = "picto-poste.png";} 
	  
	  
	  
	  var adr = address;
	  if(address2.length > 1)
	  {
		  adr = adr.concat("<br>"+address2);
	  }
	  
	  
	  
	  if(Picto == 'MD')
				{
	  //contenu de la div sur la carte.
	  var content_div = '<div class="divCarteMD"><p><h6>'+Libelle+'</h6></p><br><img src="./images/defaut/SoColissimo/ok.png" class="CP" alt="Valider" title="Valider" onclick="choisir_point(\'MD\',\'Mon Domicile\',\'\',\'\',\'\',\'\',\'\',\'\',\'\')"></div>';
				}else{
	  //contenu de la div sur la carte.
	  var content_div = '<div class="divCarte"><p><h6>'+Libelle+'</h6><font size="4">'+adr+'<br>'+CP+' '+Commune+'</p><br><img src="./images/defaut/SoColissimo/ok.png" class="CP" alt="Valider" title="Valider" onclick="choisir_point(\''+Identifiant+'\',\''+Libelle+'\',\''+address+'\',\''+address2+'\',\''+CP+'\',\''+Commune+'\',\''+Picto+'\')"><br><br>Horaires:<br><b>Lundi: </b>'+HoLundi+'<br><b>Mardi: </b>'+HoMardi+'<br><b>Mercredi: </b>'+HoMercredi+'<br><b>Jeudi: </b>'+HoJeudi+'<br><b>Vendredi: </b>'+HoVendredi+'<br><b>Samedi: </b>'+HoSamedi+'<br><b>Dimanche: </b>'+HoDimanche+'</font></div>';				
				}
				
				
				
				
	  var myWindowOptions = {
		  content:
		  content_div
	  };
	  var myInfoWindow = new google.maps.InfoWindow(myWindowOptions);
	  
	  
	  
	 
	  var myMarkerImage = new google.maps.MarkerImage('./images/defaut/SoColissimo/'+picto_gauche);	
	  
	  
	  var marker = new google.maps.Marker({
		position: latlng,
		map: map,
		icon: myMarkerImage,
		title: Libelle
	  });
	  // Affichage de la fenetre au click sur le marker
	  google.maps.event.addListener(marker, 'click', function() {		
		 myInfoWindow.open( map, marker);
		  window.scrollTo(0,0);
	  });
	  
	  google.maps.event.addListener(map, 'click', function(){
   		myInfoWindow.close();
 	  });
	  
	  gmarkers.push(marker);
	  infoWindows.push(myInfoWindow);
	  
	  

	 
	            mobred = '';
    			if(Mobred == 1)
				{mobred = '<img src="./images/defaut/SoColissimo/picto-handicap.png" class="mobred">';}
				
				adresse = '';
				if(address2.length > 0)
				{	adresse = '<span class="address1">'+address+'</span><br /><span class="address2">'+address2+'</span><br />'; }
				else {	adresse = '<span class="address1">'+address+'</span><br />'; }
				
				
				
				 // creation du bouton vers marqueur
	  			var oBtn = document.createElement('div');
	  			oBtn.className = "PointRetrait";
	  
	  		
			  // function sur click
			  oBtn.onclick = function(){
				google.maps.event.trigger( marker, "click");
			  };
				
				
				
				if(Picto == 'MD')
				{
				oBtn.innerHTML += '<span class="picto"><img src="./images/defaut/SoColissimo/'+picto_gauche+'" alt=""></span><span class="libelle">'+Libelle+'</span><br /><span class="address1">Je souhaite &ecirc;tre livr&eacute; &agrave; mon domicile</span><span class="point-choose" onclick="choisir_point(\'MD\',\'Mon Domicile\',\'\',\'\',\'\',\'\',\'\',\'\',\'\')"><img src="./images/defaut/SoColissimo/ok.png" alt="Valider" title="Valider"></span>';
				}else{
				oBtn.innerHTML += '<span class="picto"><img src="./images/defaut/SoColissimo/'+picto_gauche+'" alt=""></span><span class="distance">(env '+Distance+' km)</span><span class="libelle">'+Libelle+'</span><br />'+adresse+'<span class="cp_ville">'+CP+' '+Commune+'</span><span class="point-choose" onclick="choisir_point(\''+Identifiant+'\',\''+Libelle+'\',\''+address+'\',\''+address2+'\',\''+CP+'\',\''+Commune+'\',\''+Picto+'\')"><img src="./images/defaut/SoColissimo/ok.png" alt="Valider" title="Valider"></span>'+mobred;
				}

				divCont.appendChild ( oBtn);
}
	
	
	
function fermer_SoColissimo() {
	
	parent.document.getElementById('divOpaqueSoColissimo').className='display_none';
	parent.document.getElementById('divPopupSoColissimo').className='display_none';
	
	parent.document.getElementById('typeSoco').value="MD";
	parent.document.getElementById('point_retrait_soco_choisi').value="";
	parent.document.getElementById('SoCoPortable').value="";
	
	parent.document.getElementById('adresse_soco').value="";
	parent.document.getElementById('cp_soco').value="";
	parent.document.getElementById('ville_soco').value="";
	
	}
	

	
function choisir_point(point,Libelle,address,address2,CP,Commune,Picto)
	  {
		  var portable = document.getElementById('tel_portable_soco').value;
		 
		 if(point == "MD")
		 {
						parent.document.getElementById('divOpaqueSoColissimo').className='display_none';
						parent.document.getElementById('divPopupSoColissimo').className='display_none'; 
						afficherDivMonDomicile();
		 }else{
		 
			  if(portable.length !=0){
			  
					  if(isTelephonePortable(portable)){
						  
						  	 picto_gauche = '';
	 						 if(Picto == "A2P"){picto_gauche = "commercant_Q_1.png";}
							 else if(Picto == "CIT"){picto_gauche = "City_Q_1.png";}
							 else{picto_gauche = "BureauPoste_Q_1.png";} 
						  
							parent.document.getElementById('AdrPointRelais').innerHTML = 	'<h6>'+Libelle+'</h6><font size="4">'+address+'<br>'+address2+'<br>'+CP+' '+Commune+'<br></font>';
							parent.document.getElementById('AdrPointRelaisPicto').innerHTML = 	'<img src="./images/defaut/SoColissimo/'+picto_gauche+'" />';							
							
							
							parent.document.getElementById('point_retrait_soco_choisi').value=point;
							parent.document.getElementById('divOpaqueSoColissimo').className='display_none';
							parent.document.getElementById('divPopupSoColissimo').className='display_none';
							parent.document.getElementById('SoCoPortable').value=portable;
							
							parent.document.getElementById('typeSoco').value=Picto;
							
							parent.document.getElementById('blocSoCo').className='display_none';
							parent.document.getElementById('adresseSoCoChoisi').className='display blocChoixSoCo pdg_10 mar_b_10 mar_t_10';
	
						  
					  }else{
						  alert("Le numéro de téléphone portable n'est pas valide");
					  }
			  }else{
						  alert("Le numéro de téléphone portable est obligatoire");
			  }
		 }
	  }
	
	
	
	
 function calcul_dist(latitude_orgine,longitude_orgine,tabLatitude,tabLongitude,tabIdentifiant)
     {
		 
		 tabDestination = new Array();
		 for (i=0; i<tabLatitude.length; i++){	
		 tabDestination[i] = "("+tabLatitude[i]+","+tabLongitude[i]+")";
		 }
     
	 	 document.getElementById('SoCoIdent').value = tabIdentifiant;
		 
	     var origine = '('+latitude_orgine+','+longitude_orgine+')';
		
		 var service = new google.maps.DistanceMatrixService();
		 service.getDistanceMatrix(
		 {
		 origins: [origine],
		 destinations: tabDestination,
		 travelMode: google.maps.TravelMode.DRIVING,
		 unitSystem: google.maps.UnitSystem.METRIC,
		 avoidHighways: false,
		 avoidTolls: false
		 }, callback );
	 
	 
    }
    
function callback(response, status)
     {
		
		tabDistance = new Array();

     if (status != google.maps.DistanceMatrixStatus.OK)
    	 {
    			 //alert('Erreur : ' + status); //message d'erreur du serveur distant GG Maps
    	 }
     else
    	 {
			 //réponses du serveur (
			 var origins = response.originAddresses;
			 var destinations = response.destinationAddresses;

			
			for (var i = 0; i < origins.length; i++)
			 {
			 var results = response.rows[i].elements;
			 var dep = origins[i];
			 if(dep!='')
			 {
			 for (var j = 0; j < results.length; j++)
			 {
			 var element = results[j];
			 var statut = element.status;
			 var arr = destinations[j];
			 if(statut=='OK')
			 {
			 
			 var dist = element.distance.value;
			 tabDistance[j] = element.distance.value;
			 
			 }
			
			 
			 }
			 }
			
			 }
		 }

		 loadData2(tabDistance); 	 
}	
	


function isTelephonePortable(numero){
	
	numero = remplacer(numero);
	
	var reg_telephone_portable = '^(06|07)[0-9]{8}$';
	if( numero.match(reg_telephone_portable) ){
		return true;
	} else {
		return false;
	}
}


function remplacer(a)
 {
	 var tmp;
	 tmp = "";
	
	 for(var i = 0; i < a.length; i++)
	 {
		 tmp = tmp + a.charAt(i);
		 if (a.charAt(i) == " ")
		 {
			 tmp = tmp.replace(" ","");
		 }
		 if (a.charAt(i) == "-")
		 {
			 tmp = tmp.replace("-","");
		 }
	 }
	 return tmp;
} 
	
function aideSoCo(id)
{
	
	parent.document.getElementById('aideCom').className='display_none';
	parent.document.getElementById('aideCity').className='display_none';
	parent.document.getElementById('aideBP').className='display_none';
	parent.document.getElementById('aideDomicile').className='display_none';
	parent.document.getElementById('aideDomicileRDV').className='display_none';
	
 	parent.document.getElementById(id).className='display blocAideSoCo';
		
}

function aideSoCoOut(id)
{
 	parent.document.getElementById(id).className='display_none';
		
}

function afficherDivMonDomicile()
{
	parent.document.getElementById('blocSoCo').className='display_none';
	parent.document.getElementById('AdrLivMonDom').className='display blocChoixSoCo pdg_10 mar_b_10 mar_t_10';
	parent.document.getElementById('typeSoco').value="MD";
	
}

function afficherDivMonDomicileRDV()
{
	parent.document.getElementById('blocSoCo').className='display_none';
	parent.document.getElementById('AdrLivMonDomRDV').className='display blocChoixSoCo pdg_10 mar_b_10 mar_t_10';
	parent.document.getElementById('typeSoco').value="MDRDV";
	
}


function afficherDivBlocSoCo()
{
	parent.document.getElementById('blocSoCo').className='display mar_t_10 mar_b_10';
	parent.document.getElementById('AdrLivMonDom').className='display_none';
	parent.document.getElementById('AdrLivMonDomRDV').className='display_none';
	parent.document.getElementById('adresseSoCoChoisi').className='display_none';
	
	parent.document.getElementById('typeSoco').value="MD";
	parent.document.getElementById('point_retrait_soco_choisi').value="";
	parent.document.getElementById('SoCoPortable').value="";
	
}





//si SoColissimo RDV alors recalcul du total panier et TVA
function calculBasketRDV(total, tva)
{
	total2 = total.replace(",",".");
	total2 = Number(total2)+Number(5);
	total2 = Math.round(total2*100)/100
	
	tva2 = tva.replace(",",".");
	tva2 = Number(tva2)+Number(0.8194);
	tva2 = Math.round(tva2*1000)/1000

	
	parent.document.getElementById('totalPanier').innerHTML=total2+'&euro;';
	parent.document.getElementById('tva196').innerHTML=tva2+'&euro;';
	
	
}

//si SoColissimo RDV alors recalcul du total panier et TVA
function UnsetCalculBasketRDV(total, tva)
{
	parent.document.getElementById('totalPanier').innerHTML=total+'&euro;';
	parent.document.getElementById('tva196').innerHTML=tva+'&euro;';
	
	
}

//si SoColissimo RDV alors recalcul du total panier et TVA
function formatHoraire(horaire)
{
	if(horaire){
	ho = horaire.split(" ");
		if(ho[1] != '00:00-00:00')
		{
		return ho[0]+' et '+ho[1];	
		}else if(ho[0] == '00:00-00:00'){
		return 'Fermé';
		}else{
		return ho[0];
		}
	}else{
	return;
	}
	
}



function ValiderFormSoco(){
	
	var typeSoco = parent.document.getElementById('typeSoco').value;
	
	
	//verification du numero de portable 
	if(typeSoco == 'MDRDV'){
	parent.document.getElementById('SoCoPortable').value = parent.document.getElementById('portable_socolissimo').value;
	}
	
	
	if(typeSoco != 'MD' && isTelephonePortable(parent.document.getElementById('SoCoPortable').value))
	{		
	document.getElementById("formulaireChoixSoco").submit();
	}
	else if(typeSoco == 'MD')
	{
	document.getElementById("formulaireChoixSoco").submit();		
	}
	else if(!isTelephonePortable(parent.document.getElementById('SoCoPortable').value) && typeSoco.length > 1){
	alert("Veuillez vérifier ou compléter votre numéro de téléphone mobile.");
	}else{
	parent.document.getElementById('typeSoco').value = 'MD';
	document.getElementById("formulaireChoixSoco").submit();
	}
	
	
}
