//------------------------------------------------------------
// MY AJAX ENGINE //////////////////////////////////////
// Author : Emmanuel Gauthier
//------------------------------------------------------------

var viewed_pages = new Array();

var gotolink = '';
var is_ie_nav = 0;

var post_requestS = new Array();
var post_div = null;

//-------------------------------------------
// Pour l'historik ajax 
var mt_historik = {};
var currentPage ;
//-------------------------------------------

function ajaxObject(){
	var AJAXrequest  = null;
	if(window.ActiveXObject){ 
		// Support Internet Explorer
		
		    var ieversions = ['Msxml2.XMLHTTP',
                      'Microsoft.XMLHTTP',
                      'Msxml2.XMLHTTP.5.0',
                      'Msxml2.XMLHTTP.4.0',
                      'Msxml2.XMLHTTP.3.0'
                      ];             
		    for(var i=0; !AJAXrequest && i<ieversions.length; i++)     
		    {         
			 try        
			 {            
			     AJAXrequest = new ActiveXObject(ieversions[i]);        
			 }         
			 catch(e)         
			 {             
			     AJAXrequest = null;         
			 }     
		    }
		
		//AJAXrequest = new ActiveXObject("Microsoft.XMLHTTP");
		return AJAXrequest;
	} else 	if(window.XMLHttpRequest){ 
		// Support Firefox, Safari, Opera
		AJAXrequest = new XMLHttpRequest();		
		return AJAXrequest;
	} else {
		// Aucun support
		alert('Désolé, mais votre navigateur ne supporte pas la technologie AJAX. Nous vous conseillons d\'utiliser un de ces navigateurs compatibles : Mozilla Firefox, Microsoft Internet Explorer, Opera.');
		return false;
	}
}

function add_historik(url,destination){
	if( mt_historik[destination] ){		
		currentPage = mt_historik[destination].push(url) - 1;
		mt_historik[destination][0] = currentPage;
	}else{
		mt_historik[destination] = new Array() ;
		mt_historik[destination][0] = 1;
		currentPage = mt_historik[destination].push(url) - 1;
	}
	//~ document.write(	js_print_r(historik));
	//~ alert(js_print_r(mt_historik));	
	update_ajax_buttons(destination);
}

var ajaxR = '';

function mt_getPage(url,destination,chargingtxt,history){
	
	//~ if(chargingtxt != 0) chargingdiv = 1;
	
	//~ var destload = $(destination).empty().addClass('ajax-loading');
	if(chargingtxt != 0 ) show_chargement(chargingtxt,destination);
		
	if(history != 0) add_historik(url,destination);	
		
	ajaxR = new Ajax(url, {
		method: 'get',
		update: $(destination),
		onComplete: function() {
			//~ log.removeClass('ajax-loading');
			if(chargingtxt !=0 )  window.hide_chargement(destination);
			//~ if(window.ActiveXObject){  document.recalc() } ; // hack pour recalculer les effets css avec le hack IE7
			if(window.ActiveXObject){  
			//~ document.recalc() 
			setTimeout("document.recalc();",10);
			} ; // hack pour recalculer les effets css avec le hack IE7
			if(chargingtxt !=0 ) mt_ajax_form_parse(destination);
		}
		});
	
	var dummy= $time() + $random(0, 100);
	
	//~ setTimeout("ajaxR.request('"+dummy+"')",100); 
	setTimeout("ajaxR.request('"+dummy+"')",350);

}



/////////////////// AJAX.LoadPage  /////////////////////:

function writeHTML(htmlStream, div){
	//~ document.getElementById(div).innerHTML = htmlStream;
	if($(div)){
		//~ alert(div);
		$(div).setHTML(htmlStream);
	}
}

// A utiliser le moins possible, utiliser plutot le transfert en tache de fond avec postPage
function loadPage(url,div){
	
	if(document.getElementById(div)){
		var request = ajaxObject()
		request.open("POST", url, false);
		request.setRequestHeader("Content-Type", "text/html; charset=iso-8859-1");
		request.setRequestHeader("Content-Language", "fr");
		request.send(null);
		if(request.readyState == 4) {
			writeHTML(request.responseText, div);
			if(window.ActiveXObject){  document.recalc() } ; // hack pour recalculer les effets css avec le hack IE7
			hide_chargement();
			//writeHTML(viewed_pages.join(';---;') + '<br />'+currentPage,"footer"); //debug
		} else { 
			return false;
		}
	}
}


