/* 
 * Version modifiee de jForms_jquery.js
 * - controle possible au niveau d'un Group (un numero de tel parmi trois requis), controle String pouvant être restreint a des chiffres
 * - decorateur specifique
 * - on enleve les controles superflus (a ajouter au cas par cas si le besoin se fait sentir)
 */

/**
 * Form manager 
 * - modifs : getValue en methode de classe et prise en compte des Controlde type groupe dans verifyControl
 */
var jFormsJQ = {
    _forms: {},

    tForm: null,

    declareForm : function(aForm){
        this._forms[aForm.name] = aForm;
        jQuery('#'+aForm.name).bind('submit',function (ev) {
        	jQuery(ev.target).trigger('jFormsUpdateFields');
            return jFormsJQ.verifyForm(ev.target)});
    },

    getForm : function (name) {
        return this._forms[name];
    },

    verifyForm : function(frmElt) {
        this.tForm = this._forms[frmElt.attributes.getNamedItem("id").value]; // we cannot use getAttribute for id because a bug with IE
        var msg = '';
        var valid = true;
		$("#"+this.tForm.name).find('.invalid').each(function(){$(this).removeClass('invalid');});
        this.tForm.errorDecorator.start(frmElt);
        for(var i =0; i < this.tForm.controls.length; i++){
            if (!this.verifyControl(this.tForm.controls[i], this.tForm))
                valid = false;
        }
        if(!valid)
            this.tForm.errorDecorator.end();
        else if (this.tForm.hideOnsubmit)
        	this.hideFormOnSubmit(this.tForm);
        return valid;
    },

    /**
     * @param jFormsJQControl*  ctrl     a jform control
     * @param jFormsJQForm      frm      the jform object
     */
    verifyControl : function (ctrl, frm) {
        var val;
        if (ctrl instanceof jFormsJQControlGroup) {
        	if (!ctrl.check(frm)) {
        		frm.errorDecorator.addError(ctrl, 1);
        		return false;
        	}
        	return true;
    	}
        else {
	        if(typeof ctrl.getValue == 'function') {
	            val = ctrl.getValue();
	        }
	        else {
	            var elt = frm.element.elements[ctrl.name];
	            if (!elt) return true; // sometimes, all controls are not generated...
	            if (!$(elt).is(':visible')) return true;// pas de contrôle sur elt non visible
	            val = this.getValue(elt);
	        }
	
	        if (val === null || val === false) {
	            if (ctrl.required) {
	                frm.errorDecorator.addError(ctrl, 1);
	                return false;
	            }
	        }
	        else {
	            if(!ctrl.check(val, frm)){
	                frm.errorDecorator.addError(ctrl, 2);
	                return false;
	            }
	        }
	        return true;
        }
    },
    
    hideFormOnSubmit : function(aForm) {
    	submitBt = $('#'+aForm.name).find('input[type="image"],submit');
    	submitBt.replaceWith('<img src="/images/indicator.gif" class="'+submitBt.attr('class')+'"/>');
    },

    showHelp : function(aFormName, aControlName){
        var frm = this._forms[aFormName];
        var ctrls = frm.controls;
        var ctrl = null;
        for(var i=0; i < ctrls.length; i++){
            if (ctrls[i].name == aControlName) {
                ctrl = ctrls[i];
                break;
            }
            if (ctrls[i].confirmField &&  ctrls[i].confirmField.name == aControlName) {
                ctrl = ctrls[i].confirmField;
                break;
            }
        }
        if (ctrl) {
            frm.helpDecorator.show(ctrl.help);
        }
    },

    hasClass: function (elt,clss) {
        return elt.className.match(new RegExp('(\\s|^)'+clss+'(\\s|$)'));
    },
    addClass: function (elt,clss) {
        if (this.isCollection(elt)) {
            for(var j=0; j<elt.length;j++) {
                if (!this.hasClass(elt[j],clss)) {
                    elt[j].className += " "+clss;
                }
            }
        } else {
            if (!this.hasClass(elt,clss)) {
                elt.className += " "+clss;
            }
        }
    },
    removeClass: function (elt,clss) {
        if (this.isCollection(elt)) {
            for(var j=0; j<elt.length;j++) {
                if (this.hasClass(elt[j],clss)) {
                    elt[j].className = elt[j].className.replace(new RegExp('(\\s|^)'+clss+'(\\s|$)'),' ');
                }
            }
        } else {
            if (this.hasClass(elt,clss)) {
                elt.className = elt.className.replace(new RegExp('(\\s|^)'+clss+'(\\s|$)'),' ');
            }
        }
    },
    setAttribute: function(elt, name, value){
        if (this.isCollection(elt)) {
            for(var j=0; j<elt.length;j++) {
                elt[j].setAttribute(name, value);
            }
        } else {
            elt.setAttribute(name, value);
        }
    },
    removeAttribute: function(elt, name){
        if (this.isCollection(elt)) {
            for(var j=0; j<elt.length;j++) {
                elt[j].removeAttribute(name);
            }
        } else {
            elt.removeAttribute(name);
        }
    },
    isCollection: function(elt) {
        if (typeof HTMLCollection != "undefined" && elt instanceof HTMLCollection) {
            return true;
        } 
        if (typeof NodeList != "undefined" && elt instanceof NodeList) {
          return true;
        }
        if (elt instanceof Array)
            return true;
        if (elt.length != undefined && (elt.localName == undefined || elt.localName == 'SELECT' || elt.localName != 'select'))
            return true;
        return false;
    }
};

