/*
	ObjAJAX = new PAjax();
	ObjAJAX.setParam ({
						url          : url_retour,
						returnFormat : Format('txt' || 'xml'),
						method       : method('POST' || 'GET'),
						data         : 'value=1&id=12',
						asynchronus  : true || false,
						onComplete   : retour || function appler a la fin de la requete recoit la reponse soit au format TXT soit au format XML,
						debug		 : false || true ouvre une popup avec le resulat de la requete ajax});
	ObjAJAX.execute(); */

document.write( '<s'+"cript src='/js/Box.Mask.js' type='text/javascript'></s"+'cript>' );


var PAJAX = new Object();
    PAJAX.iAjax = 1;
    PAJAX.objs  = {};

function PAjax_Kill( iAjax )
{                             if( typeof(iAjax) != 'string' )  iAjax = iAjax.iAjax;

         var oAjax = PAJAX.objs[iAjax]; if( ! oAjax ) return;
         PAjax_KillTimer( oAjax );

         if( oAjax.mask ) {
            if( typeof(oAjax.mask) == 'string' ) BMask_set(0, oAjax.mask); else BMask_set(0);
         }
         oAjax.obj = null; delete PAJAX.objs[iAjax];

}

function PAjax_KillTimer( oAjax )
{
         if( oAjax && oAjax.TimerRetour )
         {   
             try{ clearTimeout( oAjax.TimerRetour ); } catch(e){}
             oAjax.TimerRetour = null;
         }
}

function getCaller(rawCaller)
{
	rawCaller = rawCaller.toString();
	if (rawCaller == null)
		return "";
	return rawCaller.substring(rawCaller.indexOf("function ") + 9,rawCaller.indexOf("(")).replace(" ","");
}

function PAjax( url, data )
{
	this.data = data || '';
	this.url  = url || '';
	this.init();
}

PAjax.prototype =
{
     iAjax:0,
     asyn : true,
     url : '',
     data : '',
     method : 'POST',
     returnFormat : 'txt',
     kook : false, // 0/false | 1/true | 'alert' | 'auto'
     obj : null,
     debug : (window.PAjax_DebugNous)? 'errors' : false,
     maxTime : 10, // délai maximal en seconde ( 0 si pas de limite )
     mask : ''  // cf. /js/BoxI.js;
}

PAjax.prototype.init = function()
{
    this.obj = null;
    if (window.XMLHttpRequest)
        this.obj = new XMLHttpRequest();
    else if (window.ActiveXObject)
    {
        var ieversions = ['Msxml2.XMLHTTP','Microsoft.XMLHTTP','Msxml2.XMLHTTP.5.0','Msxml2.XMLHTTP.4.0','Msxml2.XMLHTTP.3.0'];

        for(var i=0; !this.obj && i<ieversions.length; i++)
        {
		    try
			{
		        this.obj = new ActiveXObject(ieversions[i]);
			}
			catch(e)
			{
			}
        }
    }
}

PAjax.prototype.onFailure = function (errorCode){} // func_name | 'alert' | 'auto'

PAjax.prototype.onComplete = function (response){}

PAjax.prototype.setParamFromForm = function (obj)
{
	if (!isNaN(obj))
		obj = document.forms[obj];

	if (typeof obj == "string")
		eval("obj = document."+obj);
	
	//if (!isset(obj))
	//	return ErreurObj("Donnée Invalide");
	
	//this.method = (isset(obj.method) && (["GET","POST"].inArray(obj.method.toUpperCase()))) ? obj.method.toUpperCase() : this.method;
	this.url = obj.action;
	
	for (i=0;i<obj.elements.length;i++)
	{
		//if (["file","button","reset","submit"].inArray(obj.elements[i].type.toLowerCase()))
		//continue;
		if (this.data != null)
		this.data += "&";
		
		this.data += obj.elements[i].name + "=" + escape(obj.elements[i].value);
	}
}

