/************** gestion cookie ************/
// Ecriture/ Lecture de cookie
function writeCookie(nom, valeur){
	var argv=writeCookie.arguments;
	var argc=writeCookie.arguments.length;
	var expires=(argc > 2) ? argv[2] : null;
	var path=(argc > 3) ? argv[3] : null;
	var domain=(argc > 4) ? argv[4] : null;
	var secure=(argc > 5) ? argv[5] : false;
	document.cookie=nom+"="+escape(valeur)+
	((expires==null) ? "" : ("; expires="+expires.toGMTString()))+
	((path==null) ? "" : ("; path="+path))+
	((domain==null) ? "" : ("; domain="+domain))+
	((secure==true) ? "; secure" : "");
}
function getCookieVal(offset){
	var endstr=document.cookie.indexOf (";", offset);
	if (endstr==-1) endstr=document.cookie.length;
	return unescape(document.cookie.substring(offset, endstr));
}
function readCookie(nom){
	var arg=nom+"=";
	var alen=arg.length;
	var clen=document.cookie.length;
	var i=0;
	while (i<clen){
		var j=i+alen;
		if (document.cookie.substring(i, j)==arg) return getCookieVal(j);
		i=document.cookie.indexOf(" ",i)+1;
		if (i==0) break;
	}
	return null;
}
function delCookie(nom){
	date=new Date;
	date.setFullYear(date.getFullYear()-1);
	writeCookie(nom,null,date);
}
/************** gestion cookie ************/



function checkInscription(form)
{
	var inscription = true;
	var alerte = 'Attention: pour valider votre inscription, vous devez:\n';
	if(form.civilite.value == '')
	{
		inscription = false;
		alerte += '- renseigner votre civilité\n';
	}
	if(form.nom.value == '')
	{
		inscription = false;
		alerte += '- renseigner votre nom\n';
	}
	if(form.prenom.value == '')
	{
		inscription = false;
		alerte += '- renseigner votre prénom\n';
	}
	if(form.email.value == '')
	{
		inscription = false;
		alerte += '- renseigner votre adresse email\n';
	}
	if( !form.optinPart[0].checked && !form.optinPart[1].checked)
	{
		inscription = false;
		alerte += '- accepter ou refuser les offres de nos partenaires\n';
	}

	if(inscription == false)
	{
		alert(alerte);
	}
	else
	{
		form.submit();
	}
}


function complement_reglement(id)
{
	window.open('complement-reglement.php?id='+id,'Complement_reglement_'+id,'width=550,height=250,noscrollbars');
}

function suivreURL(url, target)
{
	var l  = '';
   var remplacement1 = new RegExp("§","g");
   var remplacement2 = new RegExp("@","g");
	var remplacement3 = new RegExp("_","g");

   l = url.replace(remplacement1,"/").replace(remplacement2,".").replace(remplacement3,"-");
   if (l.charAt(0)=='#') l = l.substring(1,l.length);

   if (target=='_blank')
   {
		window.open(l);
   }
   else
   {
		window.location.href=l;
   }
}


function validerQuestion(id, jeu)
{
	document.question.submit();

	// si ya pas de cookie
	if(readCookie("validation_"+id) == null)
	{
		// ecriture du cookie validité 1 jour
		date = new Date();
		date.setHours(date.getHours()+1);
		
		writeCookie("validation_"+id, "1", date);

		// ouverture site under
		url_SU = 'banniere-validation.php?id='+id+'&jeu='+jeu; 
		var w = window.open(url_SU, 'fenetre'+id ,'width=800, height=600,scrollbars=1, resizable=1, toolbar=1, location=1, menubar=1, status=1, directories=0');
		if (w!=null) 
		{
			w.blur(); 
			window.focus(); 
		}
	}
}



/* declenchement fenetre erreur */
function declencheErreur(message, titre)
{
	if(titre!=null && titre!='')
	{
		dojo.byId("contenuAlerte").innerHTML = titre+'<br />'+message;
	}
	else
	{
		dojo.byId("contenuAlerte").innerHTML = 'Attention<br />'+message;
	}
	dijit.byId("alerteErreur").show();
}



