function create_text_child(tag_name,text){
	var tag = document.createElement(tag_name);
	var txt_tag = document.createTextNode(text);
	tag.appendChild(txt_tag);
	return tag;
	}

// ajax.js V2 (joliment OO)
// écrit par Bernhard Rieder

function AjaxRequest(url,message,fonction_sortie,async) {

 	this.url = encodeURI(url);								// encode tous les caractères spéciaux
 	this.fonction_sortie = fonction_sortie;

	var ajaxRequest = this;

    if (window.XMLHttpRequest) {

	    this.req = new XMLHttpRequest();										// pour XMLHttpRequest natif (Gecko, Safari, Opera)

		try {
	    	netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");		// Pour ouvrir la sécurité de Mozilla
	   	} catch (e) {}

		this.req.onreadystatechange = function () { ajaxRequest.processReqChange(); }

    if(typeof(async)=="undefined")
      async=true;

		this.req.open("POST", this.url, async);
		this.req.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
	 	this.req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

	 	this.req.send(message);

		try {
	    	console.log("request: "+url);
	   	} catch (e) {}

	} else if (window.ActiveXObject) {

	    this.req = new ActiveXObject("Microsoft.XMLHTTP");						 // pour IE/Windows ActiveX

        if (this.req) {
            this.req.onreadystatechange = this.req.onreadystatechange = function () { ajaxRequest.processReqChange(); }
            this.req.open("POST", this.url, true);
			this.req.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT");
			this.req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

			this.req.send(message);
		}

    } else {

		alert("Votre navigateur ne connait pas l'objet XMLHttpRequest.");

	}

}

function curseur_to_load()
{
    if(typeof(document.getElementById('main'))!="undefined")
    document.getElementById('main').className='main_on_load';
}


function curseur_to_auto()
{
    if(typeof(document.getElementById('main'))!="undefined")
      document.getElementById('main').className='';
}

AjaxRequest.prototype.processReqChange = function() {

	try {
	   	console.log("state:"+this.req.readyState);
	} catch (e) {}
	if (this.req.readyState == 1) {
    //curseur en load
    curseur_to_load();
  }
	if (this.req.readyState == 4) {				// quand le fichier est chargé
    //curseur normal
    curseur_to_auto();
    if (true ) {			// detécter problèmes de format this.req.status == 200

			try {
    			netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
   			} catch (e) {}

			try {
	   			console.log(this.req.responseText);
			} catch (e) {}
			
			if(typeof(debug)!="undefined"&&debug==1)
			{
        document.getElementById('error').innerHTML=this.req.responseText;
      }

      eval(this.fonction_sortie+"(this.req)");

		} else {

			alert("Il y avait un probleme avec le XML: " + this.req.statusText);

		}
	}
}

// from http://sislands.com/coin70/week6/encoder.htm
function URLencode(str) {

str=clean_word_items(str);
var result = "";

//str=_to_utf8(_from_utf8(str));
//alert(str);
for (i = 0; i < str.length; i++) {
if (str.charAt(i) == " ") result += "+";
else result += str.charAt(i);
}

return(escape(result));
}


function clean_word_items(str)
{

	/**
	 * The array of MS Word characters to find for replacement
	 *
	 * @access protected
	 */
	this.arr_find = [
		String.fromCharCode(8220), //
		String.fromCharCode(8221), //
		String.fromCharCode(8216), //
		String.fromCharCode(8217), //
		String.fromCharCode(8211), //
		String.fromCharCode(8212), //
		String.fromCharCode(189), //½
		String.fromCharCode(188), //
		String.fromCharCode(190), //
		String.fromCharCode(169), //
		String.fromCharCode(174), //
		String.fromCharCode(8218), //
		String.fromCharCode(8222), //
		String.fromCharCode(710), //^
		String.fromCharCode(338), //OE
		String.fromCharCode(8226), //bullet
		String.fromCharCode(8482), //TM
		String.fromCharCode(339), //oe
		String.fromCharCode(8230) //




	];

	/**
	 * The array of standard string to replace MS Word characters in this.arr_find with
	 *
	 * @access protected
	 */
	this.arr_replace = [
		'"',
		'"',
		"'",
		"'",
		"-",
		"--",
		"1/2",
		"1/4",
		"3/4",
		"(C)",
		"(R)",
		"'",
		'"',
		"",
		"OE",
		"#",
		"TM",
		"oe",
		"..."
	];



		//Make sure find and replace have equal lengths
		if ( !(arr_find.length == arr_replace.length) ) {
			//throw new Error("The MS Word entities find values do not match the replacement values");
			alert("error in MS word function");
		}

		//Still here, then replacement rules are ok - loop across and do the replacement
		for ( var i=0; i<this.arr_find.length; i++ ) {
			var regex = new RegExp(this.arr_find[i], "gi");
			str = str.replace(regex, this.arr_replace[i]);

		}//for

		//Put the cleaned string into the output box
		return str;



}


