/*----------------------------------------------*/
/*         JAVASCRIPT DISCRET	 */
/*----------------------------------------------*/

//Associe un evenement à un élément
function addEvent( emt, evt, fnc, bbl)
{
	if( 'attachEvent' in emt) emt.attachEvent( 'on' + evt, fnc); //4 MSIE
	else if( 'addEventListener' in emt) emt.addEventListener( evt, fnc, bbl); //4 ECMA ex: MFF
}


/*----------------------------------------------*/
/*         XMLHTTPRequest		*/
/*----------------------------------------------*/

// Fonction permettant l'initialisation du  XMLHttpRequest en fonction du navigateur 
function getRequester()
{
	var xhr = null;
	try
	{
		xhr = new XMLHttpRequest();// MFF...
	}
	catch (e)
	{
		try
		{
			xhr = new ActiveXObject('Msxml2.XMLHTTP'); //MSIE 6
		}
		catch (e)
		{
			try
			{
				xhr = new ActiveXObject('Microsoft.XMLHTTP'); //MSIE 5
			}
			catch (e){ return false;}
		}
	}
	return xhr;
}

// Création, ouverture, envoi et test de la requete
function ajax( url, vars, callbackFunction)
{
	//Initialisation de l'objet 
	var xhr = getRequester();
	//Ouverture de l'objet 
	xhr.open( 'POST', url, true);
	xhr.setRequestHeader( 'Content-Type', 'application/x-www-form-urlencoded');
	
	xhr.onreadystatechange = function()
	{
		if( xhr.readyState == 4  && xhr.status == 200)
		{
			if( xhr.responseXML && xhr.responseXML.hasChildNodes())
			{
				callbackFunction(xhr.responseXML,true);
			}	
			else if( xhr.responseText)
			{
				callbackFunction(xhr.responseText,false);
			}		
		}
	};
	xhr.send( vars);
}



/*----------------------------------------------*/
/*         fonction AJAX Cheque Cadeaux			*/
/*----------------------------------------------*/
/*validateMe is the function called with onblur each time the user leaves the input box
passed into it is the value entered, the rules (which you could create your own), and the id of the area the results will show in*/
function validateMe(objInput) {

	sVal = objInput.value; //get value inside of input field
	
	sRules = objInput.className.split(' '); // get all the rules from the input box classname
	sRequired = sRules[1]; // determines if field is required or not
	sTypeCheck = sRules[2]; //typecheck are additional validation rules (ie. email, phone, date)
    gShow = sRules[3]; //gShow is the td id where feedback is sent to.
  	if (gShow)
	{
		//sends the rules and value to the asp page to be validated
		http.open("GET", sUrl + (sVal) + "&sRequired=" + (sRequired) + "&sTypeCheck=" + sTypeCheck, true);
		
		http.onreadystatechange = handleHttpResponse; 	// handle what to do with the feedback 
		http.send(null);  
	}
}


function handleHttpResponse() {
	//if the process is completed, decide to do with the returned data
	if (http.readyState == 4) 
  	{
  		sResults = http.responseText.split(","); //results is now whatever the feedback from the asp page was
		//whatever the variable glo_show's (usermsg for example) innerHTML holds, is now whatever  was returned by the asp page. 
    	if (gShow)
		{
			document.getElementById(gShow).innerHTML = "";
			document.getElementById(gShow).appendChild(document.createTextNode(sResults[0]));
		}
  	}
}


function validate()
{
	var tables; 
	tables = document.getElementsByTagName('td')

	for (i=0; i<tables.length; i++)//loop through all the <td> elements 
	{
		// if the class name of that td element is rules check to see if there are error warnings
		if (tables[i].className == "rules")
		{
			//if there is a thank you or its blank then it passes
			if (tables[i].innerHTML == 'ok' || tables[i].innerHTML == '' )
			{
				tables[i].style.color = '#7cb801';//the color is changed to black or stays black
			}
			else
			{
				gErrors = gErrors + 1; //the error count increases by 1
				tables[i].style.color = '#253840';//error messages are changed to red
			}
		}
	}
		
	if (gErrors > 0)
	{
		//if there are any errors give a message
		alert ("Vous devez renseigner tous les champs obligatoires. Vos erreurs sont signalées.");
		gErrors = 0;// reset errors to 0
		return false;
	}
	else return true;

}


function getHTTPObject() {
	var xhr = null;
	try
	{
		xhr = new XMLHttpRequest();// MFF...
	}
	catch (e)
	{
		try
		{
			xhr = new ActiveXObject('Msxml2.XMLHTTP'); //MSIE 6
		}
		catch (e)
		{
			try
			{
				xhr = new ActiveXObject('Microsoft.XMLHTTP'); //MSIE 5
			}
			catch (e){ return false;}
		}
	}
	return xhr;

}