/* generation nombre aleatoire */
function RNG(seed) {
  // LCG using GCC's constants
  this.m = 0x100000000; // 2**32;
  this.a = 1103515245;
  this.c = 12345;

  this.state = seed ? seed : Math.floor(Math.random() * (this.m-1));
}
RNG.prototype.nextInt = function() {
  this.state = (this.a * this.state + this.c) % this.m;
  return this.state;
}
RNG.prototype.nextFloat = function() {
  // returns in range [0,1]
  return this.nextInt() / (this.m - 1);
}
RNG.prototype.nextRange = function(start, end) {
  // returns in range [start, end): including start, excluding end
  // can't modulu nextInt because of weak randomness in lower bits
  var rangeSize = end - start;
  var randomUnder1 = this.nextInt() / this.m;
  return start + Math.floor(randomUnder1 * rangeSize);
}
RNG.prototype.choice = function(array) {
  return array[this.nextRange(0, array.length)];
}


function ouvrirBonPlan(url)
{
	window.open(url, 'bonplan', 'left=0,top=0, width=1000, height=800, scrollbars=1, resizable=1, toolbar=1, location=1, menubar=1, status=1, directories=1');

	window.location='accueil.php';
}

function pageLoguee(type_page)
{
	dojo.xhrGet( {
		// The following URL must match that used to test the server.
		url: "../scripts/ajax/verifie_login.php", 
		handleAs: "json",
		timeout: 300, // Time in milliseconds
		content: {
				page: type_page				
		},
		preventCache: true,

		// The LOAD function will be called on a successful response.
		load: function(response, ioArgs) {
			if(response.status=="ok")
			{
				window.location.href = response.url;
				//console.dir(response);
			}
			else
			{
				declencheErreur(response.message, response.titre);
			}
			return response;
		},

		// The ERROR function will be called in an error case.
		error: function(response, ioArgs) {
			//dojo.byId("favoris_enregistre").innerHTML = 'Impossible d\enregistrer ces favoris';
			//declencheErreur('Une erreur est survenue<br/>Impossible d\'enregistrer ces favoris');
			//console.error("HTTP status code: ", ioArgs.xhr.status);
			return response;
		}
	});
}


/* declenchement fenetre commmande */
function confirmCommande(id, titre, points)
{	
	dojo.style("contenuConfirmCommande", {display : "block"} );
	dojo.style("resultatConfirmation", {display : "none"} );

	dojo.byId("confirm_libelleCadeau").innerHTML = titre;
	dojo.byId("confirm_pointsCadeau").innerHTML = points;
	dojo.byId("resultatConfirmation").innerHTML = '<center>Nous enregistrons votre commande<br /><img src="images/loterie/ajax-loader.gif" /></center>';
	dijit.byId("confirmCommande").show();

	dojo.byId("commande_oui").onclick = function () {
		dojo.style("contenuConfirmCommande", {display : "none"});
		dojo.style("resultatConfirmation", {display : "block"});
	    enregistreCommande(id);
	}
}

/* gestion de la commande de cadeau */
function enregistreCommande(id)
{
	dojo.xhrGet( {
		// The following URL must match that used to test the server.
		url: "../scripts/ajax/cadeau_enregistre.php", 
		handleAs: "json",
		timeout: 1000, // Time in milliseconds
		content: {
				cadeau: id				
		},
		preventCache: true,

		// The LOAD function will be called on a successful response.
		load: function(response, ioArgs) {
			if(response.enErreur == 0)
			{
				dojo.byId("resultatConfirmation").innerHTML = 'Votre commande a bien été enregistrée et sera traitée sous 5 jours ouvrés. <br /><br />Vous serez averti par email lors de son traitement';
				//console.dir(response);
			}
			else
			{
				dojo.byId("resultatConfirmation").innerHTML = 'Votre commande n\'a pas pu être enregistrée.<br /><br/>Motif: '+response.message;
				//console.error(response);
			}
			
			return response;
		},

		// The ERROR function will be called in an error case.
		error: function(response, ioArgs) {
			dojo.byId("resultatConfirmation").innerHTML = 'Votre commande n\'a pas pu être enregistrée.';
			//console.error("HTTP status code: ", ioArgs.xhr.status);
			return response;
		}
	});

}