var redirect_flag=1;

function redirect()
{
 // alert("redirect "+redirect_flag);
  if(redirect_flag==1)
  {  // RETOUR ARRIERE

   var initialLocation = window.location.hash.substring(1,window.location.hash.length);//unFocus.History.getCurrent();
   if (typeof initialLocation!="undefined"&&initialLocation!="") {
     decode_bookmark_hash(initialLocation);
   }
  }
}

function rien()
{return true;}

function send_request(file,args,hash)
{
   var cible=document.getElementById("content");
   cible.innerHTML="";
  document.getElementById('called_page').value=hash;
  document.getElementById('called_args').value=args;
  var envoi = new AjaxRequest(file,args+"&ajax=1","paste_to_content");
  //alert("envoi "+file+" "+args);
	//unFocus.History.addEventListener('historyChange',redirect);
  //redirect_flag=1;
  
   if(typeof(unFocus)!="undefined"&&hash!='')
  {
     redirect_flag=0;
    //alert("calling redirect... "+redirect_flag);
    unFocus.History.addHistory(hash);

  }
}

function send_xml(module_name,id,action,p,prefix,param_direct)
{
  if (typeof prefix == "undefined")
    var prefix="";
  if (typeof param_direct == "undefined")
    var param_direct="";
//	root=document.createElement('module');
//	root.appendChild(create_text_child('name',module_name));
//	root.appendChild(create_text_child('id',id));
//	root.appendChild(create_text_child('action',action));
//	var params=document.createElement('params');
//	params.appendChild(create_text_child('titre','mon premier événement'));
//	root.appendChild(params);
	var root ="<message><request><module>"+module_name+"</module><id>"+id+"</id><action>"+action+"</action>";
	var nb=p.length;
	//alert(p[1]);
	if(nb>0)
	{
		//alert(p.length);
		var i=0;
		while(i<nb)
		{
			var param_name=p[i];
		//alert(prefix+" "+param_name);
			//if(id!="")
			//	param_name=id+"_"+p[i];
			var input =document.getElementById(prefix+param_name);
			
			if(input.tagName=="TEXTAREA")
      {
//         if(input.className=="mceEditor")
//         {
 //           tinyMCE.execCommand("mceRemoveControl", true,input.id);
            tinyMCE.triggerSave(1,1);
             // alert("removing :"+input.id+" "+tinyMCE.idCounter);

       // }
        //alert(input.value);}
			}
			
			var value=input.value;
			//préparer la valeur suivant le type (checkbox)
			if(input.type=='checkbox')
			{
			//	alert(value);
				if(input.checked)
					value="1";
				else
					value="0";
				//alert(value);
			}
			//root=root+"<param var='"+p[i]+"'><![CDATA["+URLencode(value)+"]]></param>";
      //encodeURIComponent
      root=root+"<param var='"+p[i]+"'><![CDATA["+encodeURIComponent(value)+"]]></param>";
      i++;
		}
	}
	for(var clef in param_direct)
   root=root+"<param var='"+clef+"'><![CDATA["+encodeURIComponent(param_direct[clef])+"]]></param>";
    

	root=root+"</request></message>";
//	alert(root);
//	document.getElementById('content').appendChild(root);
  //unFocus.History.removeEventListener(redirect);
 

  //unFocus.History.addEventListener('historyChange',redirect);
	var envoi = new AjaxRequest(url,"xml="+root,"traiter_reponse");
	//unFocus.History.addEventListener('historyChange',redirect);
  //redirect_flag=1;
  
   if(typeof(unFocus)!="undefined")
  {
    var date=param_direct['date'];
    var hash=encode_bookmark_hash(window.location.hash.substring(1,window.location.hash.length),module_name,action,id,date);
    redirect_flag=0;
    //alert("calling redirect... "+redirect_flag);
    unFocus.History.addHistory(hash);

  }
  
  
}



