// 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 = false;
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 = 0.7clement';

	// 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'];
	}
	//---
	
	// Load Elements
	var oSelectObjet = new Array();
	var sParams      = '';
	var aParams      = new Array();
	oSelectObjet = AutoSubmit_Load_Element(aParamFunc['id'], aParamFunc['idForm']);
	//---
	
	// Constuct Params
	for(j=0;j<oSelectObjet.length; j++) {
		sParams += oSelectObjet[j]['name']+'='+oSelectObjet[j]['value'];
		if( j!=(oSelectObjet.length-1) ){ sParams += '&'; }
		
		aParams[j]          = new Array();
		aParams[j]['name']  = oSelectObjet[j]['name'];
		aParams[j]['value'] = oSelectObjet[j]['value'];
	}
	//---
		
	// 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 AutoSubmit_Load_Element(sMainId, sIdSearch){
	// Init Vars pour traitement
	var oWorking_Obj = new Array();
	var oSelectObjet = new Array();
	
	if($(sMainId).hasChildNodes()){
		// Clone le contenant a parser
		oWorking_Obj = $(sMainId).cloneNode(true);
		// Recup elements	
		oSelectObjet = AutoSubmit_getChildsElement(oWorking_Obj, sIdSearch);
		
	}
	
	return oSelectObjet;
}

function AutoSubmit_getChildsElement(oWorking_Obj, sIdSearched){
	var oSelectObjet = new Array();
	// Boucle sur les children de oWorking_Obj
	while (oWorking_Obj.firstChild) {
		
		if( (oWorking_Obj.firstChild.nodeName == 'INPUT') 
						 || (oWorking_Obj.firstChild.nodeName == 'SELECT') 
						 || (oWorking_Obj.firstChild.nodeName == 'TEXTAREA') ){
			var ObjActif = true;
				
			if( (oWorking_Obj.firstChild.id=='') || ( typeof(oWorking_Obj.firstChild.id)=='undefined') ){
				var sParent = AutoSubmit_firstParent(oWorking_Obj);
				kTrace('INPUT '+oWorking_Obj.firstChild.name+' sans ID dans : '+ sParent+' avec VALUE='+oWorking_Obj.firstChild.value);
				ObjActif = false;
			}
			if( (oWorking_Obj.firstChild.name=='') || (typeof(oWorking_Obj.firstChild.name) == 'undefined') ){
				var sParent = AutoSubmit_firstParent(oWorking_Obj);
				kTrace('INPUT '+oWorking_Obj.firstChild.id+' sans NAME dans : '+ sParent+' avec VALUE='+oWorking_Obj.firstChild.value);
				ObjActif = false; 
			}
			
			//Verifie que l'objet est actif			
			if( ObjActif){
				if($(oWorking_Obj.firstChild.id).disabled){ ObjActif = false; }
			
				//Verifie que l'objet est visible (style.display)
				//if(!AutoSubmit_obj_visible(oWorking_Obj)){ ObjActif = false; }
			
				if(ObjActif){
					var Objtype  = oWorking_Obj.firstChild.type;
					var ObjName  = oWorking_Obj.firstChild.name;
					var ObjId    = oWorking_Obj.firstChild.id;
					var ObjValue = oWorking_Obj.firstChild.value;
					var ObjHtml  = oWorking_Obj.firstChild;
			
					// Radio et CheckBox
					if( (oWorking_Obj.firstChild.type=='radio') || (oWorking_Obj.firstChild.type=='checkbox') ){
					
						if(!$(oWorking_Obj.firstChild.id).checked){ ObjValue = ''; } 
					}
				
					// TextArea et Select
					if( (oWorking_Obj.firstChild.nodeName == 'TEXTAREA') || (oWorking_Obj.firstChild.nodeName == 'SELECT') ){
						ObjValue = $(oWorking_Obj.firstChild.id).value; 
					}
				
					// idForm - recupere uniquement les input nommer comme idForm::input
					if(sIdSearched!=''){
						var sSeparator = '::';
						var sStr = sIdSearched + sSeparator;
						if(ObjId.substr(0, sStr.length) == sStr) {
							ObjName = ObjName.substring( ObjName.indexOf(sSeparator,0) + sSeparator.length, ObjName.length );
						}else{
							ObjValue='';
						}
					}
					//Recuperation des infos de l'input
					if(ObjValue!=''){
						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('#'));
						
					
						oSelectObjet.push( {'id':ObjId, 'type':Objtype, 'name':ObjName, 'value':ObjValue, 'html':ObjHtml } );
					}
				}
			}
		}
		
		// Boucle sur les children de oWorking_Obj.firstChild
		if( oWorking_Obj.firstChild.hasChildNodes() ){
			var oChildrenElem = AutoSubmit_getChildsElement(oWorking_Obj.firstChild, sIdSearched);
			oSelectObjet = oSelectObjet.concat(oChildrenElem);
		}
		oWorking_Obj.removeChild(oWorking_Obj.firstChild);
	};
	
	return oSelectObjet;
}

function AutoSubmit_obj_visible(the_obj){
	var obj=the_obj;
	var isseen=true;
	while(obj!=null){
		if(obj.style.display=='none'){
			isseen=false;
			break;
		}
		obj=obj.offsetParent;
	}
	return isseen;
}

function onFailureFunc_defaut(error){
	kTrace('Echec de la requete !'+ error.responseText);
}

function AutoSubmit_firstParent(the_obj){
	var obj=the_obj;
	var firstParent='';
	while(obj!=null){
		firstParent+=obj.nodeName+' - ';
		if( obj.id != undefined ){
			firstParent+=' ID:'+obj.id + ' - ';
			obj.nodeName
			break;
		}
		obj=obj.offsetParent;
	}
	if(firstParent==''){firstParent=' Noeud principal';}
	return firstParent;
}

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){}
		}
	}
}
