// JavaScript Document// JavaScript Document
/*
	La fonction autoSubmit permet de recupere l'ensemble des input contenu dans l'element 'id'
	et de le submit via AJAX
	Permet de recupere uniquement les input nommer comme "form::input"
	Ne renvoie que les elements ayant une value et etant visible (display!=none)
		NB : Dans le cas des radio et checkbox il faut qu'elles soient cocher egalement
	-----
	Necessite lib JS : prototype
*/
GLOBAL_DEBUG = true;

function autoSubmit(aParamFunc){
	/*
	aParamFunc{
		'id'           : string, id de l'element a parser, * 
		'url'          : string, *
		'method'       : string, par defaut post
		'idForm'       : string, chaine a trouver sur les input (idForm=form1 -> form1::input)
		'onSuccess'     : function, a exe onSuccess / prend les params de l'envoi 				($) ?
		'beforeSubmit' : function, a exe juste avant l'envoi AJAX / prend les params de l'envoi	($)
		'onFailure'    : function, a exe si echec de la requete / prend les params de l'envoi   ($)
	}
		 *  => Params Obligatoires
		($) => params passer sous forme de tableau :
			aParams[i]['name']
			          ['value']
	*/
	
	//Version
	version = 'version = 1.clement';

	// Check aParamFunc
	if( aParamFunc == undefined ){ return version; }
	if( (aParamFunc['id']==undefined) || (aParamFunc['id']=='') ) { 
		kTrace('Error : Missing Elelment ID !'); 
		return 'Error : Missing Elelment ID !'; 
	}
	if( (aParamFunc['url']==undefined) || (aParamFunc['url']=='') ) {
		kTrace('Error : Missing Url !');
		return 'Error : Missing Url !';
	}
	
	if( (aParamFunc['method']==undefined) || (aParamFunc['method']=='') ) { aParamFunc['method']='post'; }
	if( (aParamFunc['idForm']==undefined) ) { aParamFunc['idForm']=''; }
	if(typeof aParamFunc['onSuccess'] != 'function'){ 
		SubmitFunc = function empty(){}; 
	}else{ 
		SubmitFunc = aParamFunc['onSuccess']; 
	}
	if (typeof aParamFunc['onFailure'] != 'function'){
		onFailureFunc = onFailureFunc_defaut; 
	}else{
		onFailureFunc = aParamFunc['onFailure'];
	}
	//---
	

	
	var oSelectObjet = new Array();
	var sParams      = '';
	var aParams      = new Array();
	
	var aType=new Array('input','select','textarea');
	var n=0;
	var sName='';
	var ObjValue='';
	for(var k=0;k<aType.length;k++){		
		var aObj=$$('#'+aParamFunc['id']+' '+aType[k]);		
		for(var i=0;i<aObj.length;i++){				
			if(aObj[i].value){				
				sName=aObj[i].name;
				
					ObjValue=aObj[i].value;
					ObjValue=ObjValue.replace(/%/g,encodeURIComponent('%'));
					ObjValue=ObjValue.replace(/\?/g,encodeURIComponent('?'));
					ObjValue=ObjValue.replace(/\&/g,encodeURIComponent('&'));
					ObjValue=ObjValue.replace(/\+/g,encodeURIComponent('+'));
					ObjValue=ObjValue.replace(/#/g,encodeURIComponent('#'));
				
				
				if(!aObj[i].name){sName=aObj[i].id}	
				if(	aObj[i].type=="radio" || aObj[i].type=="checkbox"){
					if(aObj[i].checked){
						sParams+=sName+"="+ObjValue+"&";				
						n++;
						aParams[n]=new Array();
						aParams[n]['name']  = sName; 
						aParams[n]['value'] = ObjValue;
					} 
				}else{
					sParams+=sName+"="+ObjValue+"&";				
					n++;
					aParams[n]=new Array();
					aParams[n]['name']  = sName; 
					aParams[n]['value'] = ObjValue; 
				}
				
			} 
			
		}
	}
		
	

		
	// Execute beforeSubmit
	if (typeof aParamFunc['beforeSubmit'] != 'function'){
		beforeSubmitFunc = function empty(){}; 	
	}else{
		beforeSubmitFunc = aParamFunc['beforeSubmit'];
	}
	//---
	
	// AJAX request
	new Ajax.Request(
		aParamFunc['url'],
		{ 
			method       : aParamFunc['method'], 
			parameters   : sParams,
			onFailure    : function (err){ onFailureFunc(err); },
			onSuccess    : function (response){ SubmitFunc(response); },
			onCreate	 : function(t){	beforeSubmitFunc(aParams);}
		}
	);
	//---
}


function onFailureFunc_defaut(error){
	kTrace('Echec de la requete !'+ error.responseText);
}


function kTrace(aParamFunc){
	var version = '0.3';	
	/*
	aParamFunc{
		'message': string, message a afficher
		'top'    : int, distance du haut de l'ecran
		'left'   : int, distance du bord gauche de l'ecran
		'html'   : bool, true => ouvre la trace dans une fenetre HTML
	}
		* => Params Obligatoires (aucun ici)
	*/	
	if(GLOBAL_DEBUG){

		//verification des valeurs
		if(!aParamFunc){aParamFunc=Array();}
		if(typeof(aParamFunc)=="string"){
			var sMessage=aParamFunc;
			aParamFunc=Array()
			aParamFunc['message']=sMessage;
		}
		if(!aParamFunc['message']){ aParamFunc['message']='***** NULL *****';}
		if(!aParamFunc['top']){aParamFunc['top']=50;}
		if(!aParamFunc['left']){	aParamFunc['left']=window.screen.width/2-(430/2);}
		if(aParamFunc['html']==undefined){aParamFunc['html']=false;}
	
		//creation de l'objet POPUP DIV
		if(aParamFunc['html']){
			//POPUP HTML
			aParamFunc['top']=0;
			aParamFunc['left']=0;		
				var wPopupKTrace=window.open("","trace","menubar=no, status=no, scrollbars=no, menubar=no, width=400px,height=315px");
			wPopupKTrace.document.writeln("<html><head><title>Trace By K V."+version+"</title></head><body>&nbsp;</body></html>");
			wPopupKTrace.focus();	
			var oDoc=wPopupKTrace.document;
			var sHeader='<div style="text-align:right;"><div style="float:left;font-weight:bold;" >Trace by K. - V.'+version+'</div></div><br /><hr/><div id=\'PopupkTraceLogIn\'></div>';
		}else{
			var oDoc=document;
			var sHeader='<div style="text-align:right;"><div id="headPopupkTraceLog" style="cursor:pointer;"><div style="float:left;font-weight:bold;" >Trace by K. -  V.'+version+'</div><div ><input type="button" value="hide" onclick="var ePopup=document.getElementById(\'PopupkTraceLog\');ePopup.style.display=\'none\';" />&nbsp;&nbsp;&nbsp;&nbsp;<input type="button" value="close" onclick="var ePopup=document.getElementById(\'PopupkTraceLog\');var eBody=document.getElementsByTagName(\'body\')[0];eBody.removeChild(ePopup);" /></div></div></div><hr/><div id=\'PopupkTraceLogIn\'></div>';
		
		
		}
		var eBody=oDoc.getElementsByTagName('body')[0];	
		if(!oDoc.getElementById('PopupkTraceLog')){
			var ePopup = oDoc.createElement("div");
			var ePopupIn = oDoc.createElement("div");
			ePopup.id='PopupkTraceLog';			
			eBody.appendChild(ePopup);		
			ePopup.innerHTML=sHeader;
			ePopup.style.top=aParamFunc['top']+'px';
			ePopup.style.left=aParamFunc['left']+'px';
		}else{
			var ePopup =oDoc.getElementById('PopupkTraceLog');
		}
		
		//ecriture de la trace
		var oDate=new Date();
		if(oDate.getHours()<10){
			var sHeure='0'+oDate.getHours();
		}else{
			var sHeure=oDate.getHours();
		}
		if(oDate.getMinutes()<10){
			var sMinute='0'+oDate.getMinutes();
		}else{
			var sMinute=oDate.getMinutes();
		}
		if(oDate.getSeconds()<10){
			var sSecond='0'+oDate.getSeconds();
		}else{
			var sSecond=oDate.getSeconds();
		}
		var sDate= sHeure+":"+sMinute+":"+sSecond;
		var  ePopupIn=oDoc.getElementById('PopupkTraceLogIn');
		ePopupIn.innerHTML="<br /><strong>"+sDate+" : </strong>"+aParamFunc['message']+"<br />"+ePopupIn.innerHTML;
		
		//CSS de la div de suivi et de la popup
		ePopupIn.style.overflow='auto';
		ePopupIn.style.height='250px';
			
		ePopup.style.position='absolute';
		ePopup.style.zIndex=1000000;
		ePopup.style.fontFamily='verdana';
		ePopup.style.fontSize='10px';
	
		ePopup.style.width='400px';
		ePopup.style.height='300px';
		ePopup.style.padding='15px';
		ePopup.style.display='block';
		ePopup.style.borderColor='#999999';	
		ePopup.style.backgroundColor='#ffffff';	
		ePopup.style.borderStyle='solid';
		ePopup.style.borderSize='1px';		
		
		//Essai d'activer le drag n drop
		if(aParamFunc['html']==false){ 
			try {
				new Draggable($(ePopup),{handle:'headPopupkTraceLog'});
			}catch(err){}
		}
	}
}
