/************** 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.password.value == '')
	{
		inscription = false;
		alerte += '- renseigner votre mot de passe\n';
	}
	if(form.cpassword.value == '')
	{
		inscription = false;
		alerte += '- renseigner la confirmation de mot de passe\n';
	}
	if( !form.optinPart[0].checked && !form.optinPart[1].checked)
	{
		inscription = false;
		alerte += '- accepter ou refuser les offres de nos partenaires\n';
	}
	if(form.cpassword.value != '' && form.password.value != '' && form.cpassword.value != form.password.value)
	{
		inscription = false;
		alerte += '- vous assurer que le mot de passe et sa confirmation correspondent\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, width, height)
{
	var _width = width;
	var _height = height;
	if(_width == null) {_width = 450;}
	if(_height == null) {_height = 340;}

	var alerte = new dojox.widget.Dialog({
				title:"Attention",
				dimensions: [_width,_height],
				draggable:false,
				easing: dojo.fx.easing.expoInOut,
				sizeDuration:500,
				sizeMethod:"combine"
			},"alerteErreur");
		alerte.startup();

	dojo.query("#alerteErreur *").onclick(function(evt){
			dijit.byId('alerteErreur').hide();
		});


	if(titre!=null && titre!='')
	{
		dojo.byId("contenuAlerte").innerHTML = titre+'<br />'+message;
	}
	else
	{
		dojo.byId("contenuAlerte").innerHTML = 'Attention<br />'+message;
	}
	//dijit.byId("alerteErreur").show();
	alerte.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: 1000, // 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;
			}
			else
			{
				if(typeof(popup)=='undefined')
				{
					dojo.byId("popup_login").innerHTML = response.popup;

					popup = new dojox.widget.Dialog({
							title:"Attention",
							dimensions: [450,440],
							draggable:false,
							easing: dojo.fx.easing.expoInOut,
							sizeDuration:500,
							sizeMethod:"combine"
						},"popup_login");				
					popup.startup();
					
					dijit.byId("popup_login").show();
				}
				dijit.byId("popup_login").show();
			}
			return response;
		},

		// The ERROR function will be called in an error case.
		error: function(response, ioArgs) {
			console.log( 'erreur : '+response );
			return response;
		}
	});
}


function login( )
{
	dojo.byId("popup_message").innerHTML = '';
	var email = dojo.byId("popup_email").value;
	var pass = dojo.byId("popup_mdp").value;
	
	dojo.xhrPost( {
		// The following URL must match that used to test the server.
		url: "../scripts/ajax/login.php", 
		handleAs: "json",
		timeout: 2000, // Time in milliseconds
		content: {
			email: email,
			pass : pass
		},
		preventCache: true,

		// The LOAD function will be called on a successful response.
		load: function(response, ioArgs) {
			if(response.statut=="OK")
			{
				if( dojo.byId("page_voulu").value == "loterie" )
					window.location.href = "loterie.php";
				else if ( dojo.byId("page_voulu").value == "parrainage" )
					window.location.href = "parrainage.php";
			}
			else
			{
				dojo.byId("popup_message").innerHTML = response.erreur;
			}
			return response;
		},

		// The ERROR function will be called in an error case.
		error: function(response, ioArgs) {
			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. Vous serez averti par email lors de son traitement.<br /><br />Si vous n\'avez pas encore mis à jour vos données personnelles, faites le maintenant en vous rendant sur <a href="mon-profil.php" style="color:white;cursor:pointer;text-decoration:none;font-weight:bold;">mon profil</a>.<br /><br />Si votre profil n\'est pas à jour au moment du traitement de votre commande, alors la commande sera annulée et les points Kaliflooz correspondant seront perdus.';
				//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: 10000, // 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: 25000, // 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 *****************************/



function afficheLayer(message, width, height)
{
	var _width = width;
	var _height = height;
	if(_width == null) {_width = 700;}
	if(_height == null) {_height = 500;}

	/*var layer = new dojox.widget.Dialog({
			title:"Actualité Kalifoo",
			dimensions: [_width,_height],
			draggable:false,
			easing: dojo.fx.easing.expoInOut,
			sizeDuration:500,
			sizeMethod:"combine"
		},"popup_actualite");
	layer.startup();*/

	var layer = new dojox.widget.Dialog({
				title:"Attention",
				dimensions: [_width,_height],
				draggable:false,
				easing: dojo.fx.easing.expoInOut,
				sizeDuration:500,
				sizeMethod:"combine"
			},"popupActualite");
	layer.startup();

	dojo.byId("popupActualite").innerHTML = message;
	
	dojo.query("#popupActualite *").onclick(function(evt){
		dijit.byId('popupActualite').hide();
	});

	layer.show();
}


/*********************** GESTION MENU ******************************/
var menuids=new Array("onglets") //Enter id(s) of UL menus, separated by commas
var submenuoffset=-2 //Offset of submenus from main menu. Default is -2 pixels.

function createcssmenu(){
for (var i=0; i<menuids.length; i++){
  var ultags=document.getElementById(menuids[i]).getElementsByTagName("ul")
	for (var t=0; t<ultags.length; t++){
	/*var spanref=document.createElement("span")
		spanref.className="arrowdiv"
		spanref.innerHTML="&nbsp;&nbsp;"
		ultags[t].parentNode.getElementsByTagName("a")[0].appendChild(spanref)*/
	ultags[t].parentNode.onmouseover=function(){
	this.getElementsByTagName("ul")[0].style.left=this.parentNode.offsetWidth+submenuoffset+"px"
	this.getElementsByTagName("ul")[0].style.display="block"
	}
	ultags[t].parentNode.onmouseout=function(){
	this.getElementsByTagName("ul")[0].style.display="none"
	}
	}
  }
}
if (window.addEventListener)
	window.addEventListener("load", createcssmenu, false)
else if (window.attachEvent)
	window.attachEvent("onload", createcssmenu)
/*********************** GESTION MENU ******************************/