var numeros = new Array;
var numerosMAX = 6;

dojo.addOnLoad(function(){
	dojo.query("#grille td")
	.onmouseover(function(evt) {

		if(evt.target.style.backgroundColor != "rgb(235, 205, 228)" && evt.target.style.backgroundColor != "#EBCDE4" && evt.target.innerHTML != '')
		{
			dojo.style(evt.target, {background : "#ffcc04", cursor : "pointer"});
		}/*
		else if(evt.target.innerHTML != '')
		{
			dojo.style(evt.target, {cursor : "url('../images/loterie/gomme.cur')" });
		}*/
	})
	.onmouseout(function(evt) {
		if(evt.target.style.backgroundColor != "rgb(235, 205, 228)" && evt.target.style.backgroundColor != "#EBCDE4" && evt.target.innerHTML != '')
		{
			dojo.style(evt.target, {background : "", cursor : "pointer"});
		}
	})
	.onclick(function(evt) {
		if(evt.target.innerHTML != '' || (evt.target.tagName == 'IMG' && evt.target.parentNode.id != '') )
		{
			// Recup du numero selectionné
			var numero = evt.target.id;
			if(!numero)
			{
				var numero = evt.target.parentNode.id;
			}

			// Verification si numero deja choisi
			if(numeroDejaPresent(numeros, numero)) 
			{
				// On retire numéro
				caseDeselectionne(numero);
			}				
			else if(numeros.size() < numerosMAX)
			{
				// Ajout du numero
				caseSelectionnee(numero);
			}
			else
			{
				declencheErreur('Vous avez déjà joué vos '+numerosMAX+' numéros');
			}
		}
	});
});



function caseSelectionnee(numero_selectionne)
{
	// Ajout du numéro selectionné dans le tableau
	numeros.push(numero_selectionne);

	var index_numero = numeros.size();

	// Ajout des images et input des numeros joues
	dojo.byId('numero_'+index_numero).innerHTML = '<img src="images/loterie/'+numero_selectionne+'.gif" /><input type="hidden" name="numero_'+index_numero+'" value="'+numero_selectionne+'" />';
	//image_numero.innerHTML = '<img src="images/loterie_v2/plume_grille.gif" height="25px" /><input type="hidden" name="numero_'+index_numero+'" value="'+numero_selectionne+'" />';

	// Mise en couleur des numeros joues
	//dojo.query('#'+numero_selectionne).style({background : "#EBCDE4", color : "#cb2c02", fontWeight : "bold" });
	var case_selectionnee = dojo.byId(''+numero_selectionne);
	case_selectionnee.innerHTML = '<img src="/images/loterie_v2/plume_grille.png" height="25px" />';
	dojo.style(case_selectionnee, 'background', '#ebcde4');

	if(numeros.size() >= numerosMAX)
	{
		dojo.style('etape2', {display : "block" });

		// on deplace l'ecran sur les bannieres de valid
		var anim0 = dojox.fx.smoothScroll({ node: 'etape2', win: window, duration:700, easing:dojo.fx.easing.easeOut });
		anim0.play();
	}
}

function caseDeselectionne(numero_deselectionne)
{
	// On retire le numero du tableau
	var index_a_enlever = dojo.indexOf(numeros, numero_deselectionne);
	numeros.splice(index_a_enlever, 1);

	// on garde une copie du tableau à jour avant effacer()	
	var numeros_ok = dojo.clone(numeros);

	var numeros_ok2 = new Array();
	numeros_ok2 = numeros_ok

	// on remet a zero la grille
	effacer();

	// On remet les effets visuels pour les numeros joués
	dojo.map(numeros_ok,
	  function(elem) { caseSelectionnee(elem);  }
	);
}

function choixAutomatique()
{
	effacer();

	var rng = new RNG(new Date());
	for (var i = 0; i < 50 && numeros.size() < numerosMAX; i++ )
	{
		var numero = rng.nextRange(1,50);
		if(! numeroDejaPresent(numeros, numero))
		{
			caseSelectionnee(numero);
		}
	}
}



function numeroDejaPresent(tableau, numeroATester)
{
	var tableau_tmp = tableau.clone();
	tableau_tmp.push(numeroATester);
	tableau_tmp = tableau_tmp.uniq();

	if (tableau.size()+1 == tableau_tmp.size())
	{
		return false;
	}
	else
	{
		return true;	
	}
}