function repondu()
{
	var bloc = dojo.byId("bloc_banniere").style.display;

	if(bloc!='block')
	{
		dojo.style("bloc_banniere", {display : "block"} );
	}
}


function updateBlocByForm( id_bloc, url_ajax, formulaire)
{	
		dojo.xhrPost( {
			
			url: url_ajax, 
			handleAs: "text",
			timeout: 2000, // Time in milliseconds
			
			form : formulaire,
			
			// The LOAD function will be called on a successful response.
			load: function(response, ioArgs) {
				dojo.byId(id_bloc).innerHTML = response;
				return response;
			},

			// The ERROR function will be called in an error case.
			error: function(response, ioArgs) {
				
				declencheErreur('Une erreur est survenue<br/>');
				
				return response;
			}
		});
}

function updateBloc( id_bloc, url_ajax, tab)
{	
		dojo.xhrPost( {
			
			url: url_ajax, 
			handleAs: "text",
			timeout: 2000, // Time in milliseconds
			
			content :tab, 
			preventCache: true,
			
			
			// The LOAD function will be called on a successful response.
			load: function(response, ioArgs) {
				dojo.byId(id_bloc).innerHTML = response;
				return response;
			},

			// The ERROR function will be called in an error case.
			error: function(response, ioArgs) {				
				declencheErreur('Une erreur est survenue<br/>');				
				return response;
			}
		});
}

 function isEmpty( inputStr ) 
 { 
	 if ( null == inputStr || "" == inputStr ) 
	{ 
		return true;
	} 
	 return false; 
 }
	  
function is_numeric(num)
{
		var exp = new RegExp("^[0-9-.]*$","g");
		return exp.test(num);
}

	
function erreurCouleur( emplacement )
{		
	if (emplacement.substring(1,11) == "mon-profil")
		dojo.query(emplacement).style({border : "1px solid #cb2c02"});
	else if (emplacement.substring(1,26) == "inscription-intermediaire")
		dojo.query(emplacement).style({border : "2px solid #cb2c02"});
}


function justeCouleur( emplacement )
{		
	if (emplacement.substring(1,11) == "mon-profil")
			dojo.query(emplacement).style({border : "1px solid #CCCCCC"});
	else if (emplacement.substring(1,26) == "inscription-intermediaire")
			dojo.query(emplacement).style({border : "1px solid #cb2c02"});
}

/******************************** TELEPHONE *****************************/
function checkTel( numero, emplacement )
{
	if(numero.substring(0,1) == 0 && numero.substring(0,2) != '00' && is_numeric(numero))
	{
		justeCouleur( emplacement );
		if(numero.length == 10){
			valideTel( numero, emplacement );
		}
	}
	else if(numero.length == '' && emplacement.substring(1,26) == "inscription-intermediaire")
	{
		justeCouleur( emplacement );	
	}
	else{
		erreurCouleur( emplacement );
	}
}

function valideTel( numero, emplacement )
{
	if(numero.length == 10)
	{
		if(numero.substring(0,1) == 0 && numero.substring(0,2) != '00' && is_numeric(numero)){
			justeCouleur( emplacement );	
		}
		else{
			erreurCouleur( emplacement );
		}
	}
	else if(numero.length == '' && emplacement.substring(1,26) == "inscription-intermediaire")
	{
		justeCouleur( emplacement );	
	}
	else{
		erreurCouleur( emplacement );
	}	
}
/******************************* FIN TELEPHONE ****************************/

/******************************** CODE POSTAL *****************************/
function checkCP( CP, emplacement )
{
	if(is_numeric(CP) && !isEmpty(CP))
	{
		justeCouleur( emplacement );			
	}

	else
	{
		erreurCouleur( emplacement );
	}
}

function valideCP( CP, emplacement )
{
	if (is_numeric(CP) && CP.length == 5){
		justeCouleur( emplacement );	
	}
	else{
		erreurCouleur( emplacement );
	}
}
/******************************** FIN CODE POSTAL *****************************/