// 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 / kTrace
*/

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.5charly';

	// 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 = aParamFunc['beforeSubmit'];
		beforeSubmitFunc(aParams);
	}
	//---
	
	// AJAX request
	
	new Ajax.Request(
		aParamFunc['url'],
		{ 
			method       : aParamFunc['method'], 
			parameters   : sParams,
			onFailure    : function (err){ onFailureFunc(err); },
			onSuccess    : function (response){ SubmitFunc(response); }
		}
	);
	//---
}

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(document.getElementById(oWorking_Obj.firstChild.id)){}else{
				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=='') || (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 verifieChampsObligatoire(aParam){
	/* idPop : id de la popup
	liste_champs : array avec les champs a valide
	nocolor : false par defaut, avec true , le changement de couleur n'est pas applique.
	init : false par defaut, remet les couleurs de bases quelque soit le resultat
	*/
	var idChamp='';
	var nErreur=0;
	var objParent='';
	if(!aParam['init']){
		var bInit=false;
	}else{
		var bInit=aParam['init'];
	}
	if(!aParam['nocolor']){
		var bNoColor=false
	}else{
		var bNoColor=aParam['nocolor'];
	}
	if(aParam['idPop'] || aParam['idPop']==''){
		var idPop=aParam['idPop'];
		if(aParam['liste_champs']){
			aListeChamps=aParam['liste_champs'];
		}else{
			aListeChamps=new Array();
		}
	
		var nbElem=aListeChamps.length;
			
		for(var i=0;i<nbElem;i++){
			idChamp=idPop+aListeChamps[i];
			var aElements=document.getElementsByName(idChamp);
			var nbElements=aElements.length;
			
			if(nbElements>1){
				var bChecked=false;
				for(var j=0;j<nbElements;j++){					
					if(aElements[j].checked	){
						bChecked=true;
					}
				}
				if(!bChecked){
					objParent=aElements[(j-1)].offsetParent;
					nErreur++;
					if(!bNoColor)objParent.style.color='#990000';
				}else{
					objParent=aElements[(j-1)].offsetParent;
					if(!bNoColor)objParent.style.color='#000000';
				}
				if(bInit)objParent.style.color='#000000';				
			}			
			
			if(document.getElementById(idChamp)){				
				if($(idChamp).type=="checkbox"){	
					if(!$(idChamp).checked){
						nErreur++;
						objParent=$(idChamp).offsetParent;
						if(!bNoColor)objParent.style.color='#990000';
					}else{
						objParent=$(idChamp).offsetParent;
						if(!bNoColor)objParent.style.color='#000000';
					}
					if(bInit)objParent.style.color='#000000';
				}
				
				if($(idChamp).type!="checkbox" && $(idChamp).type!="radio"){				
					if($(idChamp).value==''){						
						nErreur++;
						if(!bNoColor)$(idChamp).style.borderColor='#990000';
						if(!bNoColor)$(idChamp).style.color='#990000';						
					}else{
						if(!bNoColor)$(idChamp).style.borderColor='#999999';
						if(!bNoColor)$(idChamp).style.color='#000000';
					}
				
					if(bInit)$(idChamp).style.color='#000000';
					if(bInit)$(idChamp).style.borderColor='#999999'; 
				}
			}				
		}
	}
	return nErreur;
}