var TYPE_LOAD_NONE=0;
var TYPE_LOAD_GLOBAL=1;
var TYPE_LOAD=2;
var LOADCOUNT=0;
var AC_EVAL="eval";
var AC_VALUE= "value";
var AC_INNER="inner";
var AC_ALERT="alert";
var AC_FCT="function";
var AC_METHOD="methode";
var AC_REPLACE="replace";
var AC_JS="innerDivJs";
var AC_MESSAGE = "showMessage";
var AC_WOPEN = "windowopen";
var AC_DEBUG = "acdebug";

var ie4 = (document.all)? true:false;

/************************************************************
* NewAC
*
* Retourne une instance de la classe AjaxCon
*
* @param  string url_, url http pr la connection Ajax
*
************************************************************/
function NewAC(url_){
	return new AjaxConn(url_);
}

/************************************************************
* Constructeur de la classe AjaxCon
*
* @param  string url_, url http pr la connection Ajax
*
************************************************************/
function AjaxConn(url_){
	this.url=url_;
	this.handlers=new Array();
	this.mimetype="text/plain";
    this.innerBool=false;
    this.innerDivId='';
	this.encoding='';
}

AjaxConn.prototype.setMimeType = function(mimetype_){
	this.mimetype=mimetype_;
	return this;
}

AjaxConn.prototype.getMimeType = function(){
	return this.mimetype;
}

AjaxConn.prototype.setEncoding = function(encoding_){
	this.encoding=encoding_;
	return this;
}

AjaxConn.prototype.getEncoding = function(){
	return this.encoding;
}

/************************************************************
* connect
*
* Execute la connection Ajax a l'url
*
* @param cibleId, si null -> affichage du divLoading centr???, (DEFAULT)
*							  si id d'un element HTML -> affichage d'un loading sur l'element
*							  si false -> pas d'affichage
*
************************************************************/
AjaxConn.prototype.connect= function(method_,cibleId)
{
	
	this.showLoading(true, cibleId);
	
	//forcer le reload ds les navigateurs ac cache
	var today = new Date();
    var timestamp = today.getTime();
	var strUrl= new String(this.url);
	
	if(!method_) method_="get";

	if(strUrl.indexOf("?")<0){
		strUrl+="?nocache="+timestamp;
	}else{
		strUrl+="&nocache="+timestamp;
	}
		
	//showLoading(true, cibleId);
	var conn=this;

	//parametre de connexion bind Ajax
	var bindArgs = { url: strUrl,
							 load: function(type, evaldObj){											
									conn.execHandler(evaldObj);
									conn.showLoading(false, cibleId);
								},
								transport: "XMLHTTPTransport",
								mimetype:conn.getMimeType(),					
								method:method_,
								headers: {"X-Requested-With":"XMLHttpRequest"}
								};

	//connexion HttpRequest
	//setTimeout(function(){dojo.io.bind(bindArgs);},0);
         if(this.innerBool){
           this.replaceInnerByLoadScreen(this.innerDivId);
       }
	dojo.io.bind(bindArgs);
}

/************************************************************
* submit
*
* Validation en POST d'un formulaire
*
* @param  string form_ , id du form  HTML
* @param cibleId, si null -> affichage du divLoading centr???, (DEFAULT)
*							  si id d'un element HTML -> affichage d'un loading sur l'element
*							  si false -> pas d'affichage
*
************************************************************/
AjaxConn.prototype.submit = function(form_,cibleId)
{		
	this.showLoading(true, cibleId);
	var urlToValidate=this.url;
	
	var conn=this;	
	
	var bindArgs = { 	url: urlToValidate,								
						formNode: document.getElementById(form_),
						method: "post",
						encoding: conn.getEncoding(),
						headers: {"X-Requested-With":"XMLHttpRequest"},										
						handle: function(type, evaldObj,evt){
							
									try{
										
										var data="";

										if(evaldObj instanceof Object){												
										
											//si evaldObj n'est pas d???fini, c k'il sagit d'un form d'upload.
											var ifrContent;	
											if(window.execScript){										
												ifrContent = document.getElementById('dojoIoIframe').contentWindow.document;																			
											}else if(navigator.userAgent.indexOf('KHTML') != -1){											
											}else{												
												ifrContent = document.getElementsByTagName("iframe")["dojoIoIframe"].contentDocument;												
											}	
											
											if(ifrContent)
											{
												datas="";										
												var arS=ifrContent.getElementsByTagName("script");
												for(var sc=0; sc<arS.length; sc++){
													datas+='<script type="text/javascript">'+arS[sc].innerHTML+'</script>';
												}																
												data=datas+ifrContent.body.innerHTML;	
											}
										}else{
											data=evaldObj;
										}
									}catch(er){
//                                                                        alert('break showloading');
//                                                                        conn.showLoading(false, cibleId);
                                                                        }
									
									conn.showLoading(false, cibleId);
									conn.execHandler(data);
								}	
					};
	
	dojo.io.bind(bindArgs);
 }
 
 AjaxConn.prototype.replaceInnerByLoadScreen= function(divId){

                var div =document.getElementById(divId);
                if(div){
                    var divLoading=document.getElementById('divLoading');
                    if(divLoading){
                        div.innerHTML=divLoading.innerHTML;
                    }else{
                        div.innerHTML='Chargement ...';
                    }
                }

 }