function effacer()
{
	// remise a zero des numeros selectionnés
	dojo.query("#recap_numeros li, #numero_7").forEach(function(node, index, array){
		node.innerHTML = '<img src="images/loterie/rond_rouge.gif" />';
		dojo.style('etape2', {display : "none" });
	});

	// remise a zero du style visuels de la grille
	dojo.query("#grille td").forEach(function(node, index, array){
		node.style.background = '';
		node.style.color = '#cb2c02';
		node.style.fontWeight = 'normal';
		node.innerHTML = node.id;
	});

	// remise a zero du tableau des numeros joues
	numeros.clear();
}




function testNumero7()
{
	var code = dojo.byId('code');
	if(code == null || code.value == '')
	{
		declencheErreur('Vous devez saisir le code fourni lors de l\'appel téléphonique pour obtenir un 7<sup>ème</sup> numéro');
	}
	else
	{
		//dojo.byId('numero7_bas').innerHTML = '<br /><br/ ><img src="images/loterie/ajax-loader.gif" />';
		//dojo.style('numero7_bas', {display : "none" });
		//dojo.style('numero7_loader', {display : "block" });

		dojo.xhrPost({
		// form: "someFormId", // read the url: from the action="" of the <form>
		url: 'includes/audiotel_loterie.php',
		timeout: 15000, // give up after 3 seconds
		content: { code: code.value }, // creates ?part=one&another=part with GET, Sent as POST data when using xhrPost
		load: function(data, ioArgs){
			if(data == 'ok')
			{
				//dojo.style('avec6numeros', {display : "none" });
				//dojo.style('avec7numeros', {display : "block" });
				dojo.style('numero_7', {display : "block" });
				dojo.style('etape2', {display : "none" });
				numerosMAX = 7;
				getCommandeAudiotel(numerosMAX);
			}
			else
			{
				dojo.style('numero_7', {display : "none" });
				declencheErreur('Le code saisi n\'est pas correct.');
				//dojo.style('numero7_bas', {display : "block" });
				//dojo.style('numero7_loader', {display : "none" });
			}
		},
		error: function(err, ioArgs){
			dojo.style('numero_7', {display : "none" });
			declencheErreur('Une erreur inattendue est survenue.');
			//dojo.style('numero7_bas', {display : "block" });
			//dojo.style('numero7_loader', {display : "none" });
		}

		});
	}
}


function validerGrille(id, grille_id)
{
	var form = dojo.byId("form_grille");

	var input1 = document.createElement('input');
    input1.setAttribute('type', 'hidden');
	input1.setAttribute('name', 'banniere_validation_id');
	input1.setAttribute('value', id);
	form.appendChild(input1);

	var input2 = document.createElement('input');
    input2.setAttribute('type', 'hidden');
	input2.setAttribute('name', 'banniere_validation_grille');
	input2.setAttribute('value', grille_id);
	form.appendChild(input2);
	
	document.form_grille.submit();

	/*
	// ouverture pop up validation
	var url_PU = 'loterie_validation.php';		
	var newWin = window.open( url_PU, 'fenetreloterie'+id, 'left=0,top=0, width=410, height=470, scrollbars=0, resizable=0, toolbar=0, location=0, menubar=0, status=0, directories=0' );
	// work around pour safari
	if(typeof newWin == 'undefined') 
	{
		newWin = window.open( '', 'fenetreloterie'+id, options);

		try{ 
		newWin.location.href = url_PU; 
		}catch(ex){ 
		alert(error); 
		} 
	}

	newWin.focus(); 
	*/
}


function revenirAuJeu(type)
{
	if(type=='loterie')
	{
		window.open('loterie.php', 'loterie'+new Date().getTime(), 'left=0,top=0, width=1000, height=800, scrollbars=1, resizable=1, toolbar=1, location=1, menubar=1, status=1, directories=1');
	}
	else if(type=='concours')
	{
		window.open('gagner-cadeaux-gratuits.html', 'concours', 'left=0,top=0, width=1000, height=800, scrollbars=1, resizable=1, toolbar=1, location=1, menubar=1, status=1, directories=1'); 
	}
	else if(type=='planjour')
	{
		window.open('plan-jour.php', 'planjour', 'left=0,top=0, width=1000, height=800, scrollbars=1, resizable=1, toolbar=1, location=1, menubar=1, status=1, directories=1');
	}
	this.close();
}


