var nbAjaxCall = 0;

jQuery(document).ready(function() {

    /*
    *   regex : seek an expression in a string
    *
    *   @copyright arnaud chiron 28/10/11
    *
    *   @param sPattern : s = expression to seek
    *   @return : b
    */
    $.fn.regex=function(sPattern) {
        return ($(this).val().match(sPattern)) ? true : false;
    }

    $('input.submit').bind('click',function(){
        //Désactive le clic si un appel ajax encore en cours
        if (nbAjaxCall>0) {
            return false;
        }

        return checkNotesValues();
    });

    // ___________________________ NOTES PRINCIPALES __________________________________ //
    checkTable();
    $("#principale #info-saisie-notes-left #cursus").bind('change', checkTable);
    $("#principale #info-saisie-notes-left #annee").bind('change', checkTable);
    $("#principale #info-saisie-notes-left #option").bind('change', checkTable);
    $("#principale #info-saisie-notes-left #specialite").bind('change', checkTable);
    $("#principale #info-saisie-notes-right #mode").bind('change', checkTable);
    $("#principale #info-saisie-notes-right #type").bind('change', checkTable);

    function checkTable()
    {
        
        //Informations requises
        var annee = $("#principale #info-saisie-notes-left  #annee").val();
        var cursus = $("#principale #info-saisie-notes-left  #cursus").val();
        var option = $("#principale #info-saisie-notes-left  #option").val();
        var specialite = $("#principale #info-saisie-notes-left  #specialite").val();
        var mode = $("#principale #info-saisie-notes-right #mode").val();
        var type = $("#principale #info-saisie-notes-right #type").val();
        var niveau = $("#hiddenNiveau").val();
        var redoublement = 0;
        var tableBac = $("#principale #tab-saisie-notes-bac").val();

        //Teste si on est sur une page de notes
        if(niveau==null)
            return false;
        
        $("#principale #tab-saisie-notes").html("");
        $("#principale #tab-saisie-notes").hide();
        $("#principale #tab-saisie-notes-bac").html("");
        $("#principale #tab-saisie-notes-bac").hide();

        //Si toutes les conditions sont remplies, on affiche le tableau
        if(cursus!='' && mode !='' && type !='' && annee!='' && option!='' && specialite!='')
        {
            $("#notesLoader").html("Chargement du tableau des notes en cours...<br /><img src=\"admin/images/ajax-loader2.gif\" alt=\"patientez\" />");
            $('#principale input, #principale select').attr('disabled','disabled');
            $("#notesLoader").show();
            getAjaxNotes(niveau,cursus,mode,type,redoublement,option,specialite);

            //Si c'est une année à BAC
            if(tableBac != null)
            {
                $("#notesLoader-bac").html("Chargement du tableau des notes du bac en cours...<br /><img src=\"admin/images/ajax-loader2.gif\" alt=\"patientez\" />");
                $("#notesLoader-bac").show();
                getAjaxNotes(niveau,cursus,mode,type,redoublement,option,specialite,true);
            }                 
        }        
    }

    // ___________________________ INIT MENTION __________________________________ //
    //if ($('#notesLoader-double').size()!=0) $('#notesLoader-double').html('Pour afficher le tableau de notes de votre ann&eacute;e redoubl&eacute;e, veuillez completer le formulaire ci-dessus.');
    //if ($('#notesLoader').size()!=0) $('#notesLoader').html('Pour afficher le tableau de notes de votre ann&eacute;e, veuillez completer le formulaire ci-dessus.');

    // ___________________________ NOTES REDOUBLEES __________________________________ //
    checkTableDoublement();
    $("#info-saisie-notes-right #double-oui").bind('change', checkTableDoublement);
    $("#info-saisie-notes-right #double-non").bind('change', checkTableDoublement);
    $("#info-saisie-notes-double-left #annee-double").bind('change', checkTableDoublement);
    $("#info-saisie-notes-double-left #cursus-double").bind('change', checkTableDoublement);
    $("#info-saisie-notes-double-left #option-double").bind('change', checkTableDoublement);
    $("#info-saisie-notes-double-left #specialite-double").bind('change', checkTableDoublement);
    $("#info-saisie-notes-double-right #mode-double").bind('change', checkTableDoublement);
    $("#info-saisie-notes-double-right #type-double").bind('change', checkTableDoublement);

    function checkTableDoublement()
    {
        //Informations requises
        var annee = $("#info-saisie-notes-double-left #annee-double").val();
        var cursus = $("#info-saisie-notes-double-left #cursus-double").val();
        var option = $("#info-saisie-notes-double-left #option-double").val();
        var specialite = $("#info-saisie-notes-double-left #specialite-double").val();
        var mode = $("#info-saisie-notes-double-right #mode-double").val();
        var type = $("#info-saisie-notes-double-right #type-double").val();
        var niveau = $("#hiddenNiveau").val();
        var redoublement = 1;
        var tableBac = $("#double #tab-saisie-notes-bac-double").val();

        //Teste si on est sur une page de notes
        if(niveau==null)
            return false;

        $('#tab-saisie-notes-double').html("");
        $('#tab-saisie-notes-double').hide();
        $('#tab-saisie-notes-bac-double').hide();

        //Test des checkbox de redoublement
        if ($('#double-oui').size()==1) $('#double').show('slow');
        /*
        if($("#info-saisie-notes-right #double-oui").attr('checked')) $('#double').show('slow');
        else $('#double').hide('fast');
        */

        //Si toutes les conditions sont remplies, on affiche le tableau
        if(cursus!='' && mode !='' && type !='' && annee!='' && option!='' && specialite!='')
        {            
            $("#notesLoader-double").html("Chargement du tableau des notes de redoublement en cours...<br /><img src=\"admin/images/ajax-loader2.gif\" alt=\"patientez\" />");
            $('#double input, #double select').attr('disabled','disabled');
            $("#notesLoader-double").show();            
            getAjaxNotes(niveau,cursus,mode,type,redoublement,option,specialite);

            //Si c'est une année à BAC
            if(tableBac != null)
            {
                $("#notesLoader-bac-double").html("Chargement du tableau des notes du bac de redoublement en cours...<br /><img src=\"admin/images/ajax-loader2.gif\" alt=\"patientez\" />");
                $("#notesLoader-bac-double").show();
                getAjaxNotes(niveau,cursus,mode,type,redoublement,option,specialite,true);
            }
        }        
    }
   

    // FONCTION DE RECUPERATION DES NOTES EN AJAX //
    function getAjaxNotes(_niveau,_cursus,_mode,_type,_redoublement,_option,_specialite,_bac){

        nbAjaxCall++;
        $.ajax({
            url: 'ajaxNotes.php5',
            type: "POST",
            data: ({
                action: "get_notes",
                niveau: _niveau,
                cursus: _cursus,
                redoublement: _redoublement,
                bac: _bac
            }),
            success: function(data) {
                nbAjaxCall--;
                var sBalise = "";
                var sDouble = "";
                var sBac = "";
                // affiche image de chargement
                if(_redoublement==1)
                {
                    sBalise = "#double";
                    sDouble = "-double";
                }
                else
                    sBalise = "#principale";

                if(_bac)
                    sBac = "-bac";

                $('#notesLoader'+sBac+sDouble).hide();

                // complete la liste des etablissements
                $('#tab-saisie-notes'+sBac+sDouble).html(data);

                //Teste les valeurs à afficher
                checkDataTable(_cursus,_mode,_type,_redoublement,_option,_specialite);

                //libelle option
                if ($('#tab-saisie-notes'+sBac+sDouble).find('tr.option').size()) {
                    if ($('#tab-saisie-notes'+sBac+sDouble).find('tr.option > td:first > strong').html()=='Option') {
                        $('#tab-saisie-notes'+sBac+sDouble).find('tr.option > td:first > strong').html($('strong.jquery_strong_option').html());
                    }
                }
                //libelle specialite
                if ($('#tab-saisie-notes'+sBac+sDouble).find('tr.specialite').size()) {
                    if ($('#tab-saisie-notes'+sBac+sDouble).find('tr.specialite > td:first > strong').html()=='Spécialité') {
                        $('#tab-saisie-notes'+sBac+sDouble).find('tr.specialite > td:first > strong').html($('strong.jquery_strong_specialite').html());
                    }
                }

                //Une fois tous les traitements terminés,
                //On affiche le tableau
                $('#tab-saisie-notes'+sBac+sDouble).show('slow');

                //ECOUTEUR SUR LE LIEN FILLLINE
                //Rempli les champs d'une matière à 99
                $("a.fillLine").bind('click',function(){
                    $('input',$(this).parents('tr:first')).val('99');
                        /*var i =14;
                        $("tr.matiere input").each(function(){
                            $(this).val(i);
                            i++;
                            if(i>20) i=11;
                        });*/
                    
                    return false;
                });

                $(sBalise+' input, '+sBalise+' select').removeAttr('disabled');

            }
        });
    }

    // TESTE LES DONNEES A AFFICHER ET A MASQUER //
    function checkDataTable(_cursus,_mode,_type,_redoublement,_option,_specialite){

        //if ((!_option) && (!_specialite) && (_cursus='none')) _cursus='s';

        var sBalise = "";
        var sDouble = "";
        // affiche image de chargement
        if(_redoublement==1)
        {
            sBalise = "#double";
            sDouble = "-double";
        }
        else
            sBalise = "#principale";
            
        //on masque les informations correspondant aux différents modes
        $(sBalise+' #tab-saisie-notes'+sDouble+' .trimestre').hide();
        $(sBalise+' #tab-saisie-notes'+sDouble+' .semestre').hide();
        //on masque les informations correspondant aux différents types de classement
        $(sBalise+' #tab-saisie-notes'+sDouble+' .type-rang').hide();
        $(sBalise+' #tab-saisie-notes'+sDouble+' .type-moyenne').hide();
        //options specialites
        $(sBalise+" .option").hide();
        $(sBalise+" .specialite").hide();

        //Option //TODO
        if(_option!='' && _option != 'none')
        {
            $(sBalise+' .'+_cursus+".option").show();
        }
        //Specialité //TODO
        if(_specialite!='' && _specialite != 'none')
        {
            $(sBalise+' .'+_cursus+".specialite").show();
        }

        //Si le mode change
        if(_mode!='')
        {
            if(_mode==1) _mode= 'trimestre';
            else _mode='semestre';
            //on affiche les informations correspondant au mode
            $(sBalise+' .'+_mode).show();
        }
        //Si le type de classement change
        if(_type!='')
        {
            if(_type==1) _type= 'type-rang';
            else _type='type-moyenne';
            //on affiche les informations correspondant au mode
            $(sBalise+' .'+_type).show();
        }

    }
    
    $("input.moyenneValue").live('click',function(){
        $(this).css({
            'background-color' : 'white',
            'color' : 'black'
        });
    });
    $("input.type-rang").live('click',function(){
        $(this).css({
            'background-color' : 'white',
            'color' : 'black'
        });
    });

    //Teste si des notes incorrectes ont été saisies
    function checkNotesValues()
    {
        var bSuccess = true;
        var bAlert = true;

        //Teste les valeurs des notes
        $("input.moyenneValue").each(function(){
            if ($(this).val()!='') {
                if (($(this).regex(/^[0-9]{1,2}.[0-9]{1,2}$/)==false) && ($(this).regex(/^[0-9]*$/)==false)) {
                    $(this).css({'background-color':'red','color':'white'});
                    bSuccess=false;
                }
                else if (($(this).val()>20 || $(this).val()<0)  && $(this).val()!=99) {
                    $(this).css({'background-color':'red','color':'white'});
                    bSuccess=false;
                }
            }
        });

        //Teste les valeurs des rangs
        $("input.type-rang").each(function(){
            if ($(this).val()!='') {
                if (($(this).regex(/^[0-9]{1,2}.[0-9]{1,2}$/)==false) && ($(this).regex(/^[0-9]*$/)==false)) {
                    $(this).css({'background-color':'red','color':'white'});
                    bSuccess=false;
                }
                else if ($(this).val()<0) {
                    $(this).css({'background-color':'red','color':'white'});
                    bSuccess=false;
                }
                else {
                    if ($(this).parent().next('td').find('input.type-rang').size()==1) {
                       var iNbEleve=$(this).parent().next('td').find('input.type-rang').val();
                       iNbEleve=parseInt(iNbEleve);
                       if ((iNbEleve!='') && (iNbEleve!=0) && (iNbEleve<$(this).val())) {
                            $(this).css({'background-color':'red','color':'white'});
                            bSuccess=false;
                            if (bAlert==true) {
                                bAlert=false;
                                alert ('Vous ne pouvez possédez un rang supérieur au nombre d\'élèves de la classe.');
                            }
                       }
                    }
                }
            }
        });

        if(!bSuccess)
            alert('Il y a des valeurs saisies incorrectes. Veuillez corriger les cases rouges.');
        return bSuccess;
    }
    
   
});



	

    
