/**
* googleUtils.js
* Nicolas Bastien 
* Septembre 2007
*/
/******************************************************************************************************************
**
**							FONCTIONS JAVASCRIPT POUR GOOGLE MAP ---  VACANCES
**
*******************************************************************************************************************/



var map;	
var message;
var noResult;

// Variables définissant la zone de mouvement authorisé
var allowedBounds;
	
var AmaxX;
var AmaxY;
var AminX;
var AminY;

var zoomMax;

// === Flag pour les différents modes
var checkingMode=false;
var updatingMode=false;
var changeCountryMode=false;
var noUpdate=false;

// === Flag de débuggage doit être false en prod !!!
var debugMode = false;
	
// === Listener pour les controls sur les déplacements
var allowedBoundsListener;
var zoomListener;	
	
// === Ratio d'élargissement pour la surface de recherche ===
var ratioElargissement_max 		= 0.75;
var ratioElargissement_large 	= 0.5;
var ratioElargissement_moyen 	= 0.25;
var ratioElargissement_faible 	= 0.1;
var ratioElargissement_min 		= 0;

//Déclaration du type coordcountry
function Coordcountry(latboundsw, longboundsw, latboundne, longboundne, flagparcarte) {
 	this.latboundsw  = latboundsw;
	this.longboundsw = longboundsw;
 	this.latboundne  = latboundne;
 	this.longboundne = longboundne;
 	this.flagparcarte = flagparcarte;
}// coordcountry

//Fonction qui renvoie la surface de déplacement authorisée pour un pays donné
function getAllowedBounds(pays){
	//On agrandit la surface pour coller à la carte des résulats qui est plus grande que sur la home
	var ltbdsw = coordcountrytab[pays].latboundsw;
	var ltbdne = coordcountrytab[pays].latboundne;
	var lgbdsw = coordcountrytab[pays].longboundsw;				
	var lgbdne = coordcountrytab[pays].longboundne;
	
	var bounds   = new GLatLngBounds(new GLatLng(ltbdsw,lgbdsw), new GLatLng(ltbdne,lgbdne));			
	
	return bounds;		
}//getAllowedBounds
		
//Fonction qui repositionne la carte lors d'un changement de pays sur la home
//MBR 03/03/2008 mantis 788 : Recherche Vacances > Modifier le principe de la liste déroulante en recherche par carte
// si flagCarte!=1 alors on renvoie sur la home multicritères
function changeCountryHome() {
	var country = document.getElementById("pa").value;  
	
	if(coordcountrytab[country].flagparcarte!=1)
	{
		window.location.href=(urlRedirectPasCarte+'?pa='+ country )
		return false;
	}
	
	//Suppression de la limitation du zoom 
	unsetLimitZoom();
	
	//Evite le problème de repositionnement
	map.disableDragging();
	
	//On redéfini les limites de mouvements en fonction de pays  	
	allowedBounds = getAllowedBounds(country);
	
	Amaxlg = allowedBounds.getNorthEast().lng();
	Amaxlt = allowedBounds.getNorthEast().lat();
	Aminlg = allowedBounds.getSouthWest().lng();
	Aminlt = allowedBounds.getSouthWest().lat();
	
	//Recentrage de la carte
	map.setCenter(allowedBounds.getCenter(),map.getBoundsZoomLevel(allowedBounds));
	
	zoomMax = map.getZoom();
	limitZoom(zoomMax);	
	setTimeout (function(){ 
		map.zoomIn();
		map.zoomOut();		
	},10);

	return;	
}//changeCountryHome