function getFavoris(id_joueur) 
{
	if(dojo.byId("favoris").style.visibility == 'visible')
	{
		dojo.style('favoris', {visibility : "hidden" });
	}
	else
	{
		dojo.xhrGet( {
			// The following URL must match that used to test the server.
			url: "../scripts/ajax/favoris_selection.php", 
			handleAs: "text",
			timeout: 2000, // Time in milliseconds
			content: {
					id: id_joueur
			},

			// The LOAD function will be called on a successful response.
			load: function(response, ioArgs) {
				dojo.byId("favoris").innerHTML = response;
				dojo.fx.wipeIn({node: 'favoris', duration: 400 }).play();
				dojo.style('favoris', {visibility : "visible" });
				return response;
			},

			// The ERROR function will be called in an error case.
			error: function(response, ioArgs) {
				dojo.byId("favoris").innerHTML = 'Impossible de charger vos favoris';
				dojo.fx.wipeIn({node: 'favoris', duration: 400 }).play();
				dojo.style('favoris', {visibility : "visible" });
				//console.error("HTTP status code: ", ioArgs.xhr.status);
				return response;
			}
		});
	}
}

function enregistrerFavoris(id_joueur)
{
	if(numeros.size() >= numerosMAX)
	{		
		var favoris = dojo.clone(numeros);
		
		if(numerosMAX == 6 && numeros.size() == 6)
		{
			favoris.push(0);
		}

		dojo.xhrPost( {
			// The following URL must match that used to test the server.
			url: "../scripts/ajax/favoris_enregistre.php", 
			handleAs: "text",
			timeout: 2000, // Time in milliseconds
			content: {
					id: id_joueur,
					numero_1: favoris[0],
					numero_2: favoris[1],
					numero_3: favoris[2],
					numero_4: favoris[3],
					numero_5: favoris[4],
					numero_6: favoris[5],
					numero_7: favoris[6]					
			},

			// The LOAD function will be called on a successful response.
			load: function(response, ioArgs) {
				dojo.byId("favoris_enregistre").innerHTML = response;
				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;
			}
		});
	}
	else
	{
		declencheErreur('Pour enregistrer cette grille en tant que favoris, vous devez sélectionner vos '+numerosMAX+' numéros');
	}
}


function supprimerFavoris(id)
{
	dojo.xhrPost( {
			// The following URL must match that used to test the server.
			url: "../scripts/ajax/favoris_supprime.php", 
			handleAs: "text",
			timeout: 2000, // Time in milliseconds
			content: {
					id_favoris: id				
			},

			// The LOAD function will be called on a successful response.
			load: function(response, ioArgs) {
				dojo.byId("favoris").removeChild(dojo.byId("favoris_"+id));
				//dojo.byId("favoris_"+id).innerHTML = response;
				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 de supprimer ce favoris');
				//console.error("HTTP status code: ", ioArgs.xhr.status);
				return response;
			}
		});
}

function utiliserFavoris(numero1, numero2, numero3, numero4, numero5, numero6, numero7 )
{
	// Remise a zero de la grille et des numeros
	effacer();
	
	var favoris = Array();
	favoris.push(numero1);
	favoris.push(numero2);
	favoris.push(numero3);
	favoris.push(numero4);
	favoris.push(numero5);
	favoris.push(numero6);
	if(numero7!=0)
	{
		favoris.push(numero7);
	}

	dojo.style('favoris', {visibility : "hidden" });

	for (var i = 0; i < 7 && i < numerosMAX ; i++ )
	{
		numero = favoris[i];

		if( isNaN(numero) == false && numero != 0 )
		{
			caseSelectionnee(numero);
		}
	}
}

function getCommandeAudiotel(nombreNumeros) 
{
	if(dojo.byId("commandeAudiotel").style.visibility == 'visible')
	{
		dojo.style('commandeAudiotel', {visibility : "hidden" });
	}
	else
	{
		dojo.xhrGet( {
			// The following URL must match that used to test the server.
			url: "../scripts/ajax/7emenumero_selection.php", 
			handleAs: "text",
			timeout: 2000, // Time in milliseconds
			content: {
				nbNumeros: nombreNumeros
			},

			// The LOAD function will be called on a successful response.
			load: function(response, ioArgs) {
				dojo.byId("commandeAudiotel").innerHTML = response;
				dojo.fx.wipeIn({node: 'commandeAudiotel', duration: 400 }).play();
				dojo.style('commandeAudiotel', {visibility : "visible" });
				return response;
			},

			// The ERROR function will be called in an error case.
			error: function(response, ioArgs) {
				dojo.byId("commandeAudiotel").innerHTML = 'Impossible de charger les informations concernant le 7ème numero';
				dojo.fx.wipeIn({node: 'commandeAudiotel', duration: 400 }).play();
				dojo.style('commandeAudiotel', {visibility : "visible" });
				//console.error("HTTP status code: ", ioArgs.xhr.status);
				return response;
			}
		});
	}
}