var aCharger = 
    Array(
        'images/loupe.png',
        'images/bg_enquete_agrandi.jpg',
        'images/onglets.png',
        'images/resultatsArrierePlan.png',
        'images/logo.png',
        "images/spinner.gif",
        "images/bgchamp.png",
        "images/fleche_avant.png",
        "images/fleche_apres.png"
    );
    
var aChargerChargees = 0;


function pageDeRecherche(cible){
    this.cible = cible

    this.initialiser()
}

pageDeRecherche.prototype = {
    logo : null,
    moteur : null,
    champ : null,
    submits : null,
    formulaire : null,
    preferences : null,
    recherches : null,

    idRechercheEncours : null,
    idPageEncours : 1,
    nbRecherches : 0,
    etatRecherches : 0, // 0: invisible, 1: Onglets seulement, 2: ouvert

    initialiser : function(){
        var pageRecherche = this;

        // associer les elements
        this.logo = this.cible.find("#logo")
        this.moteur = this.cible.find(".champRecherche")
        this.champ = this.cible.find("#mots-clefs")
        this.submits = this.cible.find(".boutons")
        this.formulaire = this.cible.find(".formulaire")
        this.preferences = this.cible.find(".preferences")
        this.recherches = this.cible.find("#content")

        // Cacher ce qui doit être invisible
        this.preferences.hide();
        this.recherches.css({height: 0});
        this.logo.css({marginTop: 300})

        // associer des evenements aux elements
            // on associe le bouton préférences au menu
            this.cible.find(".boutonPreferences").click(function(){
                pageRecherche.afficherPreferences();
            })

            this.cible.find(".boutonChercher").click(function(){
                pageRecherche.chercher();
            })

            this.cible.find(".onglet .mots_clefs a").click(function(event){
                event.preventDefault()
                pageRecherche.basculerRecherche();
            })

            this.cible.find("#mots-clefs").focus(function(){
                if(pageRecherche.etatRecherches>1){
                    pageRecherche.changerEtatRecherche(1)
                }
            })

            this.cible.find("#mots-clefs").keypress(function(){
                if(pageRecherche.etatRecherches>1){
                    pageRecherche.changerEtatRecherche(1)
                }
            })

            this.cible.find("#mots-clefs").click(function(){
                if(pageRecherche.etatRecherches>0){
                    pageRecherche.changerEtatRecherche(1)
                }
            })

            this.cible.find("#onglets-navigation a.avant").click(function(event){
                event.preventDefault()
                pageRecherche.ongletGoNiveau(pageRecherche.cible.find("#onglets").data("niveau") - 1)
            })

            this.cible.find("#onglets-navigation a.apres").click(function(event){
                event.preventDefault()
                pageRecherche.ongletGoNiveau(pageRecherche.cible.find("#onglets").data("niveau") + 1)
            })
    },

    // API
    chercher : function(){
        // cet methode créé un nouvel onglet si les mots clefs n'ont pas été lancés ou propose de relancer une recherche
        if(this.champ.val() == "" || this.champ.val() == this.champ.data("valeurDepart")){
            return
        }

        var pageRecherche = this
        var requete = this.champ.val()

        // afficher un spinner à l'intérieur du champ de recherche sur le bord gauche
        this.cible.find(".champRecherche").addClass("loading")

        // envois de la requette
        $.ajax({
            type: "POST",
            url: "resultats.html",
            data: this.cible.find("form#search").serialize(), 
            success: function(xml){
                setTimeout(function(){
                    pageRecherche.changerEtatRecherche(2)
                    pageRecherche.cible.find(".champRecherche").removeClass("loading")

                    // décomposition du résultat
                    var idRec = ++pageRecherche.nbRecherches;
                    var resultat = $(xml)
                    var onglet = $(resultat.find("#onglets").html())
                    onglet.find(".mots_clefs a").text(requete)
                    onglet.attr("id", "onglet_"+(idRec))
                    onglet.hide();
                    pageRecherche.cible.find("#onglets").prepend(onglet)
                    onglet.show("slow")

                    var result = $(resultat.find("#recherches").html())
                    result.attr("id", "resultats_"+(idRec))
                    result.find(".recherche").hide();
                    result.data("pageEnCours", 1)

                    pageRecherche.cible.find("#recherches").append(result)

                    pageRecherche.basculerRecherche(idRec)
                    pageRecherche.changerPage(1, pageRecherche.cible.find("#pagination a:eq(0)"))

                    pageRecherche.actualiserOnglets();
                    pageRecherche.ongletGoNiveau(0);

                    // basculer vers le résultat
                    onglet.find(".mots_clefs a").click(function(event){
                        event.preventDefault()
                        var id = parseInt($(this).parents(".onglet").attr("id").substring(7))
                        pageRecherche.basculerRecherche(id);
                    })

                    // Attribuer l'evenement au bouton de fermeture
                    onglet.find(".fermer a").click(function(event){
                        event.preventDefault()
                        var id = parseInt($(this).parents(".onglet").attr("id").substring(7))
                        pageRecherche.fermerRecherche(id);
                    })

                }, 1000)
            },
            error: function(){
                // erreur
                pageRecherche.cible.find(".champRecherche").removeClass("loading")
                alert("Assurez vous que vous êtes connectés à internet, puis réessayez")
            }
        })
    },

    countRecherches: function(){
        return this.cible.find(".onglet").length
    },

    actualiserOnglets : function(){
        var lnOnglets = this.countRecherches();
        var max = Math.ceil(lnOnglets / 5)-1

        this.cible.find("#onglets").data("max", max)

        if(lnOnglets>5){
            this.cible.find("#onglets-navigation").show();

            if(this.cible.find("#onglets").data("niveau") > max){
                this.ongletGoNiveau(max)
            }
        }
        else{
            this.cible.find("#onglets-navigation").hide();
            this.ongletGoNiveau(0)
        }
    },

    ongletGoNiveau: function(niveau){
        if(niveau != this.cible.find("#onglets").data("niveau") && niveau >= 0 && niveau<=this.cible.find("#onglets").data("max")){
            this.cible.find("#onglets").data("niveau", niveau)
            this.cible.find("#onglets").animate({scrollTop: niveau * 37})
        }
    },

    basculerRecherche : function(idRecherche){
        // methode qui va d'une recherche à l'autre
        if(idRecherche == this.idRechercheEncours){
            return;
        }

        this.changerEtatRecherche(2)

        this.cible.find("#pagination").empty();

        this.idRechercheEncours = idRecherche

        this.cible.find(".onglet").removeClass("onglet_selected")
        this.cible.find(".recherche").hide()
        this.cible.find("#onglet_"+idRecherche).addClass("onglet_selected")

        this.cible.find("#resultats_"+idRecherche).slideDown("slow");

        pageRecherche = this
        this.idPageEncours = this.cible.find("#resultats_"+idRecherche).data("pageEnCours");


        // s'occuper de la pagination
        this.preparerPagination();
    },

    preparerPagination: function(){
        pageRecherche = this

        this.cible.find("#resultats_"+this.idRechercheEncours+" .page").each(function(i){
            pageRecherche.cible.find("#pagination").append('<a href="#"'+(i==(pageRecherche.idPageEncours-1)?' class="selected"':"")+'>'+(i+1)+'</a>')
        })

        // associer l'evenement à chaque lien
        this.cible.find("#pagination a").click(function(event){
            event.preventDefault()
            pageRecherche.changerPage(parseInt($(this).text()), $(this))
        })
    },

    changerPage : function(idPage, theLien){
        // maintenant on chercher l'offset du truc et on y défile l'objet

        // vérification que la page existe
        if(this.cible.find("#resultats_"+this.idRechercheEncours+" .page").length+1 >= idPage && this.idPageEncours != idPage){
            var pageCible = this.cible.find("#resultats_"+this.idRechercheEncours+" .page:eq("+(idPage - 1)+")");
            this.cible.find("#resultats_"+this.idRechercheEncours).animate({scrollTop : pageCible.offset().top}, 1000, "easeOutBounce")

            // on retire les selected
            this.cible.find("#pagination a").removeClass("selected")

            // enregistrement du numéro de page:
            this.cible.find("#resultats_"+this.idRechercheEncours).data("pageEnCours", idPage);

            // son ajout au menu au lien en cours
            theLien.addClass("selected")

            this.idPageEncours = idPage
        }
        else{
            return;
        }
    },

    fermerRecherche : function(idRecherche){
        pageRecherche = this;
        
        this.cible.find("#resultats_"+idRecherche).fadeOut(500)
        this.cible.find("#onglet_"+idRecherche).fadeOut(500, function(){
            pageRecherche.cible.find("#resultats_"+idRecherche).remove();
            pageRecherche.cible.find("#onglet_"+idRecherche).remove();

            // on bascule vers le dernier onglet affiché
            if(pageRecherche.idRechercheEncours == idRecherche){
                if(pageRecherche.cible.find(".onglet").length > 0){
                    var id = parseInt(pageRecherche.cible.find(".onglet:first").attr("id").substring(7))
                    pageRecherche.basculerRecherche(id)
                }
                else{
                    pageRecherche.changerEtatRecherche(0)
                }
            }

            pageRecherche.actualiserOnglets()
        })
    },

    rechargerRecherche : function(idRecherche){

    },

    changerEtatRecherche : function(idEtatRecherche){
        this.etatRecherches = idEtatRecherche;

        switch(idEtatRecherche){
            case 0:
                this.recherches.animate({height: 0})
                this.recherches.hide();
                this.logo.animate({marginTop: 300});
                this.cible.find(".boutons").fadeIn();
                this.cible.find("#mots-clefs").animate({color: "#787c3f"})
            break;

            case 1:
                this.recherches.animate({height: 50})
                this.logo.animate({marginTop: 260});
                this.cible.find(".boutons").fadeIn();

                this.cible.find("#mots-clefs").animate({color: "#787c3f"})
            break;

            case 2:
                this.recherches.css({top: 0})
                this.recherches.animate({height: 365})
                this.logo.animate({marginTop: 150});

                this.preferences.slideUp();
                this.cible.find(".boutons").fadeOut();

                this.champ.val(this.champ.data("valeurDepart"))
                this.champ.val("")
                this.cible.find("#mots-clefs").animate({color: "#454b1b"})
            break;
        }
    },

    afficherPreferences : function(){
        if(this.preferences.css("display") == "none"){
            if(this.etatRecherches > 1){
                this.changerEtatRecherche(1)
            }
        }
        this.preferences.slideToggle();
    }
}