//Fonction qui repositionne la carte lors d'un changement de pays
//sur la carte de résultat
function changeCountry() {
	var country = document.getElementById("pa").value;  
	document.getElementById("pa").disabled = true;
	changeCountryMode=true;
	noUpdate = true;
	//suppression de tout les markers
	map.clearOverlays();
	
	//Suppression de la limitation du zoom 
	unsetLimitZoom();
	map.setZoom(1);
	//Evite le problème de repositionnement
	map.disableDragging();
	
	//On redéfini les limites de mouvements en fonction de pays  	
	//allowedBounds = new GLatLngBounds(new GLatLng(coordcountrytab[country].latboundsw,coordcountrytab[country].longboundsw), new GLatLng(coordcountrytab[country].latboundne,coordcountrytab[country].longboundne));   	
	allowedBounds = getAllowedBounds(country);
	
	Amaxlg = allowedBounds.getNorthEast().lng();
	Amaxlt = allowedBounds.getNorthEast().lat();
	Aminlg = allowedBounds.getSouthWest().lng();
	Aminlt = allowedBounds.getSouthWest().lat();
	
	//Recentrage de la carte
	map.setCenter(allowedBounds.getCenter(),map.getBoundsZoomLevel(allowedBounds));
	
	zoomMax = map.getZoom();
	limitZoom(zoomMax);	
	setTimeout (function(){ 
		map.zoomIn();
		map.zoomOut();		
	},250);
	setTimeout (function(){
		document.getElementById("pa").disabled = false;
	},2500);
	
	return;
		
}//changeCountry

/**********************************************************************************************
								FONCTIONS CONTROLE DE LA MAP	
**********************************************************************************************/

//Fonction qui permet d'ajouter la barre de control Drag and Zoom
//@param map 	-> la map à laquelle il faut l'ajouter
//@param state  -> l'état dans lequel dans être la map 
//				   si state == 'zooming' la map est en mode zoom au chargement
function addDragZoomControl(map,state) {
	   //Définition du style de l'icone
       var boxStyleOpts = {
         opacity: 0.2,
         border: "2px solid red"
       }

       // Option du bouton
       // -> C'est ici que l'on paramètre les images utilisées
       var otherOpts = {
         buttonHTMLZoom: "<img src='"+dossierImages+"img/modules/cartographie/zoom.gif' onmouseover=\"affiche_pop('inf_zoom')\" onmouseout=\"masque_pop('inf_zoom')\"/>",
         buttonZoomingHTMLZoom: "<img src='"+dossierImages+"img/modules/cartographie/zoom-ac.gif' onmouseover=\"affiche_pop('inf_zoom')\" onmouseout=\"masque_pop('inf_zoom')\"/>",
         buttonHTMLDrag: "<img src='"+dossierImages+"img/modules/cartographie/drag.gif' onmouseover=\"affiche_pop('inf_dep')\" onmouseout=\"masque_pop('inf_dep')\"/>",
         buttonZoomingHTMLDrag: "<img src='"+dossierImages+"img/modules/cartographie/drag-ac.gif' onmouseover=\"affiche_pop('inf_dep')\" onmouseout=\"masque_pop('inf_dep')\"/>",
         buttonStartingStyle: {width: '24px', height: '24px'},
         stickyZoomEnabled: true
       };

       //Callback -> debug
       var callbacks = {};
 /*        buttonclick: function(){GLog.write("Looks like you activated DragZoom!")},
         dragstart: function(){GLog.write("Started to Drag . . .")},
         dragging: function(x1,y1,x2,y2){GLog.write("Dragging, currently x="+x2+",y="+y2)},
         dragend: function(nw,ne,se,sw,nwpx,nepx,sepx,swpx){GLog.write("Zoom! NE="+ne+";SW="+sw+' nwpx '+nwpx+' nepx '+nepx)}
       };
 */
  	    
  		var dragZoomControl = new DragZoomControl(boxStyleOpts, otherOpts, callbacks);  		
  		map.addControl(dragZoomControl);  		
  		if(state == 'zooming'){
  			dragZoomControl.setZoomingMode();	
		}
		
		return;
        
}// addDragZoomControl(map)


/**
 * Affiche / Masque les pop-up d'aide de la carte
 * @param {Object} arf
 */