PAjax.prototype.setParam = function (arr)
{
	if (typeof arr != "object" && !isset(arr))
		return ErreurObj("Donnée Invalide");

	for(k in arr)
	{
		switch (k)
		{
			case "url" :
				this.url = arr[k];
				break;
			
			case "debug" :
				this.debug = arr[k];
				break;
			
			case "method" :
				this.method = arr[k].toUpperCase();//(["GET","POST"].inArray(arr[k].toUpperCase())) ? arr[k].toUpperCase() : this.method;
				break;
			
			case "data" :
				if (typeof arr[k] == "string")
				{
					if (this.data != "")
					this.data += "&";
					this.data += arr[k];
				}
				else
				{
					if (typeof arr[k] != "object")
					break;
					
					for (j in arr[k])
					{
						if (this.data != "")
						this.data += "&";
						this.data += j + "=" + escape(arr[k][j]);
					}
					
				}
				break;
			
			case "asynchronus" :
				this.asyn = arr[k];
				break;
			
			case "onComplete" :
				this.onComplete = arr[k];
				break;
			
			case "onFailure" :
				this.onFailure = arr[k];
				break;

			case "returnFormat" :
				this.returnFormat = arr[k];
				break;
		}
	}
}

PAjax.prototype.execute = function (iso)
{
        this.obj.open(this.method,this.url,this.asyn);

        var cType  = 'application/x-www-form-urlencoded';
                   if( iso )  cType += '; charset=iso-8859-1';
	this.obj.setRequestHeader( 'Content-Type', cType );

        if( iso ) this.data += '&iso=true';

        var iAjax = 'o'+PAJAX.iAjax;  PAJAX.iAjax++;
        this.iAjax = iAjax;
        PAJAX.objs[iAjax] = this;
        //try{ this.obj.iAjax = iAjax } catch(e){};
        if(this.mask) { if( typeof(this.mask) == 'string' ) BMask_set(1, this.mask); else BMask_set(1); }

        if (this.asyn)
	{
                _tmp_iAjax_ = iAjax;// pour FF && IE6

		this.obj.onreadystatechange = function()
                {
                        var iAjax = ( this == undefined || !this.iAjax ) ? _tmp_iAjax_ : this.iAjax;

                        var oAjax = PAJAX.objs[iAjax];  if( ! oAjax ) return; if( ! oAjax ) return;
                        var obj   = oAjax.obj;

                        if( obj.readyState !== 4 ) return;

                         var done=0; PAjax_KillTimer( oAjax );

                        if( obj.status == 200 )
			{
                            if( PAjax_Retour_200( oAjax ) !== '**wait...**' ) done=1;
			}
			else // status <> 200
			{
			    if( PAjax_onFailure( oAjax ) !== '**wait...**' )  done=1;
			}

                        if( done ) PAjax_Kill(iAjax);

                }
                if(this.maxTime) { this.TimerRetour = setTimeout( 'PAjax_Delai_OverPassed("'+iAjax+'")', 1000 * this.maxTime ); }

                PAjax_Envoi(this);
	}
	else
	{
                PAjax_Envoi(this);
                
                var done = 0; var res = null;

                if (this.obj.status == "200")
		{
                    res = PAjax_Retour_200( this );
                    done = 1;
                        /*
                        if (this.debug == true)
			{
				response = this.obj.responseText;
				ObjPOPUP = new PPopup();
				ObjPOPUP.execute();
				ObjPOPUP.write(response);
				return;
			}
			if (this.returnFormat != "txt")
				response = this.obj.responseXML;
			else
				response = this.obj.responseText;

			this.response  = response;
                        this.errorCode = 0;
                        if (typeof this.onComplete == "string")
				eval (this.onComplete);
			else
				this.onComplete( response );
			*/
		}
		else
		{       
			if( PAjax_onFailure( this ) !== '**wait...**' )  done=1;
                        /*
                        this.response = null;
			errorCode = this.obj.status;
			this.errorCode = errorCode;
			if (typeof this.onFailure == "string")
				eval (this.onFailure);
			else
				this.onFailure(errorCode);
			*/
			
		}
	        
                if( done ) PAjax_Kill( this.iAjax );
                
                return res;
	}
	
}