jFormsJQ.getValue = function (elt){
    if(elt.nodeType) { // this is a node
        switch (elt.nodeName.toLowerCase()) {
            case "input":
                if(elt.getAttribute('type') == 'checkbox')
                    return elt.checked;
            case "textarea":
                var val = jQuery.trim(elt.value); 
                return (val !== '' ? val:null);
            case "select":
                if (!elt.multiple)
                    return (elt.value!==''?elt.value:null);
                var values = [];
                for (var i = 0; i < elt.options.length; i++) {
                    if (elt.options[i].selected)
                        values.push(elt.options[i].value);
                }
                if(values.length) 
                    return values; 
                return null;
        }
    } else if(this.isCollection(elt)){
        // this is a NodeList of radio buttons or multiple checkboxes
        var values = [];
        for (var i = 0; i < elt.length; i++) {
            var item = elt[i];
            if (item.checked)
                values.push(item.value);
        }
        if(values.length) {
            if (elt[0].getAttribute('type') == 'radio')
                return values[0];
            return values; 
        }
    }
    return null;
}

/** Represents a form */
function jFormsJQForm(name){
    this.name = name;
    this.controls = [];
    this.errorDecorator =  new jFormsJQErrorDecoratorAlert();
    this.helpDecorator =  new jFormsJQHelpDecoratorAlert();
    this.element = jQuery('#'+name).get(0);
    this.alertStandard = '';
    this.xitin1f=''; // indique site du form dans un taggage Xiti.
	this.xitin2f=''; // indique le niveau 2 du form dans un taggage Xiti. si à blanc, form non taggé.
	this.hideOnsubmit = false;
};

jFormsJQForm.prototype={
	setXitin1f: function(n1){this.xitin1f = n1;},
	setXitin2f: function(n2){this.xitin2f = n2;},
	isXitiActivated: function(){return (this.xitin1f != '' && this.xitin2f != '');},
	
    addControl : function(ctrl){
        this.controls.push(ctrl);
        ctrl.formName = this.name;
    },

    setErrorDecorator : function (decorator){this.errorDecorator = decorator;},
    setHelpDecorator : function (decorator){this.helpDecorator = decorator;},
    setAlertStandard : function(msg) {this.alertStandard = msg;},
    setHideOnsubmit : function (hide){this.hideOnsubmit = hide;},

    getControl : function(aControlName) {
        var ctrls = this.controls;
        for(var i=0; i < ctrls.length; i++){
            if (ctrls[i].name == aControlName) {
                return ctrls[i];
            }
        }
        return null;
    }
};