function animationChargement(cible){
   // constructeur
   this.cible = cible
}

animationChargement.prototype = {
    animationEnCours : false,
    status: 0, // 0: rien, 1: pageOuverte: 2: page fermée (chargement de page)
    wLoupe : 200,

    creerTableau: function(){
        // là on insère le tableau et on le relit à la cible
        this.cible.prepend('<div id="chargement"><img src="images/loupe.png" class="laloupe" /><div class="top">&nbsp;</div><div class="action"><div class="gauche">&nbsp;</div><div class="milieu loupe">&nbsp;</div><div class="droite">&nbsp;</div></div><div class="bottom">&nbsp;</div></div>')
    },

    animationDepart: function(){
        this.dimensionsDepart();
        
        anim = this
        $("#chargement .droite").animate({width: this.wGauche}, 2000);
        $("#chargement .gauche").animate({width: this.wDroite}, 2000, function(){
            $("#chargement .top").animate({height: 0}, 1000);
            $("#chargement .droite").animate({width: anim.wMoyenne}, 1000);
            $("#chargement .gauche").animate({width: anim.wMoyenne}, 1000);
            
            $("#chargement .bottom").animate({height: anim.hBottom + anim.hTop}, 1000, function(){
                
                $("#chargement .loupe").addClass("agrandi");
                $("#chargement .laloupe").show();
                $("#chargement .agrandi").removeClass("loupe");
                $("#chargement .laloupe").css({left: anim.wMoyenne});

                $("#chargement .laloupe").animate({width: anim.wTotal, height: anim.hTotal, top: 1, left: 1}, 500);
                $("#chargement .droite, #chargement .gauche").animate({width: 1, height: anim.hTotal}, 500);
                $("#chargement .action, #chargement .agrandi").animate({width: anim.wTotal, height: anim.hTotal}, 500);
                $("#chargement .top, #chargement .bottom").animate({height: 1}, 1000, function(){
                    $("#chargement").fadeTo(200, 0, function(){
                        $("#chargement").hide();
                    });
                });
            });
            
        });
    },

    animationFermeture: function(){
        this.dimensionsFinAnimation();
        anim = this
        
        $("#chargement .bottom").animate({height: anim.hTotal - anim.wLoupe}, 500);
        $("#chargement .action").animate({width: anim.wTotal, height: anim.wLoupe}, 500);
        $("#chargement .agrandi").animate({width: anim.wLoupe, height: anim.wLoupe}, 500);
        $("#chargement .droite, #chargement .gauche").animate({width: anim.wMoyenne, height: anim.wLoupe}, 500);

        $("#chargement .laloupe").animate({width: anim.wLoupe, height: anim.wLoupe, top: 1, left: anim.wMoyenne}, 500, function(){
            anim.animationOuverture();
        });
    },

    animationOuverture: function(){
        anim = this
        $("#chargement .laloupe").animate({width: anim.wTotal, height: anim.hTotal, top: 1, left: 1}, 500);
        $("#chargement .droite, #chargement .gauche").animate({width: 1, height: anim.hTotal}, 500);
        $("#chargement .action, #chargement .agrandi").animate({width: anim.wTotal, height: anim.hTotal}, 500);
        $("#chargement .top, #chargement .bottom").animate({height: 1}, 1000, function(){
            $("#chargement").fadeTo(200, 0, function(){
                $("#chargement").hide();
            });
        });
    },

    dimensionsDepart: function(){
       // dimensions du truc au repos !!
       this.wTotal = this.cible.width()
       this.hTotal = this.cible.height()

       // dimensions des constituants
       this.hTop = (this.hTotal - this.wLoupe) / 5 // ligne supérieure
       this.hBottom = this.hTop * 4 // ligne inférieure

       // milieu
       this.wGauche = 100;
       this.wDroite = this.wTotal - (this.wLoupe + this.wGauche) - 2;
       this.wMoyenne = ((this.wTotal - this.wLoupe) / 2) - 1;


       // affectation au fontome lol

       this.cible.find("#chargement .laloupe").hide(); // on cache la loupe en image qui sert à la deuxième étape

       this.cible.find("#chargement").css("width", this.wTotal)
       this.cible.find("#chargement").css("height", this.hTotal)
       this.cible.find("#chargement .top").css("height", this.hTop)
       this.cible.find("#chargement .bottom").css("height", this.hBottom)
       this.cible.find("#chargement .droite").css("width", this.wDroite)
    },

    dimensionsFinAnimation: function(){
        this.cible.find(".laloupe").css({width: this.wTotal, height: this.hTotal, top: 0, left: 0});
        $("#chargement .action, #chargement .agrandi").css({width: this.wTotal, height: this.hTotal});
        $("#chargement .droite, #chargement .gauche").css({width: 1, height: this.hTotal});

        $("#chargement .laloupe").show();
        $("#chargement").css({opacity: 1});
        $("#chargement").show();
    }
}