/************************************************************
* addHandler
*
* Ajout d'un handler pour le traitement du resultat retourn??? par l'HTTPRequest
*
*@param params_, array d'objet
*
* exemples	:	.addHandler({type:AC_ALERT})
*						==> alert du resultat
*
*						.addHandler({type:AC_VALUE, value:'txt'})
*						==>modifie la valeur de l'element ayant l'id 'txt'
*
*						.addHandler({type:AC_FCT, value:'alertR'})
*						==> envoie le resultat a la fonction javascript alertR()
*
*						.addHandler({type:AC_INNER, value:'para'})
*						==> remplace le contenu de l'element d'id 'para' par le resultat
*
*						.addHandler({type:AC_EVAL, value:'instruction'})
*						==> eval() instruction
*
*						.addHandler({type:AC_REPLACE, value:'idEl'})
*						==> remplace le noeud HTML idEL par le code HTML retourn??

						.addHandler({type:AC_JS})
*						==> interprete le code JS retourn?? par l'appel

						.addHandler({type:AC_MESSAGE})
*						==>affiche le resultat retourn?? dans le cadre message (bas droite)
*
* 							.addHandler({type:AC_WOPEN, title:'titre de la fenetre', width:600})
*						==>ouverture dune fenetre
*
************************************************************/
AjaxConn.prototype.addHandler= function(params_)
{
	this.handlers.push(params_);
        if(params_.type){
            if(params_.type==AC_INNER){
                this.innerBool=true;
                this.innerDivId=params_.value;
            }
        }
	return this;
}

String.prototype.extractTags=function(tag) {
	 var matchAll = new RegExp('(?:<'+tag+'.*?>)((\n|\r|.)*?)(?:<\/'+tag+'>)', 'img');
	 var matchOne = new RegExp('(?:<'+tag+'.*?>)((\n|\r|.)*?)(?:<\/'+tag+'>)', 'im');
	 return (this.match(matchAll) || []).map(function(scriptTag) {
		return (scriptTag.match(matchOne) || ['', ''])[1];
	});
} 

/************************************************************
* inner
*
* Ajout de code HTML dans un element HTML. Possibilit??? d'ajouter dynamiquement
* les elements <script>, et possibilit??? de parser le contenu si utilisation d'attributs
* dojo.
*
* @param  string htmlContent, contenu HTML
* @param  mixed htmlEl, id de l'element HTML ou ???l???ment HTML lui-meme.
* @param boolean parseJS_, sp???cifie si les elements <script> de htmlContent sont pars???s (true par d???faut)
* @param boolean parseDojo_, sp???cifie si htmlContent doit etre pars??? par le parseur Dojo
*
************************************************************/
AjaxConn.prototype.inner = function(htmlContent, htmlEl, parseJS_, parseDojo_)
{
	try{
		//init param
		if(parseJS_== null) parseJS_=true;
	
		//on recupe le domNode
		var domNode=$(htmlEl);
//                if(!domNode) alert(htmlEl+' pas trouvé');
//                else domNode.show();

	
		//on set le nouveau code html et js (htmlContent)  ds le bloc htmlEl :
		
		try{
			toto=domNode.style;
		}catch(err){
			//alert('erreur inner : '+htmlEl);
		}
	
		var jsStripContent = htmlContent.replace(new RegExp(Prototype.ScriptFragment, 'img'), '');
		domNode.innerHTML = jsStripContent;
		//domNode.innerHTML = htmlContent;
			
			
		//parse css
		try{
		 
		 var AllStyles=jsStripContent.extractTags("style");
		 if(document.createStyleSheet){
			var s=document.createStyleSheet();
			s.cssText=AllStyles;
			s.enabled=true;
		 }else{
			 var s = document.createElement('style');
			 s.type = 'text/css';
			 s.innerHTML = AllStyles;
			 document.getElementsByTagName("head")[0].appendChild(s);
		 }
		 
		 
		 } catch (ex) {} 

		//v2	: use prototype
		if(parseJS_){
		 
		 var matchAll = new RegExp(Prototype.ScriptFragment, 'img');
    	 var matchOne = new RegExp(Prototype.ScriptFragment, 'im');
    	 var jsScriptArray=(htmlContent.match(matchAll) || []);
		 
		 //if(ie4){
			 
			 for(var i=0; i<jsScriptArray.length; i++){
			 	this.globalEval ((jsScriptArray[i].match(matchOne) || ['', ''])[1]);
			}
	     }
			
		if(parseDojo_){
			var testObjects = new dojo.xml.Parse();
			var testItems = testObjects.parseElement(domNode);
			dojo.widget.getParser().createComponents(testItems);
		}
	}catch(e){}
}

