// JavaScript Document
/*	Textfield-filter.js
**	
**	Ensemble de fonction servant à la validation du contenu des champs
**	de text, des enquêtes de satisfaction.
*/

/*
	Developed by Robert Nyman, http://www.robertnyman.com
	Code/licensing: http://code.google.com/p/getelementsbyclassname/
*/	
var getElementsByClassName = function (className, tag, elm){
	if (document.getElementsByClassName) {
		getElementsByClassName = function (className, tag, elm) {
			elm = elm || document;
			var elements = elm.getElementsByClassName(className),
				nodeName = (tag)? new RegExp("\\b" + tag + "\\b", "i") : null,
				returnElements = [],
				current;
			for(var i=0, il=elements.length; i<il; i+=1){
				current = elements[i];
				if(!nodeName || nodeName.test(current.nodeName)) {
					returnElements.push(current);
				}
			}
			return returnElements;
		};
	}
	else if (document.evaluate) {
		getElementsByClassName = function (className, tag, elm) {
			tag = tag || "*";
			elm = elm || document;
			var classes = className.split(" "),
				classesToCheck = "",
				xhtmlNamespace = "http://www.w3.org/1999/xhtml",
				namespaceResolver = (document.documentElement.namespaceURI === xhtmlNamespace)? xhtmlNamespace : null,
				returnElements = [],
				elements,
				node;
			for(var j=0, jl=classes.length; j<jl; j+=1){
				classesToCheck += "[contains(concat(' ', @class, ' '), ' " + classes[j] + " ')]";
			}
			try	{
				elements = document.evaluate(".//" + tag + classesToCheck, elm, namespaceResolver, 0, null);
			}
			catch (e) {
				elements = document.evaluate(".//" + tag + classesToCheck, elm, null, 0, null);
			}
			while ((node = elements.iterateNext())) {
				returnElements.push(node);
			}
			return returnElements;
		};
	}
	else {
		getElementsByClassName = function (className, tag, elm) {
			tag = tag || "*";
			elm = elm || document;
			var classes = className.split(" "),
				classesToCheck = [],
				elements = (tag === "*" && elm.all)? elm.all : elm.getElementsByTagName(tag),
				current,
				returnElements = [],
				match;
			for(var k=0, kl=classes.length; k<kl; k+=1){
				classesToCheck.push(new RegExp("(^|\\s)" + classes[k] + "(\\s|$)"));
			}
			for(var l=0, ll=elements.length; l<ll; l+=1){
				current = elements[l];
				match = false;
				for(var m=0, ml=classesToCheck.length; m<ml; m+=1){
					match = classesToCheck[m].test(current.className);
					if (!match) {
						break;
					}
				}
				if (match) {
					returnElements.push(current);
				}
			}
			return returnElements;
		};
	}
	return getElementsByClassName(className, tag, elm);
};



/*
** Cette méthode est appelée lorsqu'une vérification sur un 
** champ de texte est nécessaire
**
**	@param value : valeur à vérifier.
**	@param divName : nom du div à modifier pour l'affichage.
**
*/
function checkValidity(value, divName, type){
	if (type == '1'){
		checkEmail(value, divName);
	}
	else if (type == '2'){
		checkPhone(value, divName);
	}
	else if (type == '3'){
		checkAlpha(value, divName);
	}
	else if (type == '4'){
		checkDate(value, divName);
	}
	else {
		alert('TextInput Type Invalid !');
	}

}


/*
**	checkEmail(email, divName)
**	@param email : cette choix doit correspondre Ã  un email valide.
**	@param divName : nom du div Ã  modifier pour l'affichage.
*/
function checkEmail(email, divName) {
	var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
	
	setDisplayMode(email, filter, divName);
}