function affiche_pop(arf) {
	if(typeof(arf)!='undefined'){
		document.getElementById(arf).style.display = "block";
	}
}
function masque_pop(arf) {
	if(typeof(arf)!='undefined'){
		document.getElementById(arf).style.display = "none";
	}	

}

// Fonction qui vérifie le positionnement de la map après un déplacement
// Si la surface afficher est en dehors des limites authorisées pour le pays (allowedBounds)
// un repositionnement est effectué
// 
// Cette fonction est branché sur les listenners des actions: "dragend" et "zoomend"

function checkBounds() {
	//Si un repositionnement est en court
	//ou que l'on vient de changer de pays
	// -> aucun control
	if(checkingMode || changeCountryMode){
		return;
	}
	
	//dbg('-> checkBounds','info');
	
	checkingMode = true;	    
	var currentBounds = map.getBounds();
	
	//La page de résultat étant plus grande
	//Si tout le pays est affficher, c'est bon
	if (currentBounds.containsBounds(allowedBounds) === true){
		return;
	}

	// Verification de la position
	if (allowedBounds.containsBounds(currentBounds) === false) {
	    
	    //dbg('Limite dépassées','log');
	    
	    // On est en dehors des limites	
	    map.disableDragging();
		var currentSW = currentBounds.getSouthWest();
		var currentNE = currentBounds.getNorthEast();			
		
		var swlg = currentSW.lng(); //dbg('swlg '+swlg,'log');
		var swlt = currentSW.lat(); //dbg('swlt '+swlt,'log');
		var nelg = currentNE.lng(); //dbg('nelg '+nelg,'log');
		var nelt = currentNE.lat(); //dbg('nelt '+nelt,'log');
		
		var currentWidth  = Math.abs(nelg - swlg);
		var currentHeight = Math.abs(nelt - swlt);
		
		//dbg('allowedBounds ' + allowedBounds,'log');
		//dbg('currentBounds ' + currentBounds,'log');
		
		//dbg('Limites Max !','info');
		//dbg('Aminlg '+Aminlg,'log');
		//dbg('Amaxlg '+Amaxlg,'log');
		//dbg('Aminlt '+Aminlt,'log');
		//dbg('Amaxlt '+Amaxlt,'log');		
		
		//dbg('Vérification limites Max !','info');
		if(allowedBounds.intersects(currentBounds) === false) {
			//dbg('En dehors !','info');
			//Dans le cas où l'on est complètement sorti des limites
			//On traite ces cas limites
			if (swlg > Amaxlg) {nelg=Amaxlg; swlg=Amaxlg-currentWidth;}  //dbg('Extérieur droit','log');}
			if (nelg < Aminlg) {swlg=Aminlg; nelg=Aminlg+currentWidth;} //dbg('Extérieur gauche','log');}
			if (swlt > Amaxlt) {nelt=Amaxlt; swlt=Amaxlt-currentHeight;} //dbg('Extérieur haut','log');}
			if (nelt < Aminlt) {swlt=Aminlt; nelt=Aminlt+currentHeight;} //dbg('Extérieur bas','log');}
		}
				
		if (swlg < Aminlg) {swlg = Aminlg; nelg=Aminlg+currentWidth;}  //dbg('swlg '+swlg,'log');}
		if (nelg > Amaxlg) {nelg = Amaxlg; swlg=Amaxlg-currentWidth;}  //dbg('nelg '+nelg,'log');}
		if (swlt < Aminlt) {swlt = Aminlt; nelt=Aminlt+currentHeight;} //dbg('swlt '+swlt,'log');}
		if (nelt > Amaxlt) {nelt = Amaxlt; swlt=Amaxlt-currentHeight;} //dbg('nelt '+nelt,'log');}		
		
		var newBounds = new GLatLngBounds(new GLatLng(swlt,swlg),new GLatLng(nelt,nelg));
		var newCenter = newBounds.getCenter();		
		//dbg('New center!'+newCenter,'info');
		
		if (allowedBounds.containsLatLng(newCenter) === false) {
			//Temporaire en attente de solution!
			//dbg('Out of bounds !','warn');			
			return;		
		}
		map.enableDragging();
		map.panTo(newCenter); 		
	}else{
		checkingMode = false;
	}
	
	return;
}// checkBounds()