function getPageSizeWithScroll(){
	if (window.innerHeight && window.scrollMaxY) {// Firefox
		yWithScroll = window.innerHeight + window.scrollMaxY;
		xWithScroll = window.innerWidth + window.scrollMaxX;
	} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
		yWithScroll = document.body.scrollHeight;
		xWithScroll = document.body.scrollWidth;
	} else { // works in Explorer 6 Strict, Mozilla (not FF) and Safari
		yWithScroll = document.body.offsetHeight;
		xWithScroll = document.body.offsetWidth;
  	}
	arrayPageSizeWithScroll = new Array(xWithScroll,yWithScroll);
	//alert( 'The height is ' + yWithScroll + ' and the width is ' + xWithScroll );
	return arrayPageSizeWithScroll;
}




function encode_bookmark_hash(last_hash,module_name,method_name,id,date_old)
{
 var reg=new RegExp("[-]+", "g");
  hash_array=last_hash.split(reg);
  var id_new="";
  var date_new="";
  var method_new="";
  var module_name_new="";
  switch(hash_array.length)
  {
    case 4: id_new=hash_array[3];
    case 3: date_new=hash_array[2];
    case 2: method_new=hash_array[1];
    case 1: module_name_new=hash_array[0];
  }
//  alert("'"+last_hash+"' "+hash_array[0]);
  switch(module_name)
  {
    case "Agenda" :
      module_name_new="Agenda";

      switch(method_name)
      {
        case "next":
          if(typeof date_old=="undefined")
            date_new="n"+document.getElementById("end_date").value;
          else
            date_new="n"+date_old;
          id_new="";
          break;
        case "prev":
          if(typeof date_old=="undefined")
            date_new="p"+document.getElementById("start_date").value;
          else
            date_new="p"+date_old;
          id_new="";
          break;
        case "open_up_special":
          id_new="o"+id;
          break;
        default :
          if(method_name.indexOf("get_")!=-1)
          {
            var aujourdhui=new Date();
            var j= aujourdhui.getDate();
            if(j<=9)
              j="0"+j;
            var m= aujourdhui.getMonth();
            if(m<=8)
              m="0"+(m+1);
            var y= aujourdhui.getFullYear();
            date_new="n"+j+m+y;
            id_new="";
            method_new=method_name.substring(method_name.indexOf("_")+1,method_name.length);
          }
      }
      break;
    case "Static_part":
      module_name_new="Agenda";
      method_new=method_name.substring(method_name.indexOf("_")+1,method_name.length);
      date_new="";
      id_new="";
      break;
    case "Event","Document":

      switch(method_name)
      {
        case "get":
          id_new=id;
          break;
        case "get_special":
          id_new='s'+id;
          break;
        case "get_short":
          id_new="";
          break;
      }
  }
  var pole="";
  if(pole_image==1)
    pole="- éducation à l'image ";
  var titre=window.document.title;
  if(method_new!='all')
    titre="Lux° "+pole+"- "+method_new
  else
    titre="Lux° "+pole+"- agenda";

  

  if(id!="")
  {
   // alert("event_"+id);
   if(method_name=='Event')
     var t=document.getElementById("event_"+id).getElementsByTagName('big')[0].innerHTML;
   else
    var t=document.getElementById("document_"+id).getElementsByTagName('big')[0].innerHTML;

    titre="Lux° "+pole+"- "+t;
  }
  window.document.title=titre;
  return module_name_new+"-"+method_new+"-"+date_new+"-"+id_new;

}

var xml_request_queue=new Array();