AjaxConn.prototype.globalEval = function(script)
{
  if(window.execScript){
    
	return window.execScript(script);
	
  }else if(navigator.userAgent.indexOf('KHTML') != -1){ //safari, konqueror..
      
	var s = document.createElement('script');
    s.type = 'text/javascript';
    s.innerHTML = script;
    document.getElementsByTagName('head')[0].appendChild(s);
	  
  }else{
    
	return window.eval(script);
  }
}

/************************************************************
* showLoading [PRIVATE METHOD]
*
* Montre le chargement pdt l'execution d'une HTTPRequest
*
* @param  boolean bool_, afficher ou masker le chargement
* @param cibleId, si null -> affichage du divLoading centr???, (DEFAULT)
							  si id d'un element HTML -> affichage d'un loading sur l'element
							  si false -> pas d'affichage
*
************************************************************/
AjaxConn.prototype.showLoading=function(bool_, cibleId)
{

	
	if(cibleId!=false){

		var div="divLoading";

		try{	
			if(cibleId!=null){
				div="divLoading2";
	
				var loadEl=document.getElementById(div);
				var cibleEl=document.getElementById(cibleId);
	
				if(!ie4){
					loadEl.style.left		=	posX(cibleEl)+"px";
					loadEl.style.width	=	widthX(cibleEl)-10+"px";
					loadEl.style.top		=	posY(cibleEl)+"px";
					loadEl.style.height	=	heightY(cibleEl)-10+"px";
				}else{
					loadEl.style.left		=	cibleEl.offsetLeft+"px";
					//TODO : utiliser les posX, WIdthX...etc
					loadEl.style.width	=	cibleEl.offsetWidth-10+"px";
					loadEl.style.top		=	cibleEl.offsetTop+"px";
					if(cibleEl.offsetHeight)
					loadEl.style.height	=	cibleEl.offsetHeight-10+"px";
				}
			}
			var div="divLoading";
			if(bool_){
				LOADCOUNT++;
				if(document.getElementById(div))
				document.getElementById(div).style.display="";
	
			}else{
	
				LOADCOUNT--;
				if(LOADCOUNT==0){
					if(document.getElementById(div))
					document.getElementById(div).style.display="none";
				}
			}
		}catch(e){}
	
	}
	
	
}

/************************************************************
* execHandler [PRIVATE METHOD]
*
* Traite le resultat retourn??? par l'HTTPRequest en fction des handlers
* ajout???s au connecteur
*
* @param  string result_, le resultat retourn??? par l'HTTPRequest
*
************************************************************/
AjaxConn.prototype.execHandler = function(result_)
{
	for(var i=0; i<this.handlers.length; i++){

		var handler= this.handlers[i];

		switch(handler.type){

			case AC_EVAL : 	if(handler.value) eval(handler.value); else eval(result_);
												 	break;

			case AC_ALERT : alert(result_);
													break;

			case AC_FCT : 			if(this.getMimeType()=="text/plain"){
													eval(handler.value+"('"+escape(result_)+"')");
												}else{
													eval(handler.value+"(result_)");
												}

													break;

			case AC_METHOD : 	var obj=handler.value;
												if(this.getMimeType()=="text/plain"){
													var result=escape(result_);
													eval("obj."+handler.method+"('"+result+"')");
												}else{
													eval("obj."+handler.method+"(result_)");
												}
												break;

			case AC_INNER : this.inner(result_, handler.value, handler.parseJS, handler.parseDojo);
													break;

			case AC_VALUE : document.getElementById(handler.value).value=result_;
													break;

			case AC_REPLACE : replaceEL(handler.value, result_);
												break;

			case AC_JS : eval(result_);
													break;

			case AC_MESSAGE : showMessage(result_);
												break;

			case AC_WOPEN : WindowSystem.getCurrentWindow().showModal(result_, handler.title, handler.width);
												break;
												
			case AC_DEBUG: try{console.info(result_)}catch(e){};
										break;
										
			default : break;
		}
	}	
}