//Desactive le mouvement si on est au zoom maximum
function checkZoom(){
	if(changeCountryMode){
		return;
	}
	
	if(map.getZoom()<= zoomMax){	
		//On repositionne sur le centre du pays
		var pays = document.getElementById("pa").value;  
		var ltbdsw = coordcountrytab[pays].latboundsw;
		var ltbdne = coordcountrytab[pays].latboundne;
		var lgbdsw = coordcountrytab[pays].longboundsw;				
		var lgbdne = coordcountrytab[pays].longboundne;
		
		var bounds = new GLatLngBounds(new GLatLng(ltbdsw,lgbdsw), new GLatLng(ltbdne,lgbdne));	
		map.setCenter(bounds.getCenter(),map.getBoundsZoomLevel(bounds));
	
		map.disableDragging();
	}else{
		map.enableDragging();
	}
}// checkZoom

//Fonction permettant de brider le zoom arrière
//En pratique on bride le zoom arrière sur le zoom min permettant d'afficher le pays
function limitZoom(zoomMin){	
	// Get the list of map types      
	var mt = map.getMapTypes();
	// Overwrite the getMinimumResolution() and getMaximumResolution() methods
	for (var i=0; i<mt.length; i++) {
		mt[i].getMinimumResolution = function() {return zoomMin;}
	}
}// limitZoom(zoomMax)


//Fonction annulant l'effet de limitZoom
function unsetLimitZoom(){
	//limite au zoom le moins élevé
	limitZoom(2);
}//unsetLimitZoom();	
	
	

// Fonction définissant les actions de la barre de mouvement
// @param dir -> directions possibles : 'up', 'down', 'left', 'right'
function moveDirection(dir) {
	
	//Si l'on est en mode d'update ou de check
	//on attend d'abord la fin des appels ajax
	//pour ne pas faire de requêtes simultanées
	if(checkingMode || updatingMode){
		return;
	}
	
	var mb = map.getBounds();
	var c = map.getCenter();
	
	lgne = mb.getNorthEast().lng();
	ltne = mb.getNorthEast().lat();
	lgsw = mb.getSouthWest().lng();
	ltsw = mb.getSouthWest().lat(); 
	
	var mapWidth = lgne-lgsw;
	var mapHeight= ltne-ltsw;
	
	var lt;
	var lg;
	
	switch(dir){
		case 'up':
			lg = c.lng();
			lt = c.lat() + mapHeight/10;
			break;
		case 'down':
			lg = c.lng();
			lt = c.lat() - mapHeight/10;
			break;
		case 'left':
			lg = c.lng() - mapWidth/10;
			lt = c.lat();
			break;
		case 'right':
			lg = c.lng() + mapWidth/10;
			lt = c.lat();
			break;
	}	
	
	var newCenter = new GLatLng(lt,lg); 
	map.panTo(newCenter);

	GEvent.trigger(map,'dragend');
	
	return true;
};

/**********************************************************************************************
							FONCTIONS VALIDATION FORMULAIRE	
**********************************************************************************************/