function PAjax_Envoi( oAjax )
{
         oAjax.obj.send(oAjax.data);
}

function PAjax_Retour_200( oAjax )
{
	 var obj = oAjax.obj;
         var response = (oAjax.returnFormat == 'txt')? obj.responseText : obj.responseXML;
         var res = null;
         var err = null;
         var typ = null;

         if( oAjax.debug == true && oAjax.debug !== 'errors' )
	 {
		response = obj.responseText;
		ObjPOPUP = new PPopup();
		ObjPOPUP.execute();
		ObjPOPUP.write(response);
	 }

         if (typeof oAjax.onComplete == 'string')
		eval (oAjax.onComplete);
	 else
         {
               if( oAjax.kook )
               {
                   var res = response.replace(/^\s+/, ''); // <=> ltrim()
                   var typ = res.slice(0,4); var err, nb_rq;
                                                 
                    switch( typ )
                    {
                        case 'Ok: ' : { typ='ok'; err=0; break; }   // = ok
                        case '00: ' : { typ='00'; err=0; break; }   // = void
                        case 'Rq: ' : { typ='rq'; err=0; nb_rq='Remarque'; break; }   // = info : attention
                        case 'Nb: ' : { typ='nb'; err=0; nb_rq='Attention'; break; }   // = info : remarque
                        case 'Ko: ' : { typ='ko'; err=1; break; }   // = Erreur gérée
                        default     : { typ='??'; err='??'; break; } // = Erreur de script
                    }
                    if( err )
                    {
                        if( err === '??' ) err = "Erreur inconnue" ;
                        else err = res.slice(4) || '(chaîne vide)';
                    }
                    else res = res.slice(4);
        
                    if( ( err || nb_rq ) && ( oAjax.kook == 'alert' || oAjax.kook == 'auto' ) )
                    {
                             if( err )  PAjax_Error_Info( "Une erreur est survenue :\n\n"+err, oAjax, res );
                        else if( nb_rq )  alert(nb_rq+":\n\n"+res)
                        if( oAjax.kook == 'auto' ) { PAjax_Kill(oAjax.iAjax); return; }
                    }

                    if( oAjax.onComplete )  oAjax.onComplete(err, typ, res, oAjax, obj);
               }
               else if( oAjax.onComplete )  oAjax.onComplete(response, oAjax, obj);
         }

         if( ! oAjax.async )
         {
               if( ! oAjax.kook ) res = response;
               oAjax.res_err  = err;
               oAjax.res_typ  = typ;
               oAjax.response = res;
         }

         return res;
}


function PAjax_Error_Info( txt_alert, oA, res )
{
         if( ! oA.debug ) { alert(txt_alert); return; }
    else if( ! confirm( txt_alert+ "\n\nSouhaitez-vous afficher les informations relatives à l'erreur ?" ) ) return;

     // popup log
        var wErr = window.open('','','top=10,left=10,width=650,height=350,scrollbars=1,resizable=1');
            wErr.document.title = 'Error information';
        var data = oA.data;
            data = data.replace(/=/g, '<a class=blue>=</a>' );
            data = data.replace(/&/g, '<a class=ros>&</a>' );

        var HTM = "<meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1' />"
                + "<style>\r\n* {font-size:11; font-family:verdana;} FIELDSET {padding:6; margin:2} legend {font-weight:bold} .blue {color:blue} .ros {color:#FF59FF}\r\n</style>"
                + "Erreur [<a style='color:blue'>"+oA.url+"</a>]\r\n\r\n"
                + "<FIELDSET><legend>xmlHTTP -> data</legend>\r\n"+data+"\r\n</FIELDSET>\r\n\r\n"
                + "<PRE>"+ res +"\r\n</PRE>" ;

        if(document.all) wErr.document.write( HTM ); else wErr.document.body.innerHTML = HTM ;
        wErr.focus();
}