$(document).ready(function(){
    animation = new animationChargement($("#page"))
    // page = new pageDeRecherche($("#page"))
    
    prechargement()

    $("form#search input").click(function(event){
        event.preventDefault()
        // animation.animationFermeture();
    })
    
    $(".autoSaveErase").each(function(){
        $(this).data("valeurDepart", $(this).attr("value"))
    })

    $(".autoSaveErase").focus(function(){
        if($(this).val() == $(this).data("valeurDepart")){
            $(this).val("")
        }
    })

    /*$(".autoSaveErase").blur(function(){
        if($(this).val() == ""){
            $(this).data("valeurDepart")
        }
    })*/

    $("form#search .augmenterTaille").each(function(){
        $(this).data("taille", $(this).css("fontSize"))
        $(this).data("tailleGrande", parseInt($(this).css("fontSize"))* 1.3)
    })

    $("form#search .augmenterTaille").hover(
        function(){
            $(this).animate({color: "#c4cd33", fontSize: $(this).data("tailleGrande")}, "fast")
        },
        function(){
            $(this).animate({color: "#717a2e", fontSize: $(this).data("taille")}, "fast")
        }
    )
})

function prechargement(){
    for(i = 0; i < aCharger.length; i++){
        $('<img src="'+aCharger[i]+'" />').load(function(){
            aChargerChargees++;
            
            if(aChargerChargees == aCharger.length){
                $("#page").show();
                
                if($.browser.msie && $.browser.version < 8){
                    //
                }
                else{
                    animation.creerTableau();
                    animation.animationDepart();
                }
                
            }
        })
    }
}