/*
	JBHR 2008 Ajax functions
*/

function createXMLHttpRequest() {
   try { return new XMLHttpRequest(); } catch(e) {}
   try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {}
   try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {}
   alert("XMLHttpRequest not supported");
   return null;
}


function xhr_call() {
	
	xhr = createXMLHttpRequest();
	
	xhr.onreadystatechange = function() {
		
		if (xhr.readyState != 4) {
			return;
		}
		
		clearTimeout(requestTimer);
		
		if (xhr.status != 200) {
			if (xhr.status > 0) {
				alert("Status error: "+xhr.status);
			}
			// on affiche la réponse reçue pour debugger
			return;
		}
		
		// Le serveur a répondu ok
		var xml = xhr.responseXML.documentElement;
		// Lecture du xml de la réponse du serveur
		if (!xml || !xml.childNodes[0].firstChild) {
			// Si le xml est mal formé ou absent c'est qu'il y a sans doute une erreur de syntaxe
			alert(xhr.responseText);
			// on affiche la réponse reçue pour debugger
			return;
		}
		
		for (var i=0; i < xml.childNodes.length; i++) {
			// Pour chaque noeud xml on décode les actions renvoyées
			if (xml.childNodes[i].firstChild) {
				var data = xml.childNodes[i].firstChild.data;
			}
			for (var j=0; j < xml.childNodes[i].attributes.length; j++) {
				if (xml.childNodes[i].attributes[j].name == "type") {
					var type = xml.childNodes[i].attributes[j].value;
				} else if (xml.childNodes[i].attributes[j].name == "id") {
					var id = xml.childNodes[i].attributes[j].value;
				}
			}
			
			switch( type ) {
				// En fonction du type d'action renvoyée, on execute l'action sur la page web
				case 'assign' :
					document.getElementById( id ).innerHTML = data;
					// Modifie  en dom le contenu de la balise html id par la chine assignée par la fonction xhr_assign
					break;
				case 'script':
					eval(data);
					// on execute le javascript dans le cas d'un xhr_script
					break;
			}
		}
	}
	
	var xhr_uri = '/xhr_ws.php?xhr_func='+encodeURIComponent(arguments[0]);
	// Construction de l'url get, encodage du nom de la fonction serveur
	
	for (i=2; i < arguments.length; i++) {
		xhr_uri += '&xhr_args[]=' + encodeURIComponent(arguments[i]);
		// puis encodage des paramètres variables
	}
	
	xhr.open ('GET', xhr_uri, true);
	// ouverture de la requete en mode asynchrone
	
	var alt_url = arguments[1];
	
	// 3 seconds timeout
	var requestTimer = setTimeout(function() {
		xhr.abort();
		// Handle timeout situation
		if (alt_url != null && alt_url.length) {
			document.location.href = alt_url;
		} else {
			alert('Erreur: pas de réponse');
		}
     }, 2500);
	
	xhr.send(null);
	// envoi de la requete
	
}