function PAjax_onFailure( oAjax, isTimeOver )
{                                              // a priori impossible ( cf. readyState == 4 -> if(this.aborted) return )
         
         var error = (isTimeOver)? '...' : oAjax.obj.status;

         if( typeof(oAjax.onFailure) == 'string' )
	 {
            if ( oAjax.onFailure == 'auto' || oAjax.onFailure == 'alert' )
	    {
                error = ( error === '...' ) ? "Délai d'attente-retour dépassé\n(problème sur le réseau)\n\nVeuillez essayer à nouveau" : '('+error+') '+oAjax.obj.statusText; //get_PAjax_Error(errorCode);
                if(oAjax.onFailure == 'auto') { alert( "Erreur HTTP : "+error ); return; }
                if( oAjax.onComplete )
                {
                  if( oAjax.kook )  oAjax.onComplete(1, '!!', error, oAjax);
                  else              oAjax.onComplete('!!', oAjax, oAjax.obj);
                }
	    } else eval( oAjax.onFailure );
         }
	 else oAjax.onFailure( error );
}

function PAjax_Delai_OverPassed( iAjax )
{                                            // alert('PAjax_Delai_OverPassed\n\n'+ iAjax + ' -> '+ PAJAX.objs[iAjax]);
         var oAjax = PAJAX.objs[iAjax];
         PAjax_KillTimer( oAjax );
             if( ! oAjax ) return; // <=> détruit <=> le retour a déjà été effectué
             oAjax.obj.onreadystatechange = function(){};
             oAjax.obj.abort();
         if( PAjax_onFailure( oAjax, 1 ) != '***for...wait***' ) PAjax_Kill( iAjax );
}

/*
function get_PAjax_Error( errCode )
{
   switch( errCode )
   {
       case '...' : { return "Délai d'attente-retour dépassé";} // cf. PAjax   : maxTime ->  PAjax_Delai_OverPassed()
       case 100   : { return 'Continue';}
       case 101   : { return 'Switching protocols';}
       case 200   : { return 'OK';}
       case 201   : { return 'Created';}
       case 202   : { return 'Accepted';}
       case 203   : { return 'Non-Authoritative Information';}
       case 204   : { return 'No Content';}
       case 205   : { return 'Reset Content';}
       case 206   : { return 'Partial Content';}
       case 300   : { return 'Multiple Choices';}
       case 301   : { return 'Moved Permanently';}
       case 302   : { return 'Found';}
       case 303   : { return 'See Other';}
       case 304   : { return 'Not Modified';}
       case 305   : { return 'Use Proxy';}
       case 307   : { return 'Temporary Redirect';}
       case 400   : { return 'Bad Request';}
       case 401   : { return 'Unauthorized';}
       case 402   : { return 'Payment Required';}
       case 403   : { return 'Forbidden';}
       case 404   : { return 'Not Found';}
       case 405   : { return 'Method Not Allowed';}
       case 406   : { return 'Not Acceptable';}
       case 407   : { return 'Proxy Authentication Required';}
       case 408   : { return 'Request Timeout';}
       case 409   : { return 'Conflict';}
       case 410   : { return 'Gone';}
       case 411   : { return 'Length Required';}
       case 412   : { return 'Precondition Failed';}
       case 413   : { return 'Request Entity Too Large';}
       case 414   : { return 'Request-URI Too Long';}
       case 415   : { return 'Unsupported Media Type';}
       case 416   : { return 'Requested Range Not Suitable';}
       case 417   : { return 'Expectation Failed';}
       case 500   : { return 'Internal Server Error';}
       case 501   : { return 'Not Implemented';}
       case 502   : { return 'Bad Gateway';}
       case 503   : { return 'Service Indisponible';}
       case 504   : { return 'Gateway Timeout';}
       case 505   : { return 'HTTP Version Not Supported';}
       case 12031 : { return "La connexion a été réinitialisée"; }
       case 12152 : { return "La réponse du serveur HTTP ne contenait pas de données HTML"; }
   }
   return "Code d'erreur inconnu";

}
*/