function createGeolocRecherche (xltsw,xlgsw,xltne,xlgne) {
		
	var ratioElargissement;
	var geoloc;
	
	//Calcul de la distance pour déterminer le ratioElargissement
   	//Principe plus le zoom est précis plus on élargi la recherche
   	var difLatitude   = xltne - xltsw;
   	var difLatitudeKM = difLatitude * 111.2;    	
   	
   	if(difLatitudeKM < 15){
   		ratioElargissement = ratioElargissement_max;
   	}else if(difLatitudeKM < 30){
   		ratioElargissement = ratioElargissement_large;
   	}else if(difLatitudeKM < 50){
   		ratioElargissement = ratioElargissement_moyen;
   	}else if(difLatitudeKM < 100){
   		ratioElargissement = ratioElargissement_faible;
   	}else{
   		ratioElargissement = ratioElargissement_min;
   	}   

   	//Calcul de la surface converte par la recherche
   	var latCentre = (xltsw + xltne) /2;
   	var lngCentre = (xlgsw + xlgne) /2;
   	
   	var decalageLat = (xltne - latCentre) * (1 + ratioElargissement);

   	xltne = latCentre + decalageLat;
   	xltsw = latCentre - decalageLat;    	
   	
   	var decalageLng = (xlgne - lngCentre) * (1 + ratioElargissement);

   	xlgne = lngCentre + decalageLng;
   	xlgsw = lngCentre - decalageLng;

	//Arrondit pr optimiser le cache
	//Zoom faible -> arrondit à 0.5	
	if(ratioElargissement < ratioElargissement_moyen){
		if(xltsw-parseInt(xltsw,10)>0.5){xltsw = Math.floor(xltsw)+0.5;}else{xltsw = Math.floor(xltsw);}
		if(xlgsw-parseInt(xlgsw,10)>0.5){xlgsw = Math.floor(xlgsw)+0.5;}else{xlgsw = Math.floor(xlgsw);}	
				
		if(xltne-parseInt(xltne,10)>0.5){xltne = Math.ceil(xltne);}else{xltne = Math.ceil(xltne)-0.5;}
		if(xlgne-parseInt(xlgne,10)>0.5){xlgne = Math.ceil(xlgne);}else{xlgne = Math.ceil(xlgne)-0.5;}		
	}else{
		//Zoom élevé -> arrondit simple pour ne pas trop agrandir la surface
		xltsw = Math.floor(xltsw*100) /100; 	
		xlgsw = Math.floor(xlgsw*100) /100;
		xltne = Math.ceil(xltne*100) /100;
		xlgne = Math.ceil(xlgne*100) /100;		
	}		
	geoloc = '&ltne='+xltne+'&lgne='+xlgne+'&ltsw='+xltsw+'&lgsw='+xlgsw;
	
	return geoloc;

}// createGeolocRecherche

	
function createParamRecherche(page){
		
	document.getElementById('divMessageError').style.display = 'none';
	
	if(document.getElementById("px1").value.match(/^[0-9]*$/) === null){
		//Le prix n'est pas valide
		document.getElementById('spanMessageError').innerHTML = 'Vous devez saisir un prix valide.';
		document.getElementById('divMessageError').style.display = 'block';
		// msg erreur 20081215 - document.getElementById('divMessageError').className = 'b cred';
		
		return false;	
	}
	
	// === Création des paramètres de recherche (utilisé via Ajax) ===
	var param = 'tp=ofr';		
	if (document.getElementById("pa").value !== ''){  param += '&pa=' + document.getElementById("pa").value;}
	if (document.getElementById("cah0").value !== ''){param += '&cah0=' + document.getElementById("cah0").value;}
	if (document.getElementById("px1").value !== ''){ param += '&px1=' + document.getElementById("px1").value;}		
	
	//Checkbox		
	selectCheckbox = false;
	if (document.recherche.tyhApp.checked){param += '&tyhApp=on'; selectCheckbox = true;}
	if (document.recherche.tyhMsn.checked){param += '&tyhMsn=on'; selectCheckbox = true;}
	if (document.recherche.tyhChl.checked){param += '&tyhChl=on'; selectCheckbox = true;}
	if (document.recherche.tyhHtl.checked){param += '&tyhHtl=on'; selectCheckbox = true;}
	if (document.recherche.tyhGt.checked){ param += '&tyhGt=on'; selectCheckbox = true;}
	if (document.recherche.tyhMH.checked){ param += '&tyhMH=on'; selectCheckbox = true;}
	if (document.recherche.aha.checked){   param += '&aha=on'; selectCheckbox = true;}
	if (document.recherche.ana.checked){   param += '&ana=on'; selectCheckbox = true;}
	if (document.recherche.pro.checked){   param += '&pro=on'; selectCheckbox = true;}
	if (document.recherche.part.checked){   param += '&part=on'; selectCheckbox = true;}
	if (document.recherche.tyhHH.checked){ param += '&tyhHH=on'; selectCheckbox = true;}
	if (document.recherche.tyhCA.checked){ param += '&tyhCA=on'; selectCheckbox = true;}

	if(selectCheckbox === false){
		//Le type de logement n'est pas valide
		document.getElementById('spanMessageError').innerHTML = 'Vous devez saisir un Type de logement.';
		document.getElementById('divMessageError').style.display = 'block';
		// msg erreur 20081215 - document.getElementById('divMessageError').className = 'b cred';
		
		return false;	
	}

	if(page == 'resultat'){
		//date
		if(document.recherche.dt[0].checked){param += '&dt='+document.recherche.dt[0].value;}
		if(document.recherche.dt[1].checked){param += '&dt='+document.recherche.dt[1].value;}
		
		if (document.recherche.ph.checked){param += '&ph=1';}
	}else{
		param += '&dt=tt';
	}
	return param;
}	
function createParamRecherche9(page){
		
	document.getElementById('divMessageError').style.display = 'none';
	
	if(document.getElementById("px1").value.match(/^[0-9]*$/) === null){
		//Le prix n'est pas valide
		document.getElementById('spanMessageError').innerHTML = 'Vous devez saisir un prix valide.';
		document.getElementById('divMessageError').style.display = 'block';
		document.getElementById('divMessageError').className = 'b cred';
		
		return false;	
	}
	
	// === Création des paramètres de recherche (utilisé via Ajax) ===
	var param = 'pa=' + document.getElementById("pa").value	;	
	if (document.getElementById("nbp0").value !== ''){param += '&nbp0=' + document.getElementById("nbp0").value;}
	if (document.getElementById("px1").value !== ''){ param += '&px1=' + document.getElementById("px1").value;}		
	
	//Checkbox		
	if (document.moteur.tbApp.checked){param += '&tbApp=';}
	if (document.moteur.tbMai.checked){param += '&tbMai=';}
	if (document.moteur.tbTer.checked){param += '&tbTer=';}

	

	return param;
}		
/**********************************************************************************************
										FONCTIONS DE DEBUG	
**********************************************************************************************/
	

//Dessine une surface
function drawBounds(bounds){
	var northEastBounds = bounds.getNorthEast();
	var southWestBounds = bounds.getSouthWest();
	
	var ltne = northEastBounds.lat();
	var ltsw = southWestBounds.lat();
	var lgne = northEastBounds.lng();
	var lgsw = southWestBounds.lng();		
	
	var northWestBounds = new GLatLng(ltne,lgsw);
	var southEastBounds = new GLatLng(ltsw,lgne);
	
	map.addOverlay(new GPolyline([northEastBounds,northWestBounds,southWestBounds,southEastBounds,northEastBounds],'black',3));
}//drawBounds

//Fonction d'aide au débuggage
//Utilise la console de firebug pour afficher des info
//@param string -> le message à afficher
//@param mode	-> le mode : log,info,warn
function dbg(string,mode){

	if(!debugMode){
		return;
	}
	
	switch(mode) {
		case 'info':
			console.info(string);
			break;
		case 'warn':
			console.warn(string);
			break;
		default:
			console.info(string);
			break;
	}
	
	
	return ;

}// dbg(string,mode)

