/* ajax.js : regroupe les scripts AJAX @date 11-2007 */

var Utf8 = {

    // public method for url encoding
    encode : function (string) {
        string = string.replace(/\r\n/g,"\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // public method for url decoding
    decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }

};

var xhr = null;
var mAjax = {

	testalert: function (){
		alert('Hello world !!');
	},

	getXhr: function (){
		if(window.XMLHttpRequest) /* Firefox et autres */
		xhr = new XMLHttpRequest();
		else if(window.ActiveXObject){ /* Internet Explorer */
			try {
				xhr = new ActiveXObject("Msxml2.XMLHTTP");
			} catch (e) {
				xhr = new ActiveXObject("Microsoft.XMLHTTP");
			}
		}
		else { /* XMLHttpRequest non supporté par le navigateur */
			alert("Votre navigateur ne supporte pas les objets XMLHTTPRequest...");
			xhr = false;
		}
	},

	/* Node cleaner */
	go: function(c){
		if(!c.data.replace(/\s/g,''))
		c.parentNode.removeChild(c);
	},

	cleanXML: function(d){
		var bal=d.getElementsByTagName('*');

		for(i=0;i<bal.length;i++){
			a=bal[i].previousSibling;
			if(a && a.nodeType==3)
			mAjax.go(a);
			b=bal[i].nextSibling;
			if(b && b.nodeType==3)
			mAjax.go(b);
		}
		return d;
	},

	/* Gestion formulaire */
	ajaxForm: function(form){
		mAjax.getXhr();
		/* On défini ce qu'on va faire quand on aura la réponse */
		xhr.onreadystatechange = function(){
			if(xhr.readyState == 4 && xhr.status == 200){

				var response = mAjax.cleanXML(xhr.responseXML.documentElement);
				var items = response.getElementsByTagName("error");

				var count = response.getElementsByTagName("count")[0].firstChild.nodeValue;
				if(count == 0){
					document.location = "../accueil/";
					return true;
				}

				for(i = 0; i < count; i++) { /* POUR CHAQUE item */
					field = items[i].getElementsByTagName("field")[0].firstChild.nodeValue;
					document.getElementById("lb_"+field).className = "simple_error";
					document.getElementById(field).onchange = function(){document.getElementById("lb_"+this.name).className = "";};
					// html += '<h1>' + items[i].getElementsByTagName("title")[0].firstChild.nodeValue + '</h1>'
				}
				// alert(xhr.responseText);

				document.getElementById("formerror").innerHTML = "une erreur de saisie a été détectée.";
				new Fx.Scroll(window).toElement($('formerror'));
				return false;
			}
		}

		xhr.open("POST",'../ajax/',true);
		xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded; charset=ISO-8859-1');

		/* récupération des champs via la propriété elements. */
		elts = form.elements;
		for(var s="",i=0;i<elts.length;i++){
			if(elts[i].type == 'checkbox') s += "&"+elts[i].id+"="+elts[i].checked;
			else s += "&"+elts[i].id+"="+elts[i].value;
		}
		// alert(s);
		xhr.send(s);
		//xhr.send(s+"&ajax=1");
	},

	/* Chargement ajax d'une page à partir de son URL */
	loadURL: function(url){
		mAjax.getXhr();
		/* On défini ce qu'on va faire quand on aura la réponse */
		xhr.onreadystatechange = function(){
			try{
				if(xhr.readyState == 4 && xhr.status == 200){
					var response = mAjax.cleanXML(xhr.responseXML.documentElement);
					var content = response.getElementsByTagName('content');  // content = NodeList
					var message = response.getElementsByTagName('message');  // content = NodeList
					var id_page = response.getElementsByTagName('page');  // id_page = NodeList
					var fil = response.getElementsByTagName('fil');  // fil = NodeList
					//var id_page = response.getElementsByTagName('id_page');  // id_page = NodeList
					var javascript = response.getElementsByTagName('javascript');  // javascript = NodeList
					var data = "";
								
					// le résultat est contenu dans tous les fils noeuds fils (Une NodeList avec des type Node)
					for (var i = 0; i < content[0].childNodes.length ; i++)
					{
						data += content[0].childNodes[i].nodeValue;
					}
					
					// le premier élément est un type 1 (Element_Node) dont le contenu est dans ses fils (le premier est le texte)
					if(message[0].childNodes.length > 0)
						document.getElementById('message').innerHTML = message[0].firstChild.nodeValue + "&nbsp;"; // pour que la div (id='message') ne s'efface pas
					
					document.getElementById('ariane').innerHTML = fil[0].firstChild.nodeValue;
					document.getElementById('centre').innerHTML = data;
					
					// mSite.menu(document.getElementById('men'+id_page[0].firstChild.nodeValue));
					if(document.getElementById('men'+id_page[0].firstChild.nodeValue))
						document.getElementById('men'+id_page[0].firstChild.nodeValue).className = 'arighton';
											
					// document.getElementById('men'+id_page[0].firstChild.nodeValue).className = 'arighton';  // re-affichage du menu principal
					mSite.restart(javascript[0].firstChild.nodeValue); // re-start des effets graphiques
				}
			}
			catch(e){
				alert('Une erreur est survenue : '+e);
			}
		}
		xhr.open("POST",url,true);
		xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded; charset=UTF-ISO-8859-1');
		// xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded; charset=utf-8');
		xhr.send("&ajax=1");
	},
	
	/* Exécution d'une action à partir de son nom*/
	doPanier: function(url){
		mAjax.getXhr();
		/* On défini ce qu'on va faire quand on aura la réponse */
		xhr.onreadystatechange = function(){
			try{
				if(xhr.readyState == 4 && xhr.status == 200){					
					var response = mAjax.cleanXML(xhr.responseXML.documentElement);
					var message = response.getElementsByTagName('message');  // content = NodeList
					var panier = response.getElementsByTagName('panier');  // content = NodeList

					document.getElementById('message').innerHTML = message[0].firstChild.nodeValue;
					document.getElementById('panier').innerHTML = panier[0].firstChild.nodeValue;
				}
			}
			catch(e){
				alert('Une erreur est survenue : '+e);
			}
		}
		xhr.open("POST",url,true);
		xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded; charset=UTF-ISO-8859-1');
		xhr.send("&ajax=1");
	}
};