/*
**	checkAlpha(text, divName)
**	@param text : cette choix doit correspondre Ã  un email valide.
**	@param divName : nom du div Ã  modifier pour l'affichage.
*/
function checkAlpha(text, divName) {
	//var filter = /^([a-zA-Z\- ])+$/;
	var filter = /^([^0123456789\#=+\\\$\*\%\|\(\[\)\]\{\}\?\!\,\;\:\.\/\@\Â£])+$/;
	setDisplayMode(text, filter, divName);

}

/*
**	checkPhone(text, divName)
**	@param text : cette choix doit correspondre Ã  un numero de tÃ©lÃ©phone valide.
**	@param divName : nom du div Ã  modifier pour l'affichage.
*/
function checkPhone(text, divName) {
	var filter = /^([0-9\-\+\(\)\ ]){5}([0-9\-\+\(\)])+$/;
	setDisplayMode(text, filter, divName);

}

/*
** checkDate(text, divName)
** @param text : ce champs doit correspondre Ã  une date valide.
** @param divName : nom du div Ã  modifier pour l'affichage.
*/
function checkDate(text, divName) {
	var filter = /^[0-3][0-9]\/[0-1][0-9]\/[2][0-9][0-9][0-9]$/;
	setDisplayMode(text, filter, divName);
}


function setDisplayMode(txt, filter, divName){
	check[divName] = false;
	if (!filter.test(txt)) {
		setErrorMode(divName);			
	}
	else {
		setGoodMode(divName);
		check[divName] = true;
	}
}


function setErrorMode(divName){
	document.getElementById(divName + "Img").src = "images/icons/delete.png";
	document.getElementById(divName + "Img").style.visibility = "visible";
	//document.getElementById(divName + "Error").style.display = "inline";
	//document.getElementById("trucmuche").style.border = "1px solid red";	
	
}
function setGoodMode(divName){
	document.getElementById(divName + "Img").src = "images/icons/accept.png";
	document.getElementById(divName + "Img").style.visibility = "visible";
	//document.getElementById(divName + "Error").style.display = "none";		
	//document.getElementById(divName + "Good").style.display = "inline";
	//document.getElementById(divName).style.border = "none";
}



function verifForm(f, resultId, errorEmpty, errorFill) {
	var result = document.getElementById(resultId);
	var ok = true;
	var elts = getElementsByClassName('required');
	for(var i = 0; i < elts.length; i += 1) {
		var eName = elts[i].name;
		var count = 0;
		var arr = new Array();
		
		if (elts[i].type == "radio") {
			ok = verifRadioArr(arr, ok);
		}
		if (elts[i].type == "text") {
			ok = verifText(elts[i], ok);
		}
		if (elts[i].type == "textarea") {
			ok = verifTextArea(elts[i], ok);
		}
		if (elts[i].type == "select-one") {
			ok = verifSelectOne(elts[i], ok);
		}
	}
	if (ok === false){
		//alert(errorEmpty);
		configureElement(result, errorEmpty,{display:"inline", color:"#ff0000"});
		return false;
	}
	go = true;
	for (var n in check) {
    	if (check[n] === false) {
    		go = false;
    	}
    }
    if (go === true) {
			//f.submit();
			configureElement(result, errorEmpty,{display:"none"});
			return true;
	}
	else {
			//alert(errorFill);
			configureElement(result, errorFill,{display:"inline", color:"#ff0000"});
			return false;
	}
	return false;
}



/*	verifRadio(f, i, ok, count)
**	Vérifie que toute les questions "radio" on été répondue
**	Ne s'utilise qu'avec la fonction verifForm(form)
*/
function verifRadio(f, i, ok, count) {
	for(var k = 0; k < count; k += 1) {		
		if (f.elements[i + k].checked) {	
			if (ok !== false) {
				return true;
			}
		}
	}
	return false;
}

function verifRadioArr(arr, ok){
	for (var k = 0; k < arr.length; k += 1){
		if (arr[k].checked && ok !== false){
			return true;
		}
	}
	return false;
}

/*	verifText(f, i, ok)
**	Vérifie que toute les questions "text" on été répondue
**	Ne s'utilise qu'avec la fonction verifForm(form)
*/
function verifText(elt, ok) {

	elt.focus();
	elt.blur();
	
	if (elt.value !== "" && elt.value !== null) {
			if (ok !== false)
			{
				return true;
			}
	}
	return false;
}

/*	verifTextArea(f, i, ok)
**	Vérifie que toute les questions "textArea" on été répondue
**	Ne s'utilise qu'avec la fonction verifForm(form)
*/
function verifTextArea(elt, ok) {
	if (elt.value.length !== 0) {
			setGoodMode(elt.name);
			if (ok !== false) {				
				return true;
			}
	}
	else{
		setErrorMode(elt.name);
	}
	return false;
}

/* verifSelectOne(f, i, ok)
** Vérifie que toute les questions "select-one" on été répondue
** Ne s'utilise qu'avec la fonction verifForm(form)
*/
function verifSelectOne(elt, ok) {

	if (elt.options[elt.selectedIndex].value != "-1") {
		if (ok !== false) {	
			return true;
		}
	}
	setErrorMode(elt.name);
	return false;
}


/**

Take a HTML element and :
 - set innerHTML
 - iterate through styleOpts if present and apply all styles defined in it
*/
function configureElement(elt, htmlContent, styleOpts){
	if(styleOpts)
	{
		for(var k in styleOpts)
		{
			elt.style[k] = styleOpts[k];
		}
	}
	elt.innerHTML = htmlContent;
}





function FillForm() {
	// To customize your form, specify form's name between the quotes on the next line.
	var FormName = "form1";

	// Find the location of the ? in the URL.
	var questionlocation = location.href.indexOf('?');

	// If no ?, return out of the function.
	if(questionlocation < 0) { return; }

	// Assign the text following the ? to variable q
	var q = location.href.substr(questionlocation + 1);
	
	// Split q on & characters and assign to array variable list.
	var list = q.split('&'); 

	// For each element of array list, execute the {} block.
	for(var i = 0; i < list.length; i++) {

	   // Split the list array element on = character and 
	   //   assign the pieces to array variable kv.
	   // kv[0] will then contain the field name and kv[1] 
	   //   will contain the field value.
	   var kv = list[i].split('=');
				   
	   // If the form does not have a field name kv[0], go to the top of the {} loop and continue there.
		if(! eval('document.'+FormName+'.'+kv[0])) { continue; }
	
	   // Convert %##'s to the actual characters.
	   //    will%20%22B%22 becomes: will "B"
	   //    will%40example.com becomes: will@example.com
	   kv[1] = unescape(kv[1]);

	   // If value kv[1] contains a " character, execute the 
	   //   {} loop.
	   // (The " character needs to be escaped because the 
	   //   value in the eval() function below uses " for field 
	   //   value delimiters.)
	   if(kv[1].indexOf('"') > -1) {
	
		  // Assign a regular expression to variable re. The  expression looks for all " characters.
		  var re = /"/g;
	
		  // In kv[1], replace each " character with: \" (The \ itself needs to be escaped here.)
		  kv[1] = kv[1].replace(re,'\\"');
	   }

	   // Create an evaluation expression for the eval() 
	   //   function that assigns the value kv[1] to the 
	   //   form field kv[0].
	   eval('document.'+FormName+'.'+kv[0]+'.value="'+kv[1]+'"');
	}
}






/*  Browser Detection Configuration */

var BrowserDetect = {
	init: function () {
		this.browser = this.searchString(this.dataBrowser) || "An unknown browser";
		this.version = this.searchVersion(navigator.userAgent)
			|| this.searchVersion(navigator.appVersion)
			|| "an unknown version";
		this.OS = this.searchString(this.dataOS) || "an unknown OS";
	},
	searchString: function (data) {
		for (var i=0;i<data.length;i++)	{
			var dataString = data[i].string;
			var dataProp = data[i].prop;
			this.versionSearchString = data[i].versionSearch || data[i].identity;
			if (dataString) {
				if (dataString.indexOf(data[i].subString) != -1)
					return data[i].identity;
			}
			else if (dataProp)
				return data[i].identity;
		}
	},
	searchVersion: function (dataString) {
		var index = dataString.indexOf(this.versionSearchString);
		if (index == -1) return;
		return parseFloat(dataString.substring(index+this.versionSearchString.length+1));
	},
	dataBrowser: [
		{
			string: navigator.userAgent,
			subString: "Chrome",
			identity: "Chrome"
		},
		{ 	string: navigator.userAgent,
			subString: "OmniWeb",
			versionSearch: "OmniWeb/",
			identity: "OmniWeb"
		},
		{
			string: navigator.vendor,
			subString: "Apple",
			identity: "Safari",
			versionSearch: "Version"
		},
		{
			prop: window.opera,
			identity: "Opera"
		},
		{
			string: navigator.vendor,
			subString: "iCab",
			identity: "iCab"
		},
		{
			string: navigator.vendor,
			subString: "KDE",
			identity: "Konqueror"
		},
		{
			string: navigator.userAgent,
			subString: "Firefox",
			identity: "Firefox"
		},
		{
			string: navigator.vendor,
			subString: "Camino",
			identity: "Camino"
		},
		{		// for newer Netscapes (6+)
			string: navigator.userAgent,
			subString: "Netscape",
			identity: "Netscape"
		},
		{
			string: navigator.userAgent,
			subString: "MSIE",
			identity: "Explorer",
			versionSearch: "MSIE"
		},
		{
			string: navigator.userAgent,
			subString: "Gecko",
			identity: "Mozilla",
			versionSearch: "rv"
		},
		{ 		// for older Netscapes (4-)
			string: navigator.userAgent,
			subString: "Mozilla",
			identity: "Netscape",
			versionSearch: "Mozilla"
		}
	],
	dataOS : [
		{
			string: navigator.platform,
			subString: "Win",
			identity: "Windows"
		},
		{
			string: navigator.platform,
			subString: "Mac",
			identity: "Mac"
		},
		{
			   string: navigator.userAgent,
			   subString: "iPhone",
			   identity: "iPhone/iPod"
	    },
		{
			string: navigator.platform,
			subString: "Linux",
			identity: "Linux"
		}
	]

};
BrowserDetect.init();