function getPage(url,destination,chargingdiv){
	mt_getPage(url,destination,chargingdiv);
}

var to_return = null;

function getPageContent(url,param){

	var last_id = post_requestS.push(ajaxObject()) - 1;
	
	var post_request = post_requestS[last_id];

	post_request.onreadystatechange = function(){
	      if (post_request.readyState == 4) {
		  if (post_request.status == 200) {
		     //alert(http_request.responseText);
		    to_return = post_request.responseText ;    
		    if(window.ActiveXObject){  document.recalc() } ; // hack pour recalculer les effets css avec le hack IE7
		  } else {
		     alert('Un problème est survenu, rendant le chargement de la page impossible. Veuillez essayer à nouveau.');
		  }
	      }else{
			//writeHTML(post_request.readyState,post_div);
	      }
	}
	post_request.open("POST", url, true);

	//post_request.setRequestHeader("Content-Type", "text/html; charset=iso-8859-1");
	post_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	//request.setRequestHeader("Content-Language", "fr");
	post_request.setRequestHeader("Content-length", param.length);
	post_request.setRequestHeader("Connection", "close");
	post_request.send(param);
		       
       return to_return ;
}


function mt_postPage(url,param,destination,chargingtxt){
	
	//~ if(chargingtxt != 0) chargingdiv = 1;
	//~ alert(param);
	var dummy= $time() + $random(0, 100);
	//~ url += dummy;
	//~ var destload = $(destination).empty().addClass('ajax-loading');
	div = destination ;
	if(chargingtxt != 0 ) show_chargement(chargingtxt,div);
		
		
	ajaxR = new Ajax(url, {
		method: 'post',
		data: param,
		update: $(div),
		onComplete: function() {
			//~ log.removeClass('ajax-loading');
			if(chargingtxt !=0 )  window.hide_chargement(div);
			if(window.ActiveXObject){  document.recalc() } ; // hack pour recalculer les effets css avec le hack IE7
			//~ if(chargingtxt !=0 ) mt_ajax_form_parse(div);
		}
		});
	
	
	
	//~ setTimeout("ajaxR.request('"+dummy+"')",100); 
	ajaxR.request();

}

function postPage(url,param,div,optional){
	mt_postPage(url,param,div,optional);
}

function mt_encodeParams(form_name){
	options = {};
	if(document.getElementById(form_name)){
		myForm = document.getElementById(form_name) ;
	}else if( document.forms[form_name]) {
		myForm = document.forms[form_name] ;
	}else if( document.forms['the_form']) {
		myForm = document.forms['the_form'] ;
	}else return;
	
	parametres = 'any=any';

	for(t=0; t<myForm.elements.length;t++){
		myElement = myForm.elements[t];
		if(myElement.name && myElement.value){
			if(myElement.type == 'radio' || myElement.type == 'checkbox' ){
				if(myElement.checked){
					//~ parametres += '&' + myElement.name + '=' + encodeURIComponent(myElement.value) ;
					options[myElement.name] = myElement.value ;
				}
			}else if(myElement.type == 'select-multiple'){
				for (var i=0; i<myElement.options.length; i++) {
					if (myElement.options[i].selected) {
						//selectedList.push(selectBox.options[i]);
						parametres += '&' + myElement.name + '=' + encodeURIComponent(myElement.options[i].value) ;
						options[myElement.name] = myElement.options[i].value ;
					}
				}
			}else{
				//~ parametres += '&' + myElement.name + '=' + encodeURIComponent(myElement.value) ;
				options[myElement.name] = myElement.value ;
			}
						
		}
			
	}
	
	self.location.hash="centre";
	
	//~ return encodeURI(parametres);
	return options ;
	
}


