/*##################################################
# Projet			: AGENCE SAINT-HUBERT								 #
# Date Début	: 12/03/2008												 #
# Last Modif	:																		 #
# Auteurs			: Emmanuel CEGO											 #
# Description	: JS servant à la technologie AJAX	 #
####################################################*/

// Flag pemettant de gérer les concurrences de l'effet AJAX
var flag_effect = 0;

//*************************************************************************//
// FONCTION PERMETTANT DE BLOQUER LA PAGE LE TEMPS DU CHARGEMENT DE L'AJAX //
//*************************************************************************//
function StartAjax(){
	// En attendant l'adaptation pour la nouvelle version
	return;
	// Incrémentation des requêtes AJAX
	flag_effect++;

	// Un seul effet AJAX est nécessaire
	if (flag_effect > 1){
		return;
	}
		
	var overlayDuration = 0.2;
	var overlayOpacity = 0.8;
	
	// PERTE DU FOCUS
	focus();
	
	// BODY
	var objBody = document.getElementsByTagName("body").item(0);
		
	// DIV OMBRAGE
	var objOverlay = document.createElement("div");
	objOverlay.setAttribute('id','overlay');
	objOverlay.style.display = 'none';
	objOverlay.onclick = function() {  }
	objBody.appendChild(objOverlay);
	var arrayPageSize = getPageSize();				
	$('overlay').style.width = arrayPageSize[0] +"px"
	$('overlay').style.height = arrayPageSize[1] +"px"	
		
	// DIV IMAGE CHARGEMENT
	var objLightbox = document.createElement("div");
	objLightbox.setAttribute('id','lightbox');
	objLightbox.setAttribute('align', 'center');
	objLightbox.style.display = 'block';		
	objOverlay.appendChild(objLightbox);
	var arrayPageScroll = getPageScroll();
	$('lightbox').style.position = "relative";
	$('lightbox').style.top = arrayPageScroll[1] + (arrayPageSize[3] / 2) +"px"
	$('lightbox').style.left = arrayPageScroll[0] +"px";

	// IMAGE CHARGEMENT
	var objLoadingImage = document.createElement("img");
	objLoadingImage.setAttribute('src', '/_img/commun/loading.gif');		
	objLightbox.appendChild(objLoadingImage);
		
	// LANCEMENT DE L'EFFET
	new Effect.Appear('overlay', { duration: overlayDuration, from: 0.0, to: overlayOpacity });		
}


//*******************************************************************************//
// FONCTION PERMETTANT DE LIBÉRER LA PAGE LORSQUE LE CHARGEMENT AJAX EST TERMINÉ //
//*******************************************************************************//
function EndAjax(){		
	// En attendant l'adaptation pour la nouvelle version
	return;
	// Décrémentation des requêtes AJAX
	flag_effect--;

	// Tant que toutes les requêtes ne sont pas traitées, l'effet doit continuer
	if (flag_effect > 0){
		return;
	}
	
	// Effet de Fade
	var overlayDuration = 0.2;
	new Effect.Fade('overlay', { duration: overlayDuration});
	
	// On fait disparaître la LightBox
	$('lightbox').style.visible = 'none';		
}


//***********************************************//
// FONCTION PERMETTANT DE LANCER LA REQUÊTE AJAX //
//***********************************************//
function makeRequest(url){				
	// On court-circuite le traitement si c'est le premier élément (informations)
//	if ($('liste_designations').selectedIndex == 0){
//		$('periode').value = "";
//    $('carence').value = "";
//    $('lancement').value = "";
//    $('descriptif').value = "";  
//    return;
//	}	
	StartAjax();

	// Variable qui va contenir l'objet AJAX
	var httpRequest = false;

	// Création de l'objet AJAX
	if (window.XMLHttpRequest){
		httpRequest = new XMLHttpRequest();
  	if (httpRequest.overrideMimeType){
  		// Peut poser problème...
  		httpRequest.overrideMimeType('text/xml');
  	}
	}
	else{
		if (window.ActiveXObject){
			try{
  			httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
  		}
  		catch (e){
  			try{
    			httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
    		}
  			catch (e){}
 			}
		}
	}

	if (!httpRequest){
		alert('Abandon :( Impossible de créer une instance XMLHTTP');
  	return false;
	}
  	
	httpRequest.onreadystatechange = function() { getInfos(httpRequest); };	
	httpRequest.open('GET', url + ieTrick('&'), true);
	httpRequest.send(null);
	
}
    
    
//****************************************************//
// FONCTION EXÉCUTÉE LORSQUE L'ÉTAT DU SERVEUR CHANGE //
//****************************************************//
function getInfos(httpRequest, section, div, element, formulaire){	
	var check = new RegExp("^[0-9]{1,10}$");
	// Le serveur a-t'il répondu ?
	if (httpRequest.readyState == 4){		
		// La réponse est-elle favorable ?
  	if (httpRequest.status == 200){    		  		   		 	  		 	
    	var infos_co = httpRequest.responseText.split("|");      	
//     	if (infos_co[0] != ''){
	if (infos_co[0] != '' && check.test(infos_co[0])){
     		$('img_co').src = infos_co[4];     	
     		$('img_co').onclick = function() {window.location = '/cgi-bin/co/searchfiche_co.cgi?idannonce=' + infos_co[0]};     		
     		if (infos_co[1] != "TERRAIN"){
     			$('desc_co').innerHTML = infos_co[1] + '<br>' + decode(infos_co[2], '#') + ' - ' + decode(infos_co[3], '#');
     		}else{
     			$('desc_co').innerHTML = infos_co[1] + '<br>' + decode(infos_co[3], '#');
     		}
     		$('desc_co').onclick = function() {window.location = '/cgi-bin/co/searchfiche_co.cgi?idannonce=' + infos_co[0]};     		
     	}else{     		
     		$('img_co').src = infos_co[4];
     		$('img_co').onclick = "void(0)";
     		$('desc_co').innerHTML = "";
     		$('desc_co').onclick = "void(0)";     		
     	}
     	EndAjax();
    }else{
    	//alert('Problème AJAX - HTTP Request: ' + httpRequest.status);
	;
    }
  }
}


//***************************************************************//
// FONCTION PERMETTANT D'OUTRE-PASSER LE CACHE DE IE POUR L'AJAX //
//***************************************************************//
function ieTrick(sep){ 
	d = new Date(); 
  trick = d.getYear() + "ie" + d.getMonth() + "t" + d.getDate() + "r" + d.getHours() + "i" + d.getMinutes() + "c" + d.getSeconds() + "k" + d.getMilliseconds(); 
    
  if (sep != "?"){ 
    sep = "&"; 
  } 	
    
  return sep + "ietrick=" + trick; 
}


//******************************************************************************************************//
// FONCTION PERMETTANT DE GÉRER LA VILLE PAR LE CP (MASQUE DE SAISIE + DÉCLENCHEMENT DE LA REQUÊTE AJAX	//
//******************************************************************************************************//
function getCO(){		
	// On lance la requête AJAX			
	setInterval(function(){makeRequest('/cgi-bin/co/search_co.cgi?from_js_function=1')}, 5000);
}	


//********************************//
// FONCTION PERMETTANT D'ENCODER	//
//********************************//
// Param 1 : le string à coder
// Param 2 : le délimiteur
function encode (string, delimiteur){			
	phrase=String(string);
	resultat="";
	
	for (i=0; i<phrase.length; i++) {
		resultat=resultat+delimiteur+phrase.charCodeAt(i);
	}
	return resultat;
}


//********************************//
// FONCTION PERMETTANT DE DECODER	//
//********************************//
// Param 1 : le string à décoder
// Param 2 : le délimiteur
function decode (string, delimiteur){		
	var tab=string.split(delimiteur);	
	var resultat="";
	
	for (i=0; i<tab.length; i++) {		
		resultat = resultat + String.fromCharCode(parseInt(tab[i]));		
	}	
	return resultat;
}


// -----------------------------------------------------------------------------------

//
// getPageSize()
// Returns array with page width, height and window width, height
// Core code from - quirksmode.com
// Edit for Firefox by pHaez
//
function getPageSize(){
	
	var xScroll, yScroll;
	
	if (window.innerHeight && window.scrollMaxY) {	
		xScroll = window.innerWidth + window.scrollMaxX;
		yScroll = window.innerHeight + window.scrollMaxY;		
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		xScroll = document.body.scrollWidth;
		yScroll = document.body.scrollHeight;		
	} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
		xScroll = document.body.offsetWidth;
		yScroll = document.documentElement.scrollHeight;
	}
	
	var windowWidth, windowHeight;
	
//	console.log(self.innerWidth);
//	console.log(document.documentElement.clientWidth);

	if (self.innerHeight) {	// all except Explorer
		if(document.documentElement.clientWidth){
			windowWidth = document.documentElement.clientWidth; 
		} else {
			windowWidth = self.innerWidth;
		}
		windowHeight = self.innerHeight;
	} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
		windowWidth = document.documentElement.clientWidth;
		windowHeight = document.documentElement.clientHeight;
	} else if (document.body) { // other Explorers
		windowWidth = document.body.clientWidth;
		windowHeight = document.body.clientHeight;
	}	
		
	// for small pages with total height less then height of the viewport
	if(yScroll < windowHeight){
		pageHeight = windowHeight;
	} else { 
		pageHeight = yScroll;
	}

//	console.log("xScroll " + xScroll)
//	console.log("windowWidth " + windowWidth)

	// for small pages with total width less then width of the viewport
	if(xScroll < windowWidth){	
		pageWidth = xScroll;		
	} else {
		pageWidth = windowWidth;
	}
//	console.log("pageWidth " + pageWidth)

	arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight) 
	return arrayPageSize;
}





// -----------------------------------------------------------------------------------

//
// getPageScroll()
// Returns array with x,y page scroll values.
// Core code from - quirksmode.com
//
function getPageScroll(){

	var xScroll, yScroll;

	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
		xScroll = self.pageXOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){	 // Explorer 6 Strict
		yScroll = document.documentElement.scrollTop;
		xScroll = document.documentElement.scrollLeft;
	} else if (document.body) {// all other Explorers
		yScroll = document.body.scrollTop;
		xScroll = document.body.scrollLeft;	
	}

	arrayPageScroll = new Array(xScroll,yScroll) 
	return arrayPageScroll;
}
