// DEPRICATED
function selectAllOptions( listBox ){
    numberOfItems = listBox.options.length;
    listBox.focus();

    for (var i=0; i<numberOfItems; i++){
        listBox.options[i].selected = true;
    }
}


// This function selects all options in an HTML select input box.
// This function is used to select all the elements of the target list in a cross-select list.
function selectAllCheckboxes(checkAllId, checkboxesName){

	$('#'+checkAllId).click(function () {
        $('input[name^='+checkboxesName+']').prop('checked', this.checked);
    });
	
	$('input[name^='+checkboxesName+']').change(function () {
        var check = ($('input[name^='+checkboxesName+']').filter(":checked").length == $('input[name^='+checkboxesName+']').length);
        $('#'+checkAllId).prop("checked", check);
    });
	
	$('#'+checkAllId).prop('checked', true);
	if(($('input[name^='+checkboxesName+']').filter(":not(:checked)").length>0)){
		$('#'+checkAllId).prop('checked', false);
	 }

}




function replaceURLWithHTMLLinks(inputText) {
	
 	var replacedText, replacePattern1, replacePattern2, replacePattern3;
 	var regex;
 	
 	/* should not be re-link if the inputext contains clickable link */
 	regex = /href/ig;
 	if (inputText.match(regex)) 
 	  return inputText;

    //URLs starting with http://, https://, or ftp://
    replacePattern1 = /(\b((https?|ftp|file):\/\/)[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|]*)/ig;
    replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');

    
    //URLs starting with "www." (without // before it, or it'd re-link the ones done above).
    replacePattern2 = /(^|[^\/])(www\.[-a-z0-9+&@#\/%?=~_()|!:,.;]*[-a-z0-9+&@#\/%=~_()|])/gim;
    replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');
    

       

    //Change email addresses to mailto:: links.
    replacePattern3 = /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)(?!)/gim;
    replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');

   
    
    return replacedText; 
}



/*
	@param field : le nom de l'attribut de l'objet formulaire concern�
	@return la valeur de field
*/
function getFieldValue(field){
	if (field.type == 'text' || field.type == 'textarea' || field.type == 'password'|| field.type == 'file' || field.type == 'select-one'){
		var value = '';
		if (field.type == 'select-one') {
			var si = field.selectedIndex;
			if (si >= 0) {
				value = field.options[si].value;
			}
		}else {
			value = field.value;
		}
		var result = $.trim(value);
		if(result==""){
			return null;
		}else{
			return result;
		}
	}else if(field.type == 'hidden'){
		var value = $.trim(field.value);
		if(value=="" || value=="null"){
			return null;
		}else{
			return value;
		}
	}else if(field.type == 'radio' || field.type == 'checkbox'){
		if(field.checked){
			 return field.value;
		}else{
			return null;
		}
	}else{
		var result= new Array();
		indexResult = 0;
		for (var index = 0; index<field.length ;index++){
   			var item = field[index];
   			var value = getFieldValue(item);
   			if(value!=null){
   				result[indexResult]=value;
 				indexResult++;
 			}
		}
		if(result.length > 0){
			return result;
		}else{
			return null;
		}
	}
}

function isDecimalNumberWith2Digits(input){
	var expression = new RegExp("[-+]?^[0-9]+([.,]([0-9]){1,2})?$");
	return expression.test(input);
}

function isDecimalNumber(input){
	var expression = new RegExp("[-+]?^[0-9]+([.,]([0-9])+)?$");
	return expression.test(input);
}

function isIntegerNumber(input){
	var expression = new RegExp("[-+]?^[0-9]+(([0-9])+)?$");
	return expression.test(input);
}

function isNumberKey(e, obj, nbDec){
	var key;
	var isCtrl;
	if (window.event) {
		key = window.event.keyCode; //IE
		if (window.event.ctrlKey) 
			isCtrl = true;
		else 
			isCtrl = false;
	}
	else {
		key = e.which; //firefox
		if (e.ctrlKey) 
			isCtrl = true;
		else 
			isCtrl = false;
	}
	
	//e = new Event(e);
	keychar = String.fromCharCode(key);
		
	//Check for comma
	if (obj && nbDec && obj.value.indexOf(",")==-1 && obj.value.indexOf(".")==-1 && (",.").indexOf(keychar) > -1)
		return true;
		
	//Check for decimals
	if(obj && nbDec && isDecimalNumber(obj.value) && ("0123456789").indexOf(keychar) > -1){
		var tableau=(obj.value).split(obj.value.match("[\\.,]"));
		if(tableau.length==2 && tableau[1].length>=nbDec){
			e.stopPropagation();
			return false;
		}
	}
	
	//Check for numbers
	if (("0123456789").indexOf(keychar) > -1)                         
		return true;

	// Check for control keys
	if ((key == null) || (key == 0) || (key == 8) || (key == 9) ||(key == 13) ||(key == 27)) {
		return true;
	}
	
	//if Ctrl is pressed check if other key is in the Allowed array
	if (isCtrl && ("acxv").indexOf(keychar) > -1) {
		return true;
	}
	
	e.stopPropagation();
	return false;
} 

function convertDec(nbr, nbDec){
	var output=""+nbr;
	output = output.replace(',','.');
	if(output=="0"){
		output="0";
	}
	else if(output.substring(output.length-nbDec,output.length)=="00"){
		output=output.substring(0,output.length-nbDec);
	}
	else{
		output=output.substring(0,output.length-nbDec)+"."+output.substring(output.length-nbDec, output.length);
		if(output.substring(0,1)=="."){
			output="0"+output;
		}
	}
	return output;
}


function convertNumber(data){
	var output="0";
	if(data){
		data = data.replace(',','.');
		if(isDecimalNumberWith2Digits(data)){
			var tableau=(data).split(".");

			if(tableau.length==1){
				output=tableau[0].concat(".00");
			}
			else if(tableau.length==2){
				if(tableau[1].length==1){
					output=tableau[0]+"."+tableau[1]+"0";
				}
				else{
					output=tableau[0]+"."+tableau[1].substring(0,2);
				}
			}
		}
	}
	return parseInt(output,10);
}

/*
	@param field : le nom de l'attribut de l'objet formulaire concern�
	@return	l'identifiant de l'element contenant l'erreur associ�e � field
*/
function getErrorsDiv(field){
	if(field){
		if (field.type == 'text' || field.type == 'textarea' || field.type == 'password'||
			field.type == 'file' || field.type == 'select-one' || field.type == 'hidden'||
			field.type == 'radio' || field.type == 'checkbox'){
			if(field.name == 'amountOption'){
				return document.getElementById("errors_financialData_amountClass");
			}else if(field.name == 'customersGroupsUnitOption'){
				return document.getElementById("errors_financialData_customersGroupsUnite");
			}else{
				return document.getElementById("errors_"+field.name);
			}
		}else{
			return getErrorsDiv(field[0]);
		}
	}
}

/*
	@param field : le nom de l'attribut de l'objet formulaire concern�
	colorie les champs de l'attribut
	@return	null
*/
function setClassName(field,classname){
	if (field.type == 'text' || field.type == 'textarea' || field.type == 'password'|| field.type == 'file' ||
		field.type == 'select-one' || field.type == 'radio' || field.type == 'checkbox'){
		field.className = classname;
	}else if(field.type != 'hidden'){
		for(var i=0;i<field.length;i++){
			field[i].className = classname;
		}
	}
	return null;
}

/*
	@param element: l'element � traiter
	retourne vrai si l'�l�ment est vide
*/
function isEmptyElement(element){
	if(element){
		var inner=$.trim(element.innerHTML);
		return inner=="";
	}
	return true;
}


/*
	@param field: le champs � traiter
	retourne vrai si le champs pass� en param�tre est associ� � une erreur
*/
function isErrorField(field){
	var errorDiv = getErrorsDiv(field);
	if(field && field.name == 'financialData_customerName'){
		return(!(isEmptyElement(errorDiv) && isEmptyElement(document.getElementById("errors_financialData_customersGroups"))));
	}else{
		return !isEmptyElement(errorDiv);
	}
}

function getDefaultForm(){
	var submitButton = $('.submitDefault');
	if(submitButton){
		return submitButton.closest("form");
	}
}

function getElementsFromForm(form){
	return form.find('input:not(input[type=button],input[type=submit],input[type=image],button),input[type=text],input[type=password],input[type=radio],input[type=checkbox],textarea,select');
}

/*
	@param form: le formulaire � parcourir
	retourne le premier champs du formulaire qui est associ� � une erreur
*/
function getFirstErrorField(form){
	var elements = getElementsFromForm(form);
	var element;
	for ( i = 0 ; i < elements.size(); i++){
		element = $(elements.get(i));
		if(isErrorField( element )){
			return element;
		};
	}
	return null;
}


/*
	@param form: le formulaire � parcourir
	vide les messages d'erreur du formulaire
*/
function initErrorsDiv(form){
	getElementsFromForm(form).each(function(){
		var errorDiv = getErrorsDiv($(this));
		if(errorDiv){
			errorDiv.innerHTML="";
		}
	});
}

/*
	initialise le focus dans le formulaire pass� en param�tre
*/
function initFocus(form){
	var firstErrorField = getFirstErrorField(form);
	if(firstErrorField!=null){
		window.location="#footer";
		firstErrorField.focus();
	}
}


/*
	initialise la classe des champs du formulaire
*/
function initFieldsClass(form){
	getElementsFromForm(form).each(function(){
		$(this).closest(".form-group").removeClass("has-error");
		if(isErrorField($(this))){
   			$(this).closest(".form-group").addClass( "has-error" );
   		}
	});

}




/*
	retourne vrai si submitCount == 0 et incr�mente celui-ci
*/
var submitCount=0; //variable globale utilis�e pour contraindre � 1 une seule soumission de formulaire
function checkSubmit() {
	if (submitCount == 0){
		submitCount++;
		return true;
	}else{
		return false;
	}
}



/*
	@param field : le nom du champs formulaire concern�
	@param maxlimit : la taille maximal du champs
	@param countinfo : l'objet de la page qui indique le nombre de caract�res restants
*/
function textDecrement(field, maxlength, countinfo) {
	//on recupere une chaine de caract�res dont les retours e la ligne sont exprimes en \r\n (unicite entre les browser)
	if(field==null){
		return null;
	}
	var unicitystring = "";
	if(field.value!=null){
		unicitystring = field.value;
	} else if (field.val()!=null){
		unicitystring = field.val();
	}
  	if (unicitystring.indexOf('\r\n')!=-1){;
  		// this is IE on windows : do nothing
  	}else if (unicitystring.indexOf('\n')!=-1){
  		// this is Firefox on any platform
  		unicitystring = unicitystring.replace ( /\n/g, '\r\n' );
  	}else if(unicitystring.indexOf('\r')!=-1){
  		// this is IE on a Mac
  		unicitystring = unicitystring.replace ( /\r/g, '\r\n' );
  	}

	// if too long
	if (unicitystring.length > maxlength){
		var unicitystring2 = unicitystring.substring(0, maxlength);
		//si le dernier caract�re est un espace "tronque"
		if(unicitystring2.charAt(maxlength-1)=='\r'){
			unicitystring2 = unicitystring.substring(0,maxlength-1);
		}
		if (unicitystring.indexOf('\n')!=-1){
  			// this is Firefox on any platform
  			unicitystring = unicitystring2.replace ( /\r\n/g, '\n' );
  		}else if(unicitystring.indexOf('\r')!=-1){
  			// this is IE on a Mac
  			unicitystring = unicitystring2.replace ( /\r\n/g, '\r' );
  		}else{
  			// this is IE on windows or it is a string without newLine
			unicitystring = unicitystring2;
		}
		if(countinfo){
			countinfo.html(maxlength - unicitystring2.length);
		}
	}else if(countinfo){
		countinfo.html(maxlength - unicitystring.length);
	}
}


/*
	@param func: la fontion � ajouter
	ajoute une fonction � executer lors du chargement de la page
*/
function addLoadEvent(func) {
	var oldonload = window.onload;
	if (typeof window.onload != 'function') {
		window.onload = func;
	} else {
		window.onload = function() {
			oldonload();
			func();
		}
	}
}