/** Control with string */
function jFormsJQControlString(name, label) {
    this.name = name;
    this.label = label;
    this.required = false;
    this.errInvalid = '';
    this.errRequired = '';
    this.help='';
    this.minLength = -1;
    this.maxLength = -1;
    this.onlyNumbers = false;
};
jFormsJQControlString.prototype.check = function (val, jfrm) {
    if(this.minLength != -1 && val.length < this.minLength)
        return false;
    if(this.maxLength != -1 && val.length > this.maxLength)
        return false;
    if (this.onlyNumbers)
    	return ( -1 != val.search(/^\d+$/));
    	
    return true;
};

/** Control for secret input */
function jFormsJQControlSecret(name, label) {
    this.name = name;
    this.label = label;
    this.required = false;
    this.errInvalid = '';
    this.errRequired = '';
    this.help='';
    this.minLength = -1;
    this.maxLength = -1;
};
jFormsJQControlSecret.prototype.check = function (val, jfrm) {
    if(this.minLength != -1 && val.length < this.minLength)
        return false;
    if(this.maxLength != -1 && val.length > this.maxLength)
        return false;
    return true;
};

/** Confirm control */
function jFormsJQControlConfirm(name, label) {
    this.name = name;
    this.label = label;
    this.required = false;
    this.errInvalid = '';
    this.errRequired = '';
    this.help='';
    this._masterControl = name.replace(/_confirm$/,'');
};
jFormsJQControlConfirm.prototype.check = function(val, jfrm) {
    if(jFormsJQ.getValue(jfrm.element.elements[this._masterControl]) !== val)
        return false;
    return true;
};

/** Control with boolean */
function jFormsJQControlBoolean(name, label) {
    this.name = name;
    this.label = label;
    this.required = false;
    this.errInvalid = '';
    this.errRequired = '';
    this.help='';
};
jFormsJQControlBoolean.prototype.check = function (val, jfrm) {
    return (val == true || val == false);
};
/** Control with Integer */
function jFormsJQControlInteger(name, label) {
    this.name = name;
    this.label = label;
    this.required = false;
    this.errInvalid = '';
    this.errRequired = '';
    this.help='';
};
jFormsJQControlInteger.prototype.check = function (val, jfrm) {
    return ( -1 != val.search(/^\s*[\+\-]?\d+\s*$/));
};

/** Control with email */
function jFormsJQControlEmail(name, label) {
    this.name = name;
    this.label = label;
    this.required = false;
    this.errInvalid = '';
    this.errRequired = '';
    this.help='';
};
jFormsJQControlEmail.prototype.check = function (val, jfrm) {
    return (val.search(/^((\"[^\"f\n\r\t\b]+\")|([\w\!\#\$\%\&\'\*\+\-\~\/\^\`\|\{\}]+(\.[\w\!\#\$\%\&\'\*\+\-\~\/\^\`\|\{\}]+)*))@((\[(((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9])))\])|(((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9]))\.((25[0-5])|(2[0-4][0-9])|([0-1]?[0-9]?[0-9])))|((([A-Za-z0-9\-])+\.)+[A-Za-z\-]+))$/) != -1);
};

/** Choice control*/
function jFormsJQControlChoice(name, label) {
    this.name = name;
    this.label = label;
    this.required = false;
    this.errInvalid = '';
    this.errRequired = '';
    this.help='';
    this.items = {};
};
jFormsJQControlChoice.prototype = {
    addControl : function (ctrl, itemValue) {
        if(this.items[itemValue] == undefined)
            this.items[itemValue] = [];
        this.items[itemValue].push(ctrl);
    },
    check : function (val, jfrm) {
        if(this.items[val] == undefined)
            return false;

        var list = this.items[val];
        var valid = true;
        for(var i=0; i < list.length; i++) {
            var val2 = jFormsJQ.getValue(jfrm.element.elements[list[i].name]);

            if (val2 == '') {
                if (list[i].required) {
                    jfrm.errorDecorator.addError(list[i], 1);
                    valid = false;
                }
            } else if (!list[i].check(val2, jfrm)) {
                jfrm.errorDecorator.addError(list[i], 2);
                valid = false;
            }
        }
        return valid;
    },
    activate : function (val) {
        var frmElt = document.getElementById(this.formName);
        for(var j in this.items) {
            var list = this.items[j];
            for(var i=0; i < list.length; i++) {
                var elt = frmElt.elements[list[i].name];
                if (val == j) {
                    jFormsJQ.removeAttribute(elt, "readonly");
                    jFormsJQ.removeClass(elt, "jforms-readonly");
                } else {
                    jFormsJQ.setAttribute(elt, "readonly", "readonly");
                    jFormsJQ.addClass(elt, "jforms-readonly");
                }
            }
        }
    }

};

/** Controle numero de telephone */
function jFormsJQControlPhone(name, label) {
    this.name = name;
    this.label = label;
    this.required = false;
    this.errInvalid = '';
    this.errRequired = '';
    this.help='';
};
jFormsJQControlPhone.prototype.check = function (val, jfrm) {
	return ( -1 != val.replace(/ /gi, '').search(/^[\+]?\d{10,24}$/));
};


/** Decorator to display errors² */
function jFormsJQErrorDecoratorAlert(){
    this.message = '';
    this.ctrlElts;
    this.tForm;
};
jFormsJQErrorDecoratorAlert.prototype = {
	    start : function(tform){
	        this.msg = '';
	        this.ctrlElts = [];
	        this.msgs = [];
	        this.tForm = tform;
	        this.msgDefaut = jFormsJQ.getForm($(this.tForm).attr('id')).alertStandard;
	        this.msgDefautShown = false
	    },
	    addError : function(control, messageType){
	        if(messageType == 1){
	        	if (control.childrenCtrl) { // group
	        		for(var i=0; i < control.childrenCtrl.length; i++) {
	        			this.ctrlElts.push($(this.tForm).find("[name='"+control.childrenCtrl[i]+"']"));
	        		}
	        	} else {
	        		this.ctrlElts.push($(this.tForm).find("[name='"+control.name+"']"));
	        	}
	        	//message
        		if (control.errRequired != '')
        			this.msgs.push(control.errRequired);
        		else if (!this.msgDefautShown) {
        			this.msgs.push(this.msgDefaut);
        			this.msgDefautShown = true;
        		}
	        }else if(messageType == 2){
	            if (control.errInvalid != '') {
	            	this.msgs.push(control.errInvalid);
	            }
	        	this.ctrlElts.push($(this.tForm).find("[name='"+control.name+"']"));
	        }else{
	        	this.ctrlElts.push($(this.tForm).find("[name='"+control.name+"']"));
	        }
	    },
	    end : function(){	    	
	    	$(this.ctrlElts).each(function(){
	    		if ($(this).attr('type') != 'checkbox' && $(this).attr('type') != 'radio') {
	    			$(this).addClass('invalid');
	    		} else {// on change le style des labels
	    			$(this).next().addClass('invalid');
	    		}
	    	});
	    	
	    	// formattage message(s) erreur
	    	for(var i=0; i < this.msgs.length; i++) {
	    		 this.msg +=  this.msgs[i] + ((i != this.msgs.length-1) ? '<br/>' : '');
	    	}
	    	if (this.msg == '')
	    		this.msg = this.msgDefaut;
	    	
	    	$(this.tForm).find(".formAlert").html(this.msg);
	    	$(this.tForm).find(".formAlert").css('display','block');
	    }
};


/** Decorator to display help messages*/
function jFormsJQHelpDecoratorAlert() { };
jFormsJQHelpDecoratorAlert.prototype = {
    show : function( message){
        alert(message);
    }
};


/**
 * Controle de type Group customise
 * - oneRequired : indique si un element du groupe est requis
 */
function jFormsJQControlGroup(name, label) {
    this.name = name;
    this.label = label;
    this.required = false;
    this.errInvalid = '';
    this.errRequired = '';
    this.help='';
    this.oneRequired = false;
    this.childrenCtrl;
};
jFormsJQControlGroup.prototype.check = function (jfrm) {
    if (this.oneRequired) {
    	var elt;
    	test = false;
    	for(var i=0; i < this.childrenCtrl.length; i++){
    		elt = jfrm.element.elements[this.childrenCtrl[i]];
    		if (elt) {
    			val = jFormsJQ.getValue(elt);
    			test = test || (val !== null && val !== false);
    			if (test) break;
    		}
    	}
    	return test;
    }
    return true;
};

/** Au chargement */
$(document).ready(function() {
	
	$("form").each(function() {
		var jform = jFormsJQ.getForm($(this).attr('id'));
		if (typeof(jform) == 'undefined') // formulaire non référencé
			return;
		// Spécificités France
		if ($(this).find("input[name='cp']").length && $(this).find("input[name='ville']").length && $(this).find("select[name='pays']").length) {	// champ code postal ville et pays trouve
			// Si pays = 'FR' => maxlength sur cp
			if ($(this).find("select[name='pays']").val() == 'FR')
				toggleFrSpecs(this, true);
			$("select[name='pays']").change(function(){
				toggleFrSpecs($(this).parents("form").get(0), $(this).val() == 'FR');
			});
			// Si pays = 'FR' => liaison cp et ville
			var villeText = $("input[name='ville']:first").clone(true); // clone du champ sous forme texte
			$("input[name='cp']").keyup(function(){
				var form = $(this).parents("form"); // formulaire courant
				if (form.find("select[name='pays']").val() == 'FR') {
					//$(this).attr('maxlength','5');
			        counter = $(this).val().length;
			        if (counter == 5 && $(this).val().search(/^\d+$/) != -1) {
			        	refreshVille($(this),form);
			        } else if (counter == 0) {
			        	var original = '<input type="text" class="'+villeText.attr('class')+'" name="ville" id="'+villeText.attr('id')+'" value="" />';
			        	form.find("[name='ville']:first").after(original).remove(); 
			        	xitiBind('focus', form.find("[name='ville']:first"));
			        }
				}
			 });
		}
		// Cas particuliers
		mode_doc = $(this).find("input[name='mode_doc']");
		if (mode_doc.length) {
			changeModeDoc($(this).find("input[name='mode_doc']:checked"));
			mode_doc.click(function(){return changeModeDoc(this);});
		}
		pr = $(this).find("input[name='profil_recherche']");
		if (pr.length && $(this).find("input[name='budget']").length) {
			toggleRequired($(this).find("input[name='profil_recherche']:checked").get(0), 'budget', "I");
			pr.click(function(){toggleRequired($(this).get(0), 'budget', "I");});
		}
		dpt1 = $(this).find("select[name='departement1']");
		if (dpt1.length)
			dpt1.change(function(){refreshProgrammes(this,'id_programme');
			if (typeof typosPgms != "undefined")
				refreshTypo();});
		dpt2 = $(this).find("select[name='departement2']");
		if (dpt2.length)
			dpt2.change(function(){refreshProgrammes(this,'id_programme2');
			if (typeof typosPgms != "undefined")
				refreshTypo();});
		if (typeof typosPgms != "undefined")
			$("select[name*='id_programme']").each(function(){$(this).change(function(){refreshTypo();});});
		// Xiti, xtsd présent dans la page
		if (typeof(xtsd) != 'undefined' && jform.isXitiActivated()) { 
			$(this).find(":text,textarea,:password").each(function(){xitiBind('focus', this, jform);});
			$(this).find("select").each(function(){xitiBind('change', this, jform);});
			$(this).find(":checkbox,:radio").each(function(){xitiBind('click', this, jform);});
		}
		// Activation label[for] Iphone / IPad
		if (navigator.userAgent.match(/iPhone/i) || navigator.userAgent.match(/iPod/i) || navigator.userAgent.match(/iPad/i)) {
			$('label[for]').click(function () {
				var el = $(this).attr('for');
				if ($('#'+el+'[type=radio], #'+el+'[type=checkbox]').attr('selected', !$('#'+el).attr('selected')))
					return;
				else
					$('#'+el)[0].focus();
			});
		}
	});
});
/** Specificites formulaires (cp) pour France */
function toggleFrSpecs(form, isFr) {
	if (isFr) {
		$(form).find("input[name='cp']").attr('maxlength','5');
		cpCtrl = jFormsJQ.getForm($(form).attr('id')).getControl('cp');
		cpCtrl.onlyNumbers = true;cpCtrl.minLength = 5;cpCtrl.maxLength = 5;
	} else {
		$(form).find("input[name='cp']").attr('maxlength','25');
		cpCtrl = jFormsJQ.getForm($(form).attr('id')).getControl('cp');
		cpCtrl.onlyNumbers = false;cpCtrl.minLength = -1;cpCtrl.maxLength = 25;
	}
}
/** Selection villes selon code postal */
function refreshVille(obj, form) {
	var o = form.find("[name='ville']:first");
	$.ajax({
		dataType: 'json',
		url: "/contact/villes",
		data: {
			id: o.attr('id'),
			classe: o.attr('class'),
			value: o.val(),
			cp: $(obj).val()
		},
		success: function(data) {
			// remplacement du champ ville si retour 
			o.after(data.html).remove(); 
			//$(obj).blur(); // sinon double effet Xiti
			oNew =  form.find("[name='ville']:first");
			xitiBind(oNew.is(":select") ? 'change' : 'focus', oNew);
		}
	});
}
/** Chargement programmes dans select cible selon departement */
function refreshProgrammes(obj, targetName) {
	var target = $("[ name = '"+targetName+"']");
	$(target).children(":gt(0)").remove();
	var tout = typeof tousPgms != "undefined" ? 1 : ''; // tousPgms a placer ou non dans js selon besoin
	if (obj.value != '') {
		$.ajax({
			dataType: 'json',
			url: "/contact/programmes",
			cache:false,
			data: {
				lieu: obj.value,
				all: tout
			},
			success: function(data) {
				var typos = typeof typosPgms != "undefined";
				if(data.length) {
					for (var i=0;i<data.length;i++) {
						$(target).append('<option value="'+data[i].value+'">'+data[i].label+"</option>");
						if (typos) {
							if (i==0)
								typosPgms["'"+$(obj).attr('name')+"'"] = [];
							typosPgms["'"+$(obj).attr('name')+"'"]["'"+data[i].value+"'"] = data[i].typo;
						}	
					}
				}
			}
		});
	}
}
/** Activation/désactivation typos selon programme */
function refreshTypo() {
	var typos = 1;
	var f = false;
	$("select[name*='id_programme']").each(function(index){
		dpt = $("select[name*='departement"+(index+1)+"']");
		if ($(this).val() != '') {
			f = true;
			typos *= typosPgms["'"+dpt.attr('name')+"'"]["'"+$(this).val()+"'"];
		} else { // dpt et aucun pgm => toutes typos activées
			if (dpt.val() != '') {
				f = false;
				return false;
			}
		}
	});
	if (!f || typos == 0 || (typos % 2 == 0) && (typos % 3 == 0))
		toggleTypo('');
	else if (typos % 2 == 0)
		toggleTypo('A');
	else
		toggleTypo('M');
}
/** Activation/désactivation checkbox typos */
function toggleTypo(t) {
	var a = $(":checkbox[value='A']");
	var m = $(":checkbox[value='M']");
	if (a.length && m.length) {
		if (t == '') {
			a.attr('disabled', false);
			m.attr('disabled', false);
		} else if (t == 'A') {
			m.attr('checked',false).attr('disabled', true);
			a.attr('disabled', false);
		} else if (t == 'M') {
			a.attr('checked',false).attr('disabled', true);
			m.attr('disabled', false);
		}
	}
}
/** Changement mode envoi documentation */
function changeModeDoc(obj) {
	var form = $(obj).parents("form");
	var adresses = $(form).find("[name = 'adresse'], [name = 'adresse2']");
	var labels = [];
	for (var i=0;i<adresses.length;i++) {
		if ($(form).find("[for='"+adresses[i].id+"']").length)
			labels.push($(form).find("[for='"+adresses[i].id+"']"));
	}
	var jForm = jFormsJQ.getForm($(form).attr('id'));
	var ctrlAdr = jForm.getControl('adresse');
	if ($(obj).val() == 'C') {
		adresses.each(function(){$(this).show();});
		$(labels).each(function(){$(this).show();});
		ctrlAdr.required = true;
	} else {
		adresses.each(function(){$(this).hide();});
		$(labels).each(function(){$(this).hide();});
		ctrlAdr.required = false;
	}
	$(form).find('.invalid').each(function(){$(this).removeClass('invalid');});
	$(this.tForm).find(".formAlert").css('display','none');
	return true;
}
/** Changer l'état obligatoire ou non d'un contrôle (targetName) */
function toggleRequired(elt, targetName, valueReq, sens) {
	var form = $("[ name = '"+targetName+"']").parents("form");
	var targetId = $("[ name = '"+targetName+"']").attr('id');
	var jForm = jFormsJQ.getForm($(form).attr('id'));
	var ctrl = jForm.getControl(targetName);
	req = (sens && sens == 'not') ? elt.value != valueReq : elt.value == valueReq;
	//if (elt.value == valueReq) {
    if (req) {
    	if (ctrl.required == false) {
    		ctrl.required = true;
    		$(form).find("[for='"+targetId+"']").append('<span class="req">*</span>');
    	}
	} else {
		if (ctrl.required == true) {
			ctrl.required = false;
			$(form).find("[for='"+targetId+"'] > span.req").remove();
			$("#"+targetId).removeClass('invalid');
		}
	}
}

function required(name, req) {
	var jForm = jFormsJQ.getForm($(form).attr('id'));
	var ctrl = jForm.getControl(targetName);
	ctrl.required = req;
	$(form).find("[for='"+targetId+"']").append('<span class="req">*</span>');
}

/** Bind Xiti d'un champ (e) du formulaire jFormsJQ (jf) à l'evtType donné */
function xitiBind(evtType, e, jf) {
	if (jf != null) {
		jfrm = jf;
	} else {
		jfrm = jFormsJQ.getForm($(e).parents("form").attr('id'));
		if (typeof(xtsd) == 'undefined' || !jfrm.isXitiActivated())
			return;
	}
	$(e).bind(evtType, function(){
		try{
			// libellé : nom sinon pour groupe cases à cocher (pas case seule) : nom::label
			name = $(this).attr('name');
			lib = ($(e).is(":checkbox,:radio") &&  $(this).parents("form").find("[name='"+name+"']").length > 1) ? 
						name.replace(/(\[\])/g,"")+'::'+$(this).parents("form").find("label[for='"+$(this).attr('id')+"']").text() 
						: name;
			xt_formulaire(jfrm.xitin1f,'F',jfrm.xitin2f,xitify(lib));
		}catch(e){}
	});
}	
/** Track champ formulaire Xiti, xtsd renseigné au niveau page */
function xt_formulaire(site,type,section,page,x1,x2,x3,x4,x5)
{xt_img = new Image();
xtdate = new Date();
xts = screen;
xt_ajout = (type=='F') ? '' : (type=='M') ? '&a='+x1+'&m1='+x2+'&m2='+x3+'&m3='+x4+'&m4='+x5 : '&clic='+x1;
Xt_im = xtsd+'.xiti.com/hit.xiti?s='+site+'&s2='+section;
Xt_im += '&p='+page+xt_ajout+'&hl=' + xtdate.getHours() + 'x' + xtdate.getMinutes() + 'x' + xtdate.getSeconds();
if(parseFloat(navigator.appVersion)>=4)
{Xt_im += '&r=' + xts.width + 'x' + xts.height + 'x' + xts.pixelDepth + 'x' + xts.colorDepth;}
xt_img.src = Xt_im;
if ((x2 != null)&&(x2!=undefined)&&(type=='C'))
{ if ((x3=='')||(x3==null)) { document.location = x2} else {xfen = window.open(x2,'xfen',''); xfen.focus();}}
else
{return;}}