function decode_bookmark_hash(hash)
{

  //alert("decoding.. "+hash);
  var reg=new RegExp("[_]+", "g");
  hash_array=hash.split(reg);
  //alert(hash_array.length);

  var arg_new="";
  var page_new="";
  switch(hash_array.length)
  {
    case 4: arg_final=hash_array[3];
    case 3: arg_plus=hash_array[2];
    case 2: arg_new=hash_array[1];
    case 1: page_new=hash_array[0];
  }
  switch(page_new)
  {
    case 'projet' :
        open_colonne("colonne_"+arg_plus);
        //send_request("colonne.php","colonne="+arg_plus,'');
        send_request("projet.php","id_projet="+arg_new+"&id_cat="+arg_plus,hash);
        
        break;
    case 'colonne' :
        open_colonne("colonne_"+arg_new);
        send_request("colonne.php","cat="+arg_new,hash);
        break;
    case 'in' :
        hover_colonnes(0);
        if(arg_new=="undefined")
          arg_new='';
        light_statics(arg_new);
        send_request("in.php",'',hash);
        break;
    default :
        if(arg_new=="undefined")
          arg_new='';
        
        open_static(hash,arg_new);
        if(arg_new!="")
          arg_new="_"+arg_new;
        send_request(hash+arg_new+".php","",hash);
       
        break;
  }
  
 
  

}



function traiter_reponse(req)
{
   if(req.responseXML.documentElement==null)
      {
       alert("ie bug");
        var buffer = document.createElement('div');
        var rep= req.responseText;
        //alert(rep);
        var reponses="";
        var i=0;
        while(rep.indexOf("<response>")!=-1)
        {
         reponses=rep.substring(rep.indexOf("<response>")+10,rep.indexOf("</response>"));
         var tag_id=reponses.substring(reponses.lastIndexOf("<tag_id>")+8,reponses.lastIndexOf("</tag_id>"));
         var html=reponses.substring(reponses.indexOf("<content><![CDATA[")+18,reponses.indexOf("]]></content>"));
        // alert(tag_id+"  "+html);
         if(document.getElementById(tag_id)!=null)
          document.getElementById(tag_id).innerHTML=html;
         rep=rep.substring(rep.indexOf("</response>")+11,rep.length);
        //alert(rep);
        i++;
        }
     
      }
      else
     {
        responses=req.responseXML.documentElement.getElementsByTagName('response');


  //var responses = answer.getElementsByTagName('response');
 //alert("enter traiter reponse : "+responses.length);
  for(i=0;i<responses.length;i++)
  {

    var r=responses[i];
    if(r.getElementsByTagName('tag_id')[0].hasChildNodes())
    {
      var id=r.getElementsByTagName('tag_id')[0].firstChild.data;
      var cible=document.getElementById(id);
      //alert("messages (c normal) pour Paul "+id);
      if(cible==null)
      {
           //alert(null);
           //alert("message pour Paul");
           cible=document.createElement('DIV');
           cible.id=id;
           document.getElementById('main').appendChild(cible);
      }

      if(r.getElementsByTagName('content')[0].hasChildNodes())
      {
        unload_tiny(cible.id);
        cible.innerHTML=r.getElementsByTagName('content')[0].firstChild.data;
        load_tiny(cible.id);

        if(typeof(cible.onload)!="undefined")
        {
         // alert(cible.onload);
          window.setTimeout(cible.onload,500);
        }

      }else
      {

        cible.innerHTML="&nbsp";
      }
      if(r.getElementsByTagName('css_class')[0].hasChildNodes())
        cible.className=r.getElementsByTagName('css_class')[0].firstChild.data;
      if(r.getElementsByTagName('js')[0].hasChildNodes())
      {
         // alert(r.getElementsByTagName('js')[0].firstChild.data);
              eval(r.getElementsByTagName('js')[0].firstChild.data);
      }
    }
    else
    {
      alert("message pour Paul");
      cible.innerHTML="&nbsp";
    }

  }
  //lancement des requêtes mises en queue
  if(xml_request_queue.length>0)
  {
    //alert(xml_request_queue.length);
    var xml=xml_request_queue.shift();
    //alert(xml_request_queue.length);
    //if(window.confirm(xml))
    eval(xml);
  }
 
  //mise à jour hauteur main
  update_main_height();
  call_sifr();
  redirect_flag=1;
// else
//   alert("erreur");
	//alert(response.getElementsByTagName('html')[0].firstChild.data);
	}
}


function paste_to_content(req)
{
//alert("'"+req.responseText+"' location : "+document.location);
// if(req.responseText!="reload")
// {
  var cible=document.getElementById("content");
  cible.innerHTML=req.responseText;
  content_focus();
  redirect_flag=1;
// }else
//   window.setTimeout(redirect,500);
 // redirect();
//   alert("erreur");
	//alert(response.getElementsByTagName('html')[0].firstChild.data);
	
}
