alias='Tables-9';
var tableau, _tableau;

Event.observe(
	$(window),
	'load',
	function(event){
		charger(alias);
	}
);
function charger(alias){
    tableau=new _tableau(alias);
    $('score')?tableau.dispacheTableau():false;
    tableau.click=$('tableau')?$('tableau').observe(
        'click',
        tableau.onClick
    ):false
}


_tableau=Class.create({
    niveau:9,
    time:10,
    essais:2,
    score:0,
    chrono:{},
    initialize:function(alias){
        $('score')?$('score').down('td').update("0 point"):false;
        this.alias=alias;
    },
    dispacheTableau:function(){
        this.json=this.chargeTableau();
        $('question').down('td').update(this.json.question);
        $('question').down('td').style.fontSize="20px";
        $('regle').down('td').update(this.json.regle);
        this.json.nombres.shuffle();
        this.json.nombres.each(function(nombre,clef){
            $('case'+clef).update(nombre);
            $('case'+clef).valeur=nombre;
        });
    
         this.initChronometre();
    },
    chargeTableau:function(){
        this.ajax=new Ajax.Request(
            "index.php?page=script-picbille",
            {
                parameters:{
                    alias:this.alias,
                    niveau:this.niveau
                },
                asynchronous:false,
                requestHeaders: {Accept: 'application/json'},
                encoding:"utf8"
            }
        );
       return this.ajax.transport.responseText.evalJSON();
    },
    afficheImageNombre : function(nombre){
        if(Object.isNumber(nombre)) nombre=""+nombre;
        return nombre.gsub(/([0-9]+)/,"<image src=\"uploads/images/picbille/image/nombreToImage.php.jpg?nombre=#{1}\" title='#{1}' height='60px' valign='middle' alt='chargement...'/>");
    },
    onClick:function(event){
        if($('confirm'))return false;
        element=event.element();
        if(element.tagName=="TD"){
            valeur=element.valeur;
            if(valeur==""+tableau.json.resultat){
                tableau.oui(event);
            }else{
                tableau.non(event);
            }
        }else{
            if(element.up('td')){
                window.case=element.up('td');
                if(element.up('td').valeur==tableau.json.resultat){
                    tableau.oui(event);
                }else{
                    tableau.non(event);
                }
            }
        }
    },
    initChronometre : function(){
        $$('#chronometre td').each(function(t){t.style.visibility="visible"});
        this.startChrono();
    },
    startChrono : function(){
        tableau.time=10;
        this.chrono=new PeriodicalExecuter(tableau.decrementeChrono, 2);
    },
    decrementeChrono : function(pe){
        $('chrono'+tableau.time).style.visibility="hidden";
        if(tableau.time==0){
            pe.stop();
            tableau.alert('Désolé le temps est écoulé<p>La bonne réponse était <p>'+tableau.bonneReponse());
            return;
        }
        tableau.time--;
    },
    relanceJeu:function(){
        $('score').down('td').update(this.score+' point'+(this.score>1?'s':''));
        this.chrono.stop();
        this.essais=2;
        this.dispacheTableau();
    },
    oui : function(event){
        event.stop();
        if(this.incrementeScore()){
            return;
        }else{
            this.alert('<p>Exact<p>Votre score est maintenant de <p>'+this.score);
        }
    },
    non : function(event){
        this.essais--;
        if(this.essais==0){
            this.decrementeScore();
            if(event.element().tagName=="TD"){
                event.element().update(new Element('span').update("Ce n'est pas la bonne solution<br/>Dommage !"));
            }else{
                event.element().up('td').update(new Element('span').update("Ce n'est pas la bonne solution<br/>Dommage !"));
            }
            this.alert('Perdu!\nLa bonne réponse était : <p>'+this.bonneReponse()+"<p>Votre score est de "+this.score);
            return;
        }
            event.stop();
            if(event.element().tagName=="TD"){
                event.element().update(new Element('span').update("Ce n'est pas la bonne solution<br/>Encore un essai"));
            }else{
                event.element().up('td').update(new Element('span').update("Ce n'est pas la bonne solution<br/>Encore un essai"));
            }
    },
    alert : function(texte){
        this.chrono.stop();
        div=new Element('div',{id:"confirm"}).update(texte+"<p><input class=ok type=button value='Ok' onclick='$(this).up(\"div\").remove();tableau.relanceJeu();'/>");
                $$('body').first().insert(div);
    },
    bonneReponse : function(){
        return $$('td[id^=case]').find(function(t){return t.valeur==window.tableau.json.resultat;}).innerHTML;
    },
    decrementeScore:function(){
        this.score--;
        if(this.score<0){
            this.score=0;
        }
    },
    incrementeScore : function(){
        this.score++;
        if(this.score>=10){
            return this.maxAtteint();
        }
        return false;
    },
    maxAtteint: function(){
       if(confirm("Bravo! vous avez atteint le score maximum.\n Voulez-vous faire une autre partie?")){
            this.score=0;
            this.relanceJeu();
            return false;
       }else{
            window.location.href='/Tables'
       }
    }
 });