// Application de la methode innerHTML avec execution des scripts et des styles (non enregistres par IE en standard)
// Les scripts doivent declarer les fonctions "window.maFunction=function() { ... }" et non pas "function maFunction() { ... }".
viaSetInnerHTML = function( viaHtmlElt, viaHtmlContent ) {
	
	// Securite
	if( typeof viaHtmlElt!='object' ) {
		return false;
	}
	if( !viaHtmlContent ) {
		viaHtmlContent = '';
	}
	
	var viaResult = true;
	
	// Utilisation de la methode standard
	viaHtmlElt.innerHTML=viaHtmlContent;
	
	// Gestion des classes
	/*try {
		var viaAllClasses = viaHtmlElt.getElementsByTagName( "*" );
		for( var i=0; i<viaAllClasses.length; i++ ) {
			viaAllClasses[i].id = viaAllClasses[i].getAttribute( "id" );
			viaAllClasses[i].name = viaAllClasses[i].getAttribute( "name" );
			if( !viaAllClasses[i].className ) {	// Securite en cas de mauvaise interpretation du navigateur
				viaAllClasses[i].className = viaAllClasses[i].getAttribute( "class" );
			}
		}
	} catch( viaEx ) {
		viaResult = false;
	}*/
	
	// Gestion des scripts
	try {
		var viaAllScripts = viaHtmlContent.viaExtractTags( "script" );
		viaForEach(
			viaAllScripts,
			function ( viaScript ) {
				// Suppression des commentaires HTML
				var viaMatches = viaScript.match( /^\s*<!--\s*((?:.*\s*)*)\s*\/\/-->\s*$/ );
				if( viaMatches ) {
					viaScript = viaMatches[1];
				}
				// Execution du script
				setTimeout( viaScript, 0 );
			}
		)
	} catch( viaEx ) {
		viaResult = false;
	}
	
	// Gestion des styles
	try {
		var viaAllStyles = viaHtmlContent.viaExtractTags( "style" );
		viaForEach(
			viaAllStyles,
			function ( viaStyle ) {
				var viaStyleSheet = this.viaDocument.createStyleSheet();
				viaStyleSheet.cssText=viaStyle;
				viaStyleSheet.enabled=true;
			},
			true
		)
	} catch( viaEx ) {
		viaResult = false;
	}
	
	return viaResult;
}

// Extraction du contenu de balise
String.prototype.viaExtractTags = function( viaMatchTag ) {
	
	var viaMatchAll = new RegExp( '(?:<'+viaMatchTag+'.*?>)((\n|\r|.)*?)(?:<\/'+viaMatchTag+'>)', 'img' );
	var viaMatchOne = new RegExp( '(?:<'+viaMatchTag+'.*?>)((\n|\r|.)*?)(?:<\/'+viaMatchTag+'>)', 'im' );
	
	var viaResult = this.match( viaMatchAll );
	if( !viaResult ) {
		viaResult = new Array();
	}
	return viaMap(
		viaResult,
		function( viaScriptTag ) {
			return ( viaScriptTag.match( viaMatchOne ) || ['', ''] )[1];
		}
	);
}

// Execution d'une fonction sur tous les elements d'un objet
viaForEach = function( viaObject, viaDelegate, viaOwnPropertiesOnly ) {
	if( typeof( viaDelegate )=="function" ) {
		if( typeof viaOwnPropertiesOnly == 'undefined' ) {
			viaOwnPropertiesOnly = ( viaObject instanceof Array );
		}
		for( var viaKey in viaObject ) {
			var viaOk = ( !viaOwnPropertiesOnly );
			if( !viaOk ) {
				try {
					viaOk = viaObject.hasOwnProperty( viaKey );
				} catch( viaEx ) {}
			}
			if (viaOk) {
				try {
					viaDelegate( viaObject[viaKey], viaKey, viaObject ) ;
				} catch( viaEx ) {}
			}
		}
	}
	return false;
}

// Mappage
viaMap = function( viaObject, viaIterator ) {
	
	viaMapResults = new Array();
	
	var viaDelegate = function( viaValue, viaIndex ) {
		viaMapResults.push( viaIterator( viaValue, viaIndex ) );
	};
	viaOwnPropertiesOnly = ( viaObject instanceof Array );
	for( var viaKey in viaObject ) {
		var viaOk = ( !viaOwnPropertiesOnly );
		if( !viaOk ) {
			try {
				viaOk = viaObject.hasOwnProperty( viaKey );
			} catch( viaEx ) {}
		}
		if (viaOk) {
			try {
				viaDelegate( viaObject[viaKey], viaKey, viaObject ) ;
			} catch( viaEx ) {}
		}
	}
	
	return viaMapResults;
}


