/**
 * Classe ddbois, gestion des scripts du site
 *
 * Alexandre STEIGMEIER
 */

ddbois = {
    
    annee: 2012,

    /**
     * fonction run, lance les actions communes à chaque page
     * (rollover du menu, etc)
     */
    run: function () {
        // Rollover du menu
        $('#menu li').each(function(i,e){
            $(e).hover(
                function(){$(this).addClass('active');},
                function(){$(this).removeClass('active');}
            );
            $(e).click(
                function(){ window.location.href = $(this).children(':first').attr('href'); }
            );
        });
        $('table.rollover tr').each(function(i,e){
            if(i>0) {
                $(e).hover(
                    function(){$(this).addClass('hover');},
                    function(){$(this).removeClass('hover');}
                );
            }
        });
        $(".tablesorter").tablesorter();
        $(".tablesorter").bind("sortEnd",function() {
            $('tbody tr').removeClass('alterne');
            $('tbody tr:odd').addClass('alterne');
            //$(this).children($('tr')).removeClass('alterne');
            //$(this).children($('tr')).filter(':even').addClass('alterne');
        });
        ddbois.autorunner();
    },
    
    /**
     * autorunner, lance automatiquement les scripts propres à chaque page
     */
    autorunner: function() {
        page = document.location.href.replace(/^http:\/\/www\.derbydesbois\.ch\/([\w]+)\/.*$/, "$1");
        if(ddbois[page] != undefined && ddbois[page].autorun() != undefined) {
            ddbois[page].autorun();
        }
    },
    
    /**
     * Objets horaires
     */
    horaires: {
        autorun: function() {
            ddbois.horaires.watchForChange();
        },
        watchForChange: function() {
            $('#n, #g_h, #g_f').change(function() {ddbois.horaires.updateMessage();});
        },
        updateMessage: function() {
            year   = $('#n').val();
            man    = $('#g_h').attr('checked');
            woman  = $('#g_f').attr('checked');
            error  = ddbois.horaires.checkValues(year, man, woman);
            switch (error) {
                case 0 : // Pas d'erreur
                    message = ddbois.horaires.getCategorie(year, man);
                    break;
                case 1 : // Mauvaise année de naissance
                    message = "Veuillez spécifier votre année de naissance.";
                    break;
                case 2 : // Genre non sélectionné
                    message = "Veuillez spécifier votre genre.";
                    break;
                case 3 : // Mauvaise année et genre non sélectionné
                    message = "Veuillez spécifier votre année de naissance et votre genre.";
                    break;
            }
            $('#trick_cat').html(message);
            if(!error) {
                ddbois.horaires.highlight();
            }
        },
        checkValues: function(year, man, woman) {
            error  = 0;
            if ((year.length != 4) || (isNaN(year)) || (year < 1920) || (year > ddbois.annee-8)) {
                error += 1;
            }
            if ((!man) && (!woman)) {
                error += 2;
            }
            return error;
        },
        getCategorie: function(year, man) {
            age        = ddbois.annee - year;
            categories = "Walking";
            femmes     = [', Ecolières C',', Ecolières B',', Ecolières A',', Cadettes B',', Cadettes A',', Juniores',', Femmes "court"',', Femmes',', Vétérans femmes',', Vétérans femmes'];
            hommes     = [', Ecoliers C',', Ecoliers B',', Ecoliers A',', Cadets B',', Cadets A',', Juniors',', Hommes "court"',', Hommes',', Vétérans hommes 1',', Vétérans hommes 2'];
            if (age ==  8 || age ==  9) categories += (man)?hommes[0]:femmes[0];
            if (age == 10 || age == 11) categories += (man)?hommes[1]:femmes[1];
            if (age == 12 || age == 13) categories += (man)?hommes[2]:femmes[2];
            if (age == 14 || age == 15) categories += (man)?hommes[3]:femmes[3];
            if (age == 16 || age == 17) categories += (man)?hommes[4]:femmes[4];
            if (age == 18 || age == 19) categories += (man)?hommes[5]:femmes[5];
            if (age >= 20 && age <= 99) categories += (man)?hommes[6]:femmes[6];
            if (age >= 20 && age <= 39) categories += (man)?hommes[7]:femmes[7];
            if (age >= 40 && age <= 49) categories += (man)?hommes[8]:femmes[8];
            if (age >= 50 && age <= 99) categories += (man)?hommes[9]:femmes[9];
            
            return categories;
        },
        highlight: function() {
            $('table:first tr').removeClass('select');
            categories = $('#trick_cat').html();
            categories = categories.split(', ');
            for(i=0; i<categories.length; i++) {
                $('table:first tr td:contains("'+categories[i]+'")').parent().addClass('select');
            }
        }
    },
    
    inscriptions: {
        autorun: function() {
            ddbois.inscriptions.watchout();
        },
        watchout: function() {
            $('#ddb_npa').blur(function(e){
                if($('#ddb_npa').val() != '' && $('#ddb_npa').val().length == 4) ddbois.inscriptions.getVilleByNPA();
            });
            $('#ddb_sexe').change(function(e) {
                ddbois.inscriptions.loadCourses();
            });
            $('#course').focus(function(e) {
                ddbois.inscriptions.loadCourses();
            });
            $('#ddb_naissance').change(function(e) {
                if($('#ddb_naissance').val() != '' || $('#ddb_naissance').val().length == 4) {
                    ddbois.inscriptions.loadCourses();
                }
            });
            $('#ddb_email').change(function(e) {
                if($(this).val() == '') {
                    $('#ddb_confirmation').attr('disabled', 'disabled').removeAttr('checked','checked');
                } else if(ddbois.inscriptions.checkField($(this), 'email')) {
                    $('#ddb_confirmation').removeAttr('disabled').attr('checked','checked');
                } else {
                    $('#ddb_confirmation').removeAttr('checked','checked');
                }
            });
            $('#form_inscription').submit(function(e) {
                return ddbois.inscriptions.checkFormulaire();
            });
        },
        getVilleByNPA: function() {
            $.ajax({
                url: '/inscriptions/ajax/npa/'+$('#ddb_npa').val(),
                dataType: 'json',
                success: function(data) {
                    if(data.length == 1) {
                        if($('#city_choice').length) $('#city_choice').hide();
                        $('#ddb_ville').val(data[0].npa_nom);
                    } else if(data.length > 1) {
                        if($('#city_choice').length) {
                            $('#city_choice').show();
                            $('#city_choice').html("");
                        } else {
                            p = $("#ddb_ville").position();
                            $(document.createElement('div')).attr({
                                style: 'position:absolute; left:'+(p.left+3)+'px; top:'+(p.top+19)+'px;',
                                id: 'city_choice'
                            }).addClass('ddown_ville').insertAfter($('#ddb_ville'));
                        }
                        $('#city_choice').append(document.createElement('ul'));
                        for(i=0;i<data.length;i++) $('#city_choice ul:first').append(
                            $(document.createElement('li')).html(data[i].npa_nom).click(function(){
                                $('#ddb_ville').val($(this).html());
                                $('#city_choice').hide('blind', 'fast');
                            })
                        );
                    }
                }
            });
        },
        loadCourses: function() {
            $.ajax({
                url: '/inscriptions/ajax/courses/'+$('#ddb_naissance').val()+'_'+$('#ddb_sexe').val(),
                dataType: 'json',
                success: function(data) {
                    $('#course').children().remove();
                    for(key in data) {
                        $('#course').append($(document.createElement('option')).attr('value',key).html(data[key]));
                    }
                }
            });
        },
        checkField: function(n, t) {
            switch(t) {
                default:
                case 'string':
                    if($(n).val().replace(/\s/gi, '') == '') {
                        $(n).addClass('red');
                        $(n).bind('blur change', function(){ddbois.inscriptions.checkField($(this), t);});
                        return false;
                    } else {
                        $(n).removeClass('red');
                    }
                    break;
                case 'year':
                    if(isNaN($(n).val()) || $(n).val().length != 4) {
                        $(n).addClass('red');
                        $(n).bind('blur change', function(){ddbois.inscriptions.checkField($(this), t);});
                        return false;
                    } else {
                        $(n).removeClass('red');
                    }
                    break;
                case 'integer':
                    if($(n).val() == '' || isNaN($(n).val())) {
                        $(n).addClass('red');
                        $(n).bind('blur change', function(){ddbois.inscriptions.checkField($(this), t);});
                        return false;
                    } else {
                        $(n).removeClass('red');
                    }
                    break;
                case 'email':
                    if($(n).val() != '') {
                        if(!/^[a-z0-9._-]+@[a-z0-9._-]{2,}\.[a-z]{2,4}$/.test($(n).val())) {
                            $(n).addClass('red');
                            $(n).bind('blur change', function(){ddbois.inscriptions.checkField($(this), t);});
                            return false;
                        } else {
                            $(n).removeClass('red');
                        }
                    } else {
                        $(n).removeClass('red');
                    }
                    break;
            }
            return true;                
            //.blur(function(){if($(n).val().replace(/\s/gi, '')!='')$(n).removeClass('error')})
            //.keydown(function(){if($(n).val().replace(/\s/gi, '')!='')$(n).removeClass('error')});
        },
        checkFormulaire: function() {
            sansErreur  = true;
            champs      = new Array('ddb_nom','ddb_prenom','ddb_naissance','ddb_adresse','ddb_npa','ddb_ville','ddb_email','course');
            champsType  = new Array('string','string','year','string','integer','string','email','integer');
            champsNoms  = new Array('Nom','Prénom','Année de naissance','Adresse','NPA','Ville','Catégorie');
            
            for(i=0; i<champs.length; i++) {
                if(!ddbois.inscriptions.checkField($('#'+champs[i]), champsType[i])) {
                    sansErreur = false;
                }
            };
            return sansErreur;
        },
        checkCode: function() {
            $.ajax({
                url: '/inscriptions/ajax/code/'+$('#txtCode').val(),
                success: function(retour) {
                    if(retour == 'true') $('#testCode').html("Code correct.").attr('style', 'color: green;');
                    else $('#testCode').html("Code incorrect.").attr('style', 'color: red;');
                }
            });
        }
        
    }

};
$(document).ready(function() {
    ddbois.run();
});