function getFormValue(form_name,box_name){
	theBoxValue = 0;
	if(document.getElementById(form_name)){
		myForm = document.getElementById(form_name) ;
	}else if( document.forms[form_name]) {
		myForm = document.forms[form_name] ;
	}else if( document.forms['the_form']) {
		myForm = document.forms['the_form'] ;
	}else return;
	
	for(t=0; t<myForm.elements.length;t++){
		myElement = myForm.elements[t];
		if(myElement.name && myElement.value && myElement.name == box_name){
			if(myElement.type == 'radio' || myElement.type == 'checkbox' ){
				if(myElement.checked){
					theBoxValue = myElement.value ;
					break;
				}
			}else{
				theBoxValue = myElement.value ;
				break;
			}
						
		}			
	}
	
	return theBoxValue;

}


function update_ajax_buttons(destination){
	
	if(mt_historik[destination]){
		//~ alert(mt_historik[destination][0]) ;	
		if(mt_historik[destination][mt_historik[destination][0]+1]){
			//si il y a une page suivante le bouton est accessible
			if(document.getElementById('ajax_suivant')){ // si l'element existe
				document.getElementById('ajax_suivant').className = "icone_ajax asuivant";		
			}
		}else{
			if(document.getElementById('ajax_suivant')){ // si l'element existe pas
				document.getElementById('ajax_suivant').className = "icone_ajax asuivant_disable";		
			}	
		}
		if(mt_historik[destination][mt_historik[destination][0]-1] && (mt_historik[destination][0]-1) != 0){
			// si il y a une page précédente le bouton est accéssible
			if(document.getElementById('ajax_precedent')){ // si l'element existe
				document.getElementById('ajax_precedent').className = "icone_ajax apreced";		
			}
		}else{
			if(document.getElementById('ajax_precedent')){ // si l'element existe pas 
				document.getElementById('ajax_precedent').className = "icone_ajax apreced_disable";		
			}	
		}
	}
	hideBox();
}


function getRefresh(destination){
	
	if(mt_historik[destination][mt_historik[destination][0]] && mt_historik[destination][0] != 0){
		//~ currentlink = mt_historik[destination].length;
		currentlink = mt_historik[destination][mt_historik[destination][0]];
		
		//~ alert(currentlink);
		
		//writeHTML(currentlink,"footer");
		
		if(currentlink != ''){
			//writeHTML('<img src="./img/connect_dot.gif" alt="" style="position:relative;top:-3px;float:right;" />Rafraîchissement ...<br /><br />',div);	
			//~ show_chargement('',destination);
			mt_getPage(currentlink,destination,'Chargement ...',0);
		}
		
		update_ajax_buttons();
	}
	
}

function getPreced(destination){
	
	history_num = mt_historik[destination][0]-1 ;	
	//~ alert(history_num);
	if(mt_historik[destination][history_num] && history_num != 0){
		gotolink = mt_historik[destination][history_num];
		mt_historik[destination][0] = history_num; 
		//~ currentPage = currentPage - 1;
		
		//writeHTML(gotolink,"footer");
		
		if(gotolink){
			//writeHTML('<img src="./img/connect_dot.gif" alt="" style="position:relative;top:-3px;float:right;" />Rafraîchissement ...<br /><br />',div);	
			//~ show_chargement('Page précédente en chargement ...',destination);
			mt_getPage(gotolink,destination,'Page précédente en chargement ...',0);
		}
	}
	
	update_ajax_buttons(destination);
}

function getSuivant(destination){

	history_num = mt_historik[destination][0]+1 ;	
	//~ alert(history_num);
	if(mt_historik[destination][history_num] && history_num != 0){
		gotolink = mt_historik[destination][history_num];
		mt_historik[destination][0] = history_num; 
	
		//writeHTML(gotolink,"footer");
		
		if(gotolink){
			//writeHTML('<img src="./img/connect_dot.gif" alt="" style="position:relative;top:-3px;float:right;" />Rafraîchissement ...<br /><br />',div);			
			//~ show_chargement('Page suivante en chargement ...',div);
			mt_getPage(gotolink,destination,'Page suivante en chargement ...',0);
		}
	}
	
	update_ajax_buttons(destination);
}
