// JavaScript Document
var url           = '';
var gb_url        = '';
var gc_url        = '';
var img_url       = '';
var lang          = '';
var cookie_domain = '';
var translate     = new Object();
var constant      = new Object();
var map           = '';
var geocoder      = '';
var lat           = '';
var lng           = '';
var centerLat     = '';
var centerLng     = '';
var zipcode       = '';
var city          = '';
var department    = '';
var district      = '';
var country       = '';
var countrycode   = '';
var extendPercent = 0.2;   // zone invisible autour de la carte
var zoom          = 12;
var zoomMax       = 17;    // zoom max à partir duquel on ne zoom plus
var zoomPage      = 11;    // zoom à partir duquel on affiche les pages
var xml;                   // les infos de retour
var circle;                // un cercle
var page          = '';    // sur quelle page est la carte
var data          = '';    // quel type de data on veut (user ou zone)
var platformGame  = '';    // la platform
var game          = 0;     // le jeu
var mod           = 0;     // le mode
var nbmod         = 1;     // le nombre de mods du jeu (utile pour savoir si possibilité de challenge ou pas)
var zone          = 0;     // la zone
var team          = 0;     // la team
var pagepro       = 0;     // la page pro
var award         = 0;     // l'award
var friend        = 0;     // récupère l'id du mec quand il veut afficher ses amis sur la map
var pagination    = 0;     // la pagination
var find          = 0;     // la recherche
var timer	  = '';	   // timer
var original_title= '';	   // stocke le titre de la page


var app_mode      = '';
var test_mode;


/**********************************************/
/* Hello, mais tu viens faire quoi par ici ?? */
/* on vient récupérer du code ? */

$(document).ready(function(){

    var nbPlayers = 0;

    // home slider
    if($('#home_snap').is('div')) {
        $('#home_snap').crossSlide({
          sleep: 2,
          fade: 1
        }, [
          {src: img_url+'/home/mini-snap-map.jpg'},
          {src: img_url+'/home/mini-snap-profil.jpg'},
          {src: img_url+'/home/mini-snap-tournament.jpg'}
        ]);
    }
    if($('#home_game').is('div')) {


        $('#home_slider_content').jCarouselLite({
                                auto: 5000,
                                speed: 750,
                                visible: 1
                            });

        var t0=setTimeout("homeGameSlider('#home_game_slider_1')",0);

        var t1=setTimeout("homeGameSlider('#home_game_slider_2')",150);

        var t2=setTimeout("homeGameSlider('#home_game_slider_3')",300);

        var t3=setTimeout("homeGameSlider('#home_game_slider_4')",450);

        var t4=setTimeout("homeGameSlider('#home_game_slider_5')",600);

    }

    /* zone de recherche */
    $('#search').submit(function() {

        /* selon le type de recherche, utilisation de la carte ou non */
        var type = $('#search_hidden').val();
        type     = substr(type, 1);
        var adress;

        if(type == 'place' && $('.map').is("div") && (page != 'team' && page != 'one_zone' && page != 'page')) {

            /* on récupère la valeur du lieu dans le href */
            adress = $('#search_input').val();

            if(adress != "") {
                /* on envoie l'adresse */
                postAddress(adress);
            }

            return false;


        } else if(type == 'place') {

            /* on récupère la valeur du lieu dans le href */
            adress = $('#search_input').val();

            if(adress != "") {

                /* on envoie l'adresse */
                postAddress(adress, function(){

                    /* redirection */
                    document.location.href = url+'/map';
                });

                /* redirection : problème avec la redirection au dessus ?! */
                document.location.href = url+'/map';

            }else {
                /* redirection */
                document.location.href = url+'/map';
            }

            return false;

        } else if(type == 'game') {

            return false;
        }
    });


    /* zone de recherche : utile pour recherche de jeu */
    $('#search_input').keyup(function() {

        /* selon le type de recherche, utilisation de la carte ou non */
        var type = $('#search_hidden').val();
        type     = substr(type, 1);

         if(type == 'game') {

            var stringGame = $(this).val();

            if(stringGame != '' && stringGame.length > 2) {

                /* Requête AJAX */
                $.ajax({
                    type: 'GET',
                    processData: true,
                    url: url+'/ajaxgame/autocompletename/format/html',
                    dataType: 'html',
                    data: 'name='+stringGame+'&type=findsite',
                    success: function(html){

                        $('#find_zone_autocomplete').html(html).show();
                    }
                });

            } else {
                $('#find_zone_autocomplete').hide();
            }
        }

        return false;
    });


    /* type de recherche */
    $('#search ul a').click(function() {

        $(this).parent().parent().find('a').removeClass('white');
        $(this).addClass('white');

        // on change le type
        var type = $(this).attr('href');
        $('#search_hidden').val(type);
        
        type     = substr(type, 1);

        // on change l'url de destination
        if(type == 'place') {
            $('#search').attr('action', url+'/map');
            
        } else {
            $('#search').attr('action', url+'/find/'+type);
        }

        // on reset le champ de recherche
        $('#search_input').val('');

        return false;
    });

    /* switch map */
//    $('.map_switch').hover(function() {
//
//        $(this).find('div').stop(true, true).show();
//
//    },function() {
//        $(this).find('div').stop(true, true).hide();
//    });
//
//    $("#map_switch_user").click(function() {
//
//        if(data != 'user') {
//            /* rafraichissement de la carte */
//            friend = 0;
//            data   = 'user';
//            refreshMap(lat, lng);
//
//            /* gestion menu activé */
//            $('#map_switch_zone').removeClass('backcolo_blue').removeClass('shadow_blue').addClass('backcolo_grey2').addClass('shadow_grey2');
//            $('#map_switch_tournament').removeClass('backcolo_blue').removeClass('shadow_blue').addClass('backcolo_grey2').addClass('shadow_grey2');
//            $(this).removeClass('backcolo_grey2').removeClass('shadow_grey2').addClass('backcolo_blue').addClass('shadow_blue');
//
//            $('#click_element').fadeOut().remove();
//            $('#click_element_close').remove();
//        }
//    });
//
//    $("#map_switch_zone").click(function() {
//
//        if(data != 'zone') {
//            /* rafraichissement de la carte */
//            friend = 0;
//            data   = 'zone';
//            refreshMap(lat, lng);
//
//            /* gestion menu activé */
//            $('#map_switch_user').removeClass('backcolo_blue').removeClass('shadow_blue').addClass('backcolo_grey2').addClass('shadow_grey2');
//            $('#map_switch_tournament').removeClass('backcolo_blue').removeClass('shadow_blue').addClass('backcolo_grey2').addClass('shadow_grey2');
//            $(this).removeClass('backcolo_grey2').removeClass('shadow_grey3').addClass('backcolo_blue').addClass('shadow_blue');
//
//            $('#click_element').fadeOut().remove();
//            $('#click_element_close').remove();
//        }
//    });
//
//    $("#map_switch_tournament").click(function() {
//
//        if(data != 'tournament') {
//            /* rafraichissement de la carte */
//            friend = 0;
//            data   = 'tournament';
//            refreshMap(lat, lng);
//
//            /* gestion menu activé */
//            $('#map_switch_user').removeClass('backcolo_blue').removeClass('shadow_blue').addClass('backcolo_grey2').addClass('shadow_grey2');
//            $('#map_switch_zone').removeClass('backcolo_blue').removeClass('shadow_blue').addClass('backcolo_grey2').addClass('shadow_grey2');
//            $(this).removeClass('backcolo_grey2').removeClass('shadow_grey2').addClass('backcolo_blue').addClass('shadow_blue');
//
//            $('#click_element').fadeOut().remove();
//            $('#click_element_close').remove();
//        }
//    });


    /* affichage popup login */
    $("#login, #login2, .login_link").click(function() {

        var text = $('#login_zone').html();
	
        $.prompt(text, {
            buttons: {}
        });
        setTimeout(function(){
            $('#jqi input').get(0).focus();
        }, 1000);
        return false;
    });


    /* lien login twitter */
    $("#login_twitter").live('click', function() {

        /* Requête AJAX pour générer le lien twitter */
        $.ajax({
            type: 'GET',
            processData: true,
            url: url+'/twitter/url/format/html',
            dataType: 'html',
            success: function(html){
                /* on suit le lien */
                document.location.href = html;
            }
        });

    });


    /* affichage menu membre connecté */
    $("#header_nav li").hover(function() {
        $(this).find('ul').stop(true, true).slideDown();

    },function() {
        $(this).find('ul').stop(true, true).hide();
    });


    /* type de recherche */
    $("#search").hover(function() {

        $(this).addClass('backcolo_greydark');
        $(this).find('ul').stop(true, true).show();

    },function() {
        $(this).removeClass('backcolo_greydark');
        $(this).find('ul').stop(true, true).hide();
    });


    /* recherche des jeux via leur nom */
    $('#add_game').keyup(function() {

        var platforms = '';
        var type      = '';

        /* selon la page où on fait la recherche */
        if($('.signin_platform').is("input")) {

            /* on récupère les plateformes */
            var inputplatform = $(".signin_platform:checked");

            jQuery.each(inputplatform, function(key, value) {

                platforms += $(value).val()+',';
            });
            platforms = substr(platforms, 0, -1);
            type      = 'signin';

        } else {
            type      = 'member';
        }

        /* on récupère la valeur du champ */
        var game     = $(this).val();

        if(game != "") {

            /* Requête AJAX */
            $.ajax({
                type: 'GET',
                processData: true,
                url: url+'/ajaxgame/autocompletename/format/html',
                dataType: 'html',
                data: 'name='+game+'&type='+type+'&platform='+platforms,
                success: function(html){

                    $('#zone_autocomplete').html(html).show();
                }
            });

        } else {
            $('#zone_autocomplete').slideUp();
        }

        return false;
    });

    /**
     * ajout de jeux lors de la création d'un compte
     */
    $('#add_games_signin').keyup(function(){

        var game = $(this).val();

        if(window.gb_signingametimeout != undefined) {
            window.clearTimeout(window.gb_signingametimeout);
            delete window.gb_signingametimeout;
        }

        if(game.length > 2) {
            window.gb_signingametimeout = setTimeout(searchSigninUserGame, 250);
        }
        else if(game.length == 0) {
            $('#zone_autocomplete').slideUp();
        }
    });

    /**
     *
     */
    function searchSigninUserGame() {

        var search = $('#add_games_signin').val();

        if(search.length > 2) {
            $.ajax({
                type: 'GET',
                processData: true,
                url: url+'/ajaxgame/autocompletename/format/html',
                dataType: 'html',
                data: 'name='+search+'&type=signin',
                beforeSend: function() {
                    $('#add_games_signin').addClass('autocomplete_loading');
                },
                success: function(html){

                    if(html == '') {
                        $('#zone_autocomplete').slideUp();
                    }
                    else {
                        $('#zone_autocomplete').html(html).show();
                    }
                },
                complete: function() {
                    $('#add_games_signin').removeClass('autocomplete_loading');
                }
            });
        }
    }

    /* pop up workingprogress */
    $('.todo_challenge, .todo_discuss, .todo_tournament').live('click', function() {

        var type = $(this).attr('class');
        var text = $('#modale_workingprogress');

        if(type == 'todo_challenge') {
            text.find('.modale_wip_infos').html(translate['workinprogress_challenge']);
        }

        text = text.html();

        $.prompt(text, {
            buttons: {}
        });

        return false;
    });


    /* lien discuter */
    $(".discuss_user").live('click', function() {

	var data    = $(this).attr('href').split('_');
	var userid  = data[2];

	//si le destinataire est actuellement connecté, on ouvre sa fenêtre de chat, sinon, on ouvre un popup d'envoi de message classique
	if (!_chatManager.handleContactLinkByChat(userid)) {

            /* Requête AJAX */
            $.ajax({
                type: 'GET',
                processData: true,
                url: url+'/member/ajax/popupmessage/format/html',
                dataType: 'html',
                data: 'userid=' + userid,
                success: function(html){

                    // modale de message
                    $.prompt(html, {
			buttons: {}
		    });
                }
            });
	}

        return false;
    });

    /**
     * discussion multiple avec des utilisateurs
     * les informations pour créer la popup sont dans le href du lien
     * le href doit commencer par # (protection si pas de Js) et séparer les infos par des underscores
     *
     * liste des infos :
     *
     * 0: l'entité associée
     * 1: l'id de l'entité
     * 2: la classe html des champs à récupérer en js
     *
     * exemple de href : #tournament_45_cbxCompetitors
     */
    $(".discuss_user_multiple").click(function() {

        var href     = $(this).attr('href').substr(1);
        var infos    = href.split('_');
        var inputs = $('.'+infos[2]+':checked');

        var usersIds = [];$(inputs).each(function(){usersIds[usersIds.length] = parseInt(this.value);});

        // si au moins un utilisateur sélectionné
        if(usersIds.length > 0) {

            // Requête AJAX
            $.ajax({
                type: 'GET',
                processData: true,
                url: url+'/member/ajax/popupmessagemultiple/format/html',
                dataType: 'html',
                data: 'entity=' + infos[0] + '&entityId=' + infos[1] + '&usersIds=' + usersIds.join(','),
                success: function(html){

                    // modale de message
                    $.prompt(html, {
                        buttons: {}
                    });
                }
            });

        }
        
        return false;
    });

    /* ajoute le jeu */
    $('#autocomplete a').live('click', function() {

        /* on ferme le volet */
        $('#zone_autocomplete').slideUp();
        $('#zone_autocomplete').hide(); // pour chrome

        var infos = $(this).parent().attr('id');

        infos = explode('_', infos);

        var height = '';
        if(infos[2] == 'psp') {
            height = 'height="135px"';
        }

        /* on regarde sur quelle page est l'autocomplete */
        var type = $('#autocomplete').attr('class');

        if(type == 'signin') {

            /* on ajoute le jeu */
            $('#signin_listgame').append('<li><input type="hidden" name="game[]" value="'+infos[1]+'" /><img class="cover" src="'+gc_url+'/'+infos[2]+'/96/'+infos[1]+'.jpg" alt="" '+height+'/><a href="#nogo"><img src="'+img_url+'/icone/close_16.png" alt="" /></a></li>');

        } else if(type == 'find') {

            document.location.href = url+'/game/'+infos[2]+'/'+infos[3]+'/'+infos[1]+'/home/all';
           
        } else {

            /* on ajoute le jeu à la liste*/
            $('.list_game').prepend('<li class="p_'+infos[2]+'">'
                +'<img src="'+gc_url+'/'+infos[2]+'/85/'+infos[1]+'.jpg" alt="" title="" />'
                +'</li>');

            /* et dans la base de données */
            if(infos[1] != "") {
                /* Requête AJAX */
                $.ajax({
                    type: 'GET',
                    processData: true,
                    url: url+'/member/ajax/addgame/format/html',
                    dataType: 'html',
                    data: 'idgame='+infos[1],
                    success: function(){

                    }
                });
            }
        }

        /* on reset le champ */
        $('#add_game').val('');
        $('#add_games_signin').val('');

        return false;
    });

    /* ajoute le jeu depuis la page d'un jeu */
    $('#game_default_add').live('click', function() {


        /* on récupère la valeur du champ */
        var message = $(this).attr('href');
        message     = substr(message, 1);

        infos = explode('_', message);

        /*dans la base de données */
        if(infos[1] != "") {
            /* Requête AJAX */
            $.ajax({
                type: 'GET',
                processData: true,
                url: url+'/member/ajax/addgame/format/html',
                dataType: 'html',
                data: 'idgame='+infos[1],
                success: function(html){

                    //indique que l'on se trouve sur la page des zones du jeu
                    if($('#game_default_add').attr('class') == 'zone_game_default_add'){

                        $('#game_default_add').hide().next().fadeIn();

                    }else {
                        /* selon on ajoute le jeu sur la page du jeu ou d'une zone */
                        var pageZone = parseInt($('#zone').html());

                        if(pageZone > 1) {
                            $('#game_default_add').hide().next().show();
                        }else {
                            $('#game_default_add').parent().fadeOut();
                        }
                    }
                }
            });
        }

         /* on modifie le champ */

        return false;
    });

    /* ajoute le jeu depuis une bubble */
    $('.bubble_add_game').live('click', function() {

        /* on récupère la valeur du champ */
        var link    = $(this);
        var message = link.attr('href');
        message     = substr(message, 1);

        infos = explode('_', message);

        /*dans la base de données */
        if(infos[1] != "") {
            /* Requête AJAX */
            $.ajax({
                type: 'GET',
                processData: true,
                url: url+'/member/ajax/addgame/format/html',
                dataType: 'html',
                data: 'idgame='+infos[1],
                success: function(html){

                    link.hide();
                    link.next().show();
                }
            });
        }
        return false;
    });


    /* ajoute les attributs de géoloc */
    $('.geo_url a, .geo_url_link, #site_breadcrumb .location, .list_game2 .geo_url').live('mousedown', function(event) {

        /* on récupère l'url */
        var url = $(this).attr('href');

        window.geolocOldUrl = url;

        url += '/'+lat+'/'+lng;

        /* on ajoute les paramètres de géoloc */
        if(zoom >= 5) {
            url += '/'+rawurlencode(no_accent(countrycode));
        }
        /* région */
        if(zoom >= 7) {
            url += '/'+rawurlencode(no_accent(district));
        }
        /* département */
        if(zoom >= 8) {
            url += '/'+rawurlencode(no_accent(department));
        }
        /* ville */
        if(zoom >= 12) {
            url += '/'+rawurlencode(no_accent(city))+'/'+zipcode;
        }

        $(this).attr('href', url);
    });
    $('.geo_url a, .geo_url_link, #site_breadcrumb .location, .list_game2 .geo_url').live('mouseup', function(event) {

         if(event.which == 3 || event.which == 2) {

                window.setTimeout(function(elem){
                    var url = window.geolocOldUrl;
                    delete window.geolocOldUrl;
                    $(elem).attr('href', url);
                }, 1000, this);
         }
    });

    /* modifie la durée d'une zone */
    $('.day_duration_change').click(function() {

        /* less or more */
        var action = $(this).attr('href');
        action     = substr(action, 1);

        /* la durée actuelle */
        var duration = $('#day_duration').html();
        var dayText  = '';

        /* la durée minimale (utile pour l'édition)*/
        var durationMini = parseInt($(this).attr('name'));


        /* boucle if else */
        if (action == 'more'){
            if (duration == '1') {
                duration = '3';
            } else if (duration == '3'){
                duration = '7';
            }else if (duration == '7'){
                duration = '15';
            }else if (duration == '15'){
                duration = '30';
            } else if (duration == '30'){
                duration = '45';
            }else if (duration == '45'){
                duration = '60';
            } else if (duration == '60'){
                duration = '90';
            }else if (duration == '90'){
                duration = '120';
            } else if (duration == '120'){
                duration = durationMini;
            }
        } else {
            if (duration == durationMini) {
                duration = '120';
            } else if (duration == '3' && duration >= durationMini){
                duration = '1';
            }else if (duration == '7' && duration >= durationMini){
                duration = '3';
            }else if (duration == '15' && duration >= durationMini){
                duration = '7';
            }else if (duration == '30' && duration >= durationMini){
                duration = '15';
            }else if (duration == '45' && duration >= durationMini){
                duration = '30';
            }else if (duration == '60' && duration >= durationMini){
                duration = '30';
            } else if (duration == '90' && duration >= durationMini){
                duration = '60';
            } else if (duration == '120' && durationMini != 120){
                duration = '90';
            }
        }

        if(duration == '1') {
            dayText  = translate["day"];
        }else {
            dayText  = translate["days"];
        }

        $('#list_datenext strong').hide();
        $('#day_duration').parent().html('<strong id="day_duration">'+duration+'</strong> '+dayText);

        /* on le met dans le input hidden */
        $('#duration').val(duration);

        $('#datenext_'+duration).show();

    });

    /* tooltip user */
    $(".bubble_user").simpletip({
        baseClass: 'simpletip',
        fixed: true,
        position: 'top',
        content: '<p class="center loading"><img src="'+img_url+'/icone/loading.gif" alt="" />',
        onBeforeShow: function() {

            var link = $(this.getParent());
            var firstTime = link.children('div').children('p').hasClass('loading');

            if(firstTime) {

                var datauser = this.getParent().attr('href'); 
                this.load(url+'/member/ajax/bubble/format/html', {data:datauser, nbmod:nbmod});
            }
        }
    });

    $(".bubble_user2").simpletip({
        baseClass: 'simpletip3',
        fixed: true,
        position: [-15,-77],
        content: '<p class="center loading"><img src="'+img_url+'/icone/loading.gif" alt="" />',
        onBeforeShow: function() {

            var link = $(this.getParent());
            var firstTime = link.children('div').children('p').hasClass('loading');

            if(firstTime) {

                var datauser = this.getParent().attr('href');
                this.load(url+'/member/ajax/bubble/format/html', {data:datauser, nbmod:nbmod});
            }
        }
    });


    /* tooltip jeux */
    $(".bubble_game").simpletip({
        baseClass: 'simpletip2',
        fixed: true,
        position: ["0", "-35px"],
        content: '<p class="center loading"><img src="'+img_url+'/icone/loading.gif" alt="" />',
        onBeforeShow: function() {

            var link = $(this.getParent());
            var firstTime = link.children('div').children('p').hasClass('loading');

            if(firstTime) {

                var datagame = this.getParent().children(1).attr('href');
                this.load(url+'/ajaxgame/bubble/format/html', {data:datagame});
            }
        }
    });




    /*
     * PLATEFORMES
     */

    /* changer de plateforme */
    if($('#change_platform').is("form")) {

        $('#change_platform_select').change(function() {

            /* on récupère la platform et on redirige */
            var platform = $('#change_platform_select').val();
            document.location.href = url+'/game/'+platform;

            return false;
        });

        $('#change_platform-tn_select').change(function() {

            /* on récupère la platform et on redirige */
            var platform = $('#change_platform-tn_select').val();
            document.location.href = url+'/tournament/'+platform;

            return false;
        });

        $('#change_platform-team_select').change(function() {

            /* on récupère la platform et on redirige */
            var platform = $('#change_platform-team_select').val();
            document.location.href = url+'/team/'+platform+'/list/date-desc/1';

            return false;
        });

        $('#change_platform-match_select').change(function() {

            /* on récupère la platform et on redirige */
            var platform = $('#change_platform-match_select').val();            
            document.location.href = url+'/match/'+platform;

            return false;
        });
    }




    /*
     * JEUX
     */
//    var backColor = '';
//    $(".ranking tr").live('hover', function(ev) {
//        /* si le membre peut ouvrir un challenge */
//        var challengeStatus = $('#challenge_status').html();
//
//        var icone = $(this).find(".icone2 img").attr('src');
//
//        if(challengeStatus == '1' && icone == img_url+'/icone/storm_grey.png') {
//            $(this).find(".icone2 img").attr('src', img_url+'/icone/storm.png');
//            $(this).find(".icone2 a").show();
//
//            backColor = $(this).css("backgroundColor");
//            $(this).css("backgroundColor", "#fffde8");
//        }
//
//        if (ev.type == 'mouseout') {
//
//            /* si le membre peut ouvrir un challenge */
//            challengeStatus = $('#challenge_status').html();
//
//            if(challengeStatus == '1') {
//                $(this).find(".icone2 img").attr('src', img_url+'/icone/storm_grey.png');
//                $(this).find(".icone2 a").hide();
//                $(this).css("backgroundColor", backColor);
//            }
//        }
//    });




    /*
     * INSCRIPTION
     */

    /* page d'inscription */
    $('#signin_adress').keyup(function() {

        /* on récupère la valeur du champ */
        var adress = $(this).val();

        if(adress != "") {
            /* on envoie l'adresse */
            postAddress(adress);
        }
        return false;

    });


    /* Effet pour supprimer un jeu qui a été ajouté */
    $("#signin_listgame li").live('mouseover', function() {

        $(this).addClass('coloTransparent');
        $(this).find('a').stop(true, true).fadeIn("fast");

        return false;

    }).live('mouseout', function() {

        $(this).removeClass('coloTransparent');
        $(this).find('a').stop(true, true).fadeOut("fast");

        return false;
    });


    /* pour supprimer un jeu qui a été ajouté */
    $("#signin_listgame li a").live('click', function() {

        $(this).parent().remove();

        return false;
    });


    /* rafraichit la liste des jeux au changement de plateforme */
    $('.signin_platform').change(function() {


        /* on récupère les plateformes */
        var inputplatform = $(".signin_platform:checked");
        var platform      = '';

        $.each(inputplatform, function(key, value) {

            platform += $(value).val()+',';
        });

        platform = substr(platform, 0, -1);

        /* on récupère la valeur du champ */
        var game     = $('#add_game').val();

        if(game != "") {

            /* Requête AJAX */
            $.ajax({
                type: 'GET',
                processData: true,
                url: url+'/ajaxgame/autocompletename/format/html',
                dataType: 'html',
                data: 'name='+game+'&platform='+platform,
                success: function(html){

                    $('#zone_autocomplete').html(html).show();
                }
            });

        } else {
            $('#zone_autocomplete').slideUp();
        }
        return false;
    });


    /* pour envoyer des invits */
    $("#signin_sendinvit a").click(function() {

        /* on récupère la valeur du champ */
        var email = $('#signin_sendemail').val();

        if(email != "") {

            /* Requête AJAX */
            $.ajax({
                type: 'GET',
                processData: true,
                url: url+'/member/ajax/sendinvit/format/html',
                dataType: 'html',
                data: 'email='+email,
                success: function(html){
                    $("#signin_sendemail").val(' ');
                    $("#signin_sendinvit a").html(html);
                }
            });
        }
        return false;
    });


    /* pour envoyer des invits */
    $(".jqicontainer #invitfriends_btn input").live('click', function() {

        /* on récupère la valeur du champ */
        var email = $('.jqicontainer #invitfriends_sendemail').val();

        if(email != "") {

            /* Requête AJAX */
            $.ajax({
                type: 'GET',
                processData: true,
                url: url+'/member/ajax/sendinvit/format/html',
                dataType: 'html',
                data: 'email='+email,
                success: function(html){
                    $(".jqicontainer #invitfriends_sendemail").val(' ');
                    $(".jqicontainer #invitfriends_infos").show();
                }
            });
        }
        return false;
    });


    /* Message twitter */
    $(".twitter_publish").click(function() {

        var message = '';
        var balise  = $(this);

        /* selon la page où on envoie */
        if($('.usercard_status').is("div")) {
            /* on récupère la valeur du champ */
            message = $('#user_statut').val();

        }else {
            /* on récupère la valeur du champ */
            message = $(this).attr('href');
            message = substr(message, 1);
        }

        if(message != "") {

            /* Requête AJAX */
            $.ajax({
                type: 'GET',
                processData: true,
                url: url+'/twitter/publish/format/html',
                dataType: 'html',
                data: 'message='+message,
                success: function(html){

                    if(html != '') {
                        balise.parent().html(html);
                    }
                }
            });
        }
        return false;
    });



    /*
     * MEMBRE ADMIN
     */


    /*
     * Carte dashboard
     */
    $("#user_dashboard_mapmember").click(function() {

        /* rafraichissement de la carte */
        friend = 0;
        data   = 'user';
        refreshMap(lat, lng);
        $("#player_infos").hide();
        $("#zone_infos").hide();

        /* gestion menu activé */
        $('.user_dashboard_maplink').removeClass('active');
        $(this).addClass('active');

    });

    $("#user_dashboard_mapfriend").click(function() {

        /* rafraichissement de la carte */
        friend = 1;
        data   = 'user';
        refreshMap(lat, lng);
        $("#player_infos").hide();
        $("#zone_infos").hide();

        /* gestion menu activé */
        $('.user_dashboard_maplink').removeClass('active');
        $(this).addClass('active');
    });

    $("#user_dashboard_mapzone").click(function() {

        /* rafraichissement de la carte */
        friend = 0;
        data   = 'zone';
        refreshMap(lat, lng);
        $("#player_infos").hide();
        $("#zone_infos").hide();

        /* gestion menu activé */
        $('.user_dashboard_maplink').removeClass('active');
        $(this).addClass('active');
    });

    $("#user_dashboard_maptournament").click(function() {

        /* rafraichissement de la carte */
        friend = 0;
        data   = 'tournament';
        refreshMap(lat, lng);
        $("#player_infos").hide();
        $("#zone_infos").hide();

        /* gestion menu activé */
        $('.user_dashboard_maplink').removeClass('active');
        $(this).addClass('active');
    });


    /*
     * Suppression ami
     */
    $(".friend_delete").click(function() {

        /* on récupère la valeur du champ */
        var idfriend = $(this).attr('href');
        idfriend     = substr(idfriend, 1);

        var link = $(this);

        /* selon suppresion page ami ou notification */
        var type = $(this).prev().attr('class');

        if(type == 'accept_friend notification_open') {
            type = 'notification';
        }else {
            type = 'listfriend';
        }

        if(idfriend != "") {
            /* Requête AJAX */
            $.ajax({
                type: 'GET',
                processData: true,
                url: url+'/member/ajax/deletefriend/format/html',
                dataType: 'html',
                data: 'idfriend='+idfriend+'&type='+type,
                success: function(html){
                    /* selon suppresion page ami ou notification */
                    if(html == 'notification') {
                        link.parent().parent().remove();
                    } else {
                        link.parent().parent().parent().parent().remove();
                    }
                }
            });
        }
        return false;
    });


    /* popup envoi de message */
    $(".friend_message").click(function() {

        var idfriend = $(this).attr('href');
        idfriend     = explode('_', idfriend);
        idfriend     = idfriend[1];
        $('input[name=iduser]').val(idfriend);


        var avatar   = $('#friend_avatar_'+idfriend).attr('src');
        avatar       = str_replace('48', '96', avatar);
        $('#messageuser_avataruser').attr('src', avatar);

        var nickname = $('#friend_nickname_'+idfriend).html();
        $('#modale_messageuser #user_nickname').html(nickname);

        var text = $('#modale_messageuser').html();

        $.prompt(text, {
            buttons: {}
        });

        return false;
    });


    /* Invitation ami */
    $(".invit_friends").click(function() {

        var text = $('#modale_invitfriends').html();

        $.prompt(text, {
            buttons: {}
        });

        return false;
    });



    /*
     * Suppression jeux d'un membre
     */
    $(".game_delete").click(function() {

        /* on récupère la valeur du champ */
        var idgame = $(this).attr('href');
        idgame     = substr(idgame, 1);

        var link = $(this);

        if(idgame != "") {
            /* Requête AJAX */
            $.ajax({
                type: 'GET',
                processData: true,
                url: url+'/member/ajax/deletegame/format/html',
                dataType: 'html',
                data: 'idgame='+idgame,
                success: function(html){

                    link.parent().parent().parent().parent().remove();
                }
            });

        }

        return false;
    });



    /*
     * Limite du nombre de caractères d'un statut
     */
    if($('#user_status_message').is("textarea")) {
        $('#user_status_message').limit('140');
    }


    /*
     * Notification ouverte
     */
    $(".notification_open").click(function() {

        /* on récupère la valeur du champ */
        var idnotif = $(this).attr('href');
        idnotif     = substr(idnotif, 3);
	//alert(idnotif);
        var link = $(this);

        if(idnotif != "") {
            /* Requête AJAX */
            $.ajax({
                type: 'GET',
                processData: true,
                url: url+'/member/ajax/opennotif/format/html',
                dataType: 'html',
                data: 'idnotif='+idnotif,
                beforeSend: function(){
                    link.unbind();//on enlève l'action pour éviter plusieurs envois
                },
                success: function(html){
                    link.parent().parent().remove();

                    // -1 sur le nombre de notifications affichées dans les compteurs de la page
                    /*var nb = parseInt( $('#hud_noti').html() );

                    nb = nb-1;
                    if((nb-1) < 0) nb = 0;   
                    $('#zNbNotifs').html(nb);
                    $('#hud_noti').html(nb);
                    $('#hud_noti2').html(nb);*/

                    var nb1 = $('#zNbNotifs').html();nb1 = (nb1 > 1) ? nb1-1 : 0 ;
                    var nb2 = $('#header_notifs_messages').html();nb2 = (nb2 > 1) ? nb2-1 : 0 ;

                    $('#zNbNotifs').html(nb1);
                    $('#top_notifs').html(nb1);
                    $('#header_notifs_messages').html(nb2);
                }
            });
        }
        return false;
    });



    /*
     * Demande d'ami acceptée
     */
    $(".accept_friend").click(function() {

        /* on récupère la valeur du champ */
        var idfriend = $(this).attr('href');
        idfriend     = substr(idfriend, 1);

        var link = $(this);

        if(idfriend != "") {
            /* Requête AJAX */
            $.ajax({
                type: 'GET',
                processData: true,
                url: url+'/member/ajax/acceptfriend/format/html',
                dataType: 'html',
                data: 'idfriend='+idfriend,
                success: function(html){

                    link.parent().parent().remove();

                    // -1 sur le nombre de notifications affichées dans les compteurs de la page
                    var nb = parseInt( $('#hud_noti').html() );

                    nb = nb-1;
                    if((nb-1) < 0) nb = 0;
                    $('#zNbNotifs').html(nb);
                    $('#hud_noti').html(nb);
                    $('#hud_noti2').html(nb);
                }
            });
        }
        return false;
    });


    /*
     * Tableau de bord des notifs (mini pagination)
     */
    $("#dashboard_notif a").click(function() {
        /* affiche le li caché suivant */
        var li = $(this).parent().parent().parent().find('li.hide:first');

        if(li.is("li")) {
            li.slideDown(1500).removeClass('hide');
        }
    });




    /*
     * MEMBRE
     */
    $("#add_friend").click(function() {

        var text = $('#zone_addfriend').html();

        $.prompt(text, {
            buttons: {}
        });

        return false;
    });


    /* ajout ami */
    $('.add_friend').live('click', function() {

        var fUser    = $(this).attr('href');
        fUser        = substr(fUser, 1);
        fUser        = explode('_', fUser);

        /* Requête AJAX */
        $.ajax({
            type: 'GET',
            processData: true,
            url: url+'/member/ajax/friendrequest/format/html',
            dataType: 'html',
            data: 'user='+fUser[2],
            success: function(html){

                $.prompt(html, {
                    buttons: {}
                });
            }
        });

        return false;
    });


    /* ajout ami */
    $('#form_friendrequest input[type=submit]').live('click', function() {

        var fUser    = $('#form_friendrequest input[type=hidden]').val();

        /* Requête AJAX */
        $.ajax({
            type: 'GET',
            processData: true,
            url: url+'/member/ajax/friendrequestsend/format/html',
            dataType: 'html',
            data: 'user='+fUser,
            success: function(html){

                $('#form_friendrequest .modale_submit').hide();
                $('#form_friendrequest .modale_confirmation_message2').show();
            }
        });

        return false;
    });


    /* Envoi d'un message */
    $('.jqimessage input[name=messageuser_yes]').live('click', function() {
        if($('.jqimessage #modale_message').val() != '' && $('.jqimessage #modale_user_title').val() != '' ) {
            /* Requête AJAX */
            $.ajax({
                type: 'POST',
                processData: true,
                url: url+'/member/admin/mailcreate/format/html',
                dataType: 'html',
                data: $('.jqimessage #messageuser').serialize(),
                success: function(html){
                    $('.jqimessage .modale_confirmation_message').show();
                    $('.jqimessage #messageuser_required').hide();
                    $('.jqimessage #modale_message').attr('disabled', 'disabled');
                    $('.jqimessage #messageuser_buttons').hide();
                    $('.jqimessage .modale_footer').html(translate["you_can_close_window"]);
                }
            });
        }else{

            if( $('.jqimessage #modale_message').val() == '' )
                $('.jqimessage #messageuser_required').show();

            if( $('.jqimessage #modale_user_title').val() == '' )
                $('.jqimessage #messageuser_required2').show();
        }

        return false;
    });

    $('#usercard .open_message_challenge').live('click', function() {
        var text = $('#modale_messageuser_reply').html();

        $.prompt(text, {
            buttons: {}
        });
    });

    /* Ouverture d'un message */
    $('#usercard .open_message').live('click', function() {

        var infos		= $(this).attr('href');
        var infos_array	        = explode('_', infos);
        var notif		= infos_array[1];
        var message		= infos_array[3];

        window.location.href = url+'/member/admin/mail/detail/'+message+'/last';

        return false;
    });




    /*
     * ZONE & NOTIF membre challenge
     */

    /* on affiche un cercle rouge sur la carte quand passe sur l'avatar d'un membre */
    $('#zone_list_players li').hover(function() {

        /* ses coordonnées */
        var tempLat = $(this).find(".lat").html();
        var tempLng = $(this).find(".lng").html();

        tempLat = parseFloat(tempLat);
        tempLng = parseFloat(tempLng);

        /* on créé le cercle */
        createCircle(tempLat, tempLng);

    }, function() {
        map.removeOverlay(circle);
    });


    /* pop up challenge sur un membre */
    $('.challenge_open_user').live('click', function() {

        var cUser    = $(this).attr('href');
        cUser        = substr(cUser, 1);
        cUser        = explode('_', cUser);

        /* Requête AJAX */
        $.ajax({
            type: 'GET',
            processData: true,
            url: url+'/member/ajax/challengeopen/format/html',
            dataType: 'html',
            data: 'user='+cUser[2]+"&platform="+platformGame+"&game="+game+"&mod="+mod+"&zone="+zone,

            beforeSend:function()
            {
                var html = $('#zAjaxLoading').parent().html();
                $.prompt(html, {
                    buttons: {}
                });
            },
            success: function(html){

                $('.jqimessage').html(html);
                /*$.prompt(html, {
                    buttons: {}
                });*/
            }
        });

        return false;
    });


    /* pop up challenge sur un membre étape console */
    $('.challenge_open_user_platform').live('click', function() {

        var cUser     = $('.modale_challenge input[name=modale_challenge_user]').val();
        var cPlatform = $(this).children(0).attr('alt');

        /* Requête AJAX */
        $.ajax({
            type: 'GET',
            processData: true,
            url: url+'/member/ajax/challengeopen/format/html',
            dataType: 'html',
            data: 'user='+cUser+"&platform="+cPlatform,
            beforeSend:function()
            {
                var html = $('#zAjaxLoading').parent().html();
                $('.jqimessage').html(html);
            },
            success: function(html){

                $('.jqimessage').html(html);
            }
        });

        return false;
    });


    /* pop up challenge sur un membre étape jeu */
    $('.challenge_open_user_game').live('click', function() {

        var cUser     = $('.modale_challenge input[name=modale_challenge_user]').val();
        var cPlatform = $('.modale_challenge input[name=modale_challenge_platform]').val();
        var cGameMod  = $(this).attr('href');
        cGameMod      = substr(cGameMod, 1);
        cGameMod      = explode('_', cGameMod);

        /* Requête AJAX */
        $.ajax({
            type: 'GET',
            processData: true,
            url: url+'/member/ajax/challengeopen/format/html',
            dataType: 'html',
            data: 'user='+cUser+"&platform="+cPlatform+"&game="+cGameMod[1]+"&mod="+cGameMod[2],
            beforeSend:function()
            {
                var html = $('#zAjaxLoading').parent().html();
                $('.jqimessage').html(html);
            },
            success: function(html){

                $('.jqimessage').html(html);
            }
        });

        return false;
    });


    /* pop up challenge sur un membre étape zone */
    $('.challenge_open_user_zone').live('click', function() {

        var cUser     = $('.modale_challenge input[name=modale_challenge_user]').val();
        var cPlatform = $('.modale_challenge input[name=modale_challenge_platform]').val();
        var cGame     = $('.modale_challenge input[name=modale_challenge_game]').val();
        var cMod      = $('.modale_challenge input[name=modale_challenge_mod]').val();
        var cZone     = $(this).attr('href');
        cZone         = substr(cZone, 1);
        cZone         = explode('_', cZone);

        /* Requête AJAX */
        $.ajax({
            type: 'GET',
            processData: true,
            url: url+'/member/ajax/challengeopen/format/html',
            dataType: 'html',
            data: 'user='+cUser+"&platform="+cPlatform+"&game="+cGame+"&mod="+cMod+"&zone="+cZone[1],
            beforeSend:function()
            {
                var html = $('#zAjaxLoading').parent().html();
                $('.jqimessage').html(html);
            },
            success: function(html){

                $('.jqimessage').html(html);
            }
        });

        return false;
    });


    /* Ouverture de challenge */
   $('.modale_challenge .valid input[type=submit]').live('click', function() {

        /* Requête AJAX */
        $.ajax({
            type: 'POST',
            processData: true,
            url: url+'/member/ajax/challengeopenfinish/format/html',
            dataType: 'html',
            data: $('.modale_challenge .valid').serialize(),
            success: function(html){
                $('.jqicontainer .challengeopen_ok_infos').show();
                $('.jqicontainer .grad_orange_btn').hide();
                $('.jqicontainer .grad_blue_btn').hide();
                $('.jqicontainer .modale_footer').html(translate["you_can_close_window"]);

                $('#zComment').hide();
            }
        });

        return false;
   });

   /* Challenge à plusieurs */
   $('.modale_challenge .valid input[type=button]').live('click', function() {

        $('.jqicontainer .subtitle2').show();
        $('.jqicontainer .subtitle').hide();

        var temp = $('.jqicontainer .user2_avatar').attr('src');
        temp     = str_replace('96', '48', temp);
        $('.jqicontainer .user2_avatar').attr('src', temp);
        $('.jqicontainer .user2_avatar').attr('title', $('.user2_nickname').html());

        $('.jqicontainer .challengers_ffa').show();
        $('.jqicontainer .challengers_1v1').hide();
        $(this).hide();

        return false;
   });

   // modale de challenge > ajouter un commentaire
   $('.modale_challenge #addCommentLink').live('click', function(){

       $('#zComment div').toggleClass('hide');

       return false;
   });

   /* Autocomplete player */
   $('.jqicontainer .challengers_ffa input[name=nickname]').live('keyup', function() {

        /* on récupère la valeur du champ */
        var nickname     = $(this).val();
        var user1        = $('.jqicontainer .valid input[name=mc_user1]').val();
        var user2        = $('.jqicontainer .valid input[name=mc_user2]').val();
        var user3        = $('.jqicontainer .valid input[name=mc_user3]').val();
        var cGame        = '';
        var cMod         = '';

        if(game < 1) {
            cGame        = $('.modale_challenge input[name=mc_game]').val();
        } else {
            cGame        = game;
        }

        if(zone < 1) {
            cZone        = $('.modale_challenge input[name=mc_zone]').val();
        } else {
            cZone        = zone;
        }

        if(strlen(nickname) > 1) {

            /* Requête AJAX */
            $.ajax({
                type: 'GET',
                processData: true,
                url: url+'/member/ajax/autocomplete/format/html',
                dataType: 'html',
                data: 'nickname='+nickname+'&idgame='+cGame+'&idzone='+cZone+'&user1='+user1+'&user2='+user2+'&user3='+user3,
                success: function(html){

                    $('.jqicontainer .zone_autocomplete').html(html).show();
                }
            });

        } else {
            $('.jqicontainer .zone_autocomplete #autocomplete2').slideUp();
        }

        return false;
   });

   /* Autocomplete player, ajout du joueur */
   $('.jqicontainer #autocomplete2 a').live('click', function() {

        $('.jqicontainer .message1').hide();
        $('.jqicontainer .message2').show();
        $('.jqicontainer .message_valid2').html(translate["challengeopen_ok_infos3"]);

        /* on récupère la valeur du champ */$(this)
        var user3 = $('.jqicontainer .valid input[name=mc_user3]').val();
        var user4 = $('.jqicontainer .valid input[name=mc_user4]').val();

        $('.jqicontainer .challengers_ffa input[name=nickname]').val('');

        if(user3 == "") {
            $('.jqicontainer .valid input[name=mc_user3]').val($(this).next().html());
            $('.jqicontainer .user3_avatar').attr('src', $(this).next().next().html());

            $('.jqicontainer .user3_avatar').next().attr('title', $(this).html());

        }else if(user4 == "") {
            $('.jqicontainer .valid input[name=mc_user4]').val($(this).next().html());
            $('.jqicontainer .user4_avatar').attr('src', $(this).next().next().html());
            $('.jqicontainer .user4_avatar').next().attr('title', $(this).html());
        }

        $('.jqicontainer .zone_autocomplete #autocomplete2').slideUp();

        return false;
   });

   /* Autocomplete player, effet hover pour suppression du joueur */
   $('.jqicontainer .user_hover').live('hover', function (ev) {

        var user  = $(this).children().attr('class');
        var user3 = $('.jqicontainer .valid input[name=mc_user3]').val();
        var user4 = $('.jqicontainer .valid input[name=mc_user4]').val();

        if( (user == 'user3_avatar' && user3 != '') || (user == 'user4_avatar' && user4 != '') ) {
            if (ev.type == 'mouseover') {
                $(this).children().addClass('fade');
                $(this).children().next().removeClass('hide');
            }
        }

        if (ev.type == 'mouseout') {
            $(this).children().removeClass('fade');
            $(this).children().next().addClass('hide');
        }
    });

   /* Autocomplete player, suppression du joueur */
   $('.jqicontainer .user_hover a').live('click', function() {

        var user  = $(this).prev().attr('class');
        var user3 = $('.jqicontainer .valid input[name=mc_user3]').val();
        var user4 = $('.jqicontainer .valid input[name=mc_user4]').val();

        if(user == 'user3_avatar fade' && user3 != '') {
            $('.jqicontainer .valid input[name=mc_user3]').val('');
            $(this).prev().attr('src', img_url+'/icone/square_48.jpg');
            $('.jqicontainer .challengers_ffa input[name=nickname]').val('');
        }

        if(user == 'user4_avatar fade' && user4 != '') {
            $('.jqicontainer .valid input[name=mc_user4]').val('');
            $(this).prev().attr('src', img_url+'/icone/square_48.jpg');
            $('.jqicontainer .challengers_ffa input[name=nickname]').val('');
        }
    });

    /* pop up de réponse à une proposition de challenge */
    $('.challenge_answer').click(function() {

        var challengeid = $(this).attr('href');
        challengeid     = substr(challengeid, 1);

        /* Requête AJAX */
            $.ajax({
                type: 'GET',
                processData: true,
                url: url+'/zone/ajax/challengeuanswer/format/html',
                dataType: 'html',
                data: 'challengeid='+challengeid,
                beforeSend:function()
                {
                    var html = $('#zAjaxLoading').parent().html();
                    $.prompt(html, {
                        buttons: {}
                    });
                },
                success: function(html){

                    $('.jqimessage').html(html);
                    /*$.prompt(html, {
                        buttons: {}
                    });*/
                }
            });
    });

     /* Réponse à une demande challenge */
   $('.modale_challenge .reply input[type=submit], .modale_challenge .reply input[type=button]').live('click', function() {

        /* la réponse */
        var reply = $(this).attr('name');

       /* Requête AJAX */
        $.ajax({
            type: 'POST',
            processData: true,
            url: url+'/zone/ajax/challengeuanswerreply/format/html',
            dataType: 'html',
            data: $('.modale_challenge .reply').serialize()+'&reply='+reply,
            success: function(html){
                $('.jqicontainer .challengeopen_ok_infos').html(html).show();
                $('.jqicontainer .grad_red_btn').hide();
                $('.jqicontainer .grad_green_btn').hide();
                $('.jqicontainer .reply').hide();
                $('.jqicontainer .modale_footer').html(translate["you_can_close_window"]);

                /* on cache la notif du challenge */
                var idchallenge = $('.jqicontainer input[name=challenge_id]').val();
                $('#notifchallengeinvit_'+idchallenge).parent().parent().hide();
                $('#listchallenge_'+idchallenge).hide(); // si on répond au challenge depuis la liste des challenge

                // -1 sur le nombre de notifications affichées dans les compteurs de la page
                var nb = parseInt( $('#hud_noti').html() );

                nb = nb-1;
                if((nb-1) < 0) nb = 0;
                $('#zNbNotifs').html(nb);
                $('#hud_noti').html(nb);
                $('#hud_noti2').html(nb);

                $('#zComment').hide();
            }
        });

        return false;
   });



    /* pop up invitation à jouer sur un membre */
    $('.play_open_user').live('click', function() {

        var cUser    = $(this).attr('href');
        cUser        = substr(cUser, 1);
        cUser        = explode('_', cUser);

        /* Requête AJAX */
        $.ajax({
            type: 'GET',
            processData: true,
            url: url+'/member/ajax/playopen/format/html',
            dataType: 'html',
            data: 'user='+cUser[2]+"&platform="+platformGame+"&game="+game+"&mod="+mod+"&zone="+zone,

            beforeSend:function()
            {
                var html = $('#zAjaxLoading').parent().html();
                $.prompt(html, {
                    buttons: {}
                });
            },
            success: function(html){

                $('.jqimessage').html(html);
            }
        });

        return false;
    });


    /* pop up invitation à jouer sur un membre étape console */
    $('.play_open_user_platform').live('click', function() {

        var cUser     = $('.modale_play input[name=modale_play_user]').val();
        var cPlatform = $(this).children(0).attr('alt');

        /* Requête AJAX */
        $.ajax({
            type: 'GET',
            processData: true,
            url: url+'/member/ajax/playopen/format/html',
            dataType: 'html',
            data: 'user='+cUser+"&platform="+cPlatform,
            beforeSend:function() {
                var html = $('#zAjaxLoading').parent().html();
                $('.jqimessage').html(html);
            },
            success: function(html) {
                $('.jqimessage').html(html);
            }
        });

        return false;
    });


    /* pop up invitation à jouer sur un membre étape jeu */
    $('.play_open_user_game').live('click', function() {

        var cUser     = $('.modale_play input[name=modale_play_user]').val();
        var cPlatform = $('.modale_play input[name=modale_play_platform]').val();
        var cGame     = $(this).attr('href');
        cGame         = substr(cGame, 1);
        cGame         = explode('_', cGame);

        /* Requête AJAX */
        openChallengePopup(cGame[1], cPlatform, cUser);
        return false;
    });

    /* cacher une proposition de date */
    $('.invitation_proposition_hide').live('click', function() {

        var parent = $(this).parent();
        parent.addClass('hide');
        parent.find('.date_picker').val('');

        $('.invitation_proposition_add').parent().show();

        return false;
    });


    /* cacher une proposition de date */
    
    $('.invitation_proposition_add').live('click', function() {

        $(".list_invitation_proposition").find('li.hide:first').removeClass('hide');

        /* combien de proposition sont déjà affichées */
        var nb = 3 - parseInt($(".list_invitation_proposition").find('.hide').length);

        if(nb > 2) {
            $('.invitation_proposition_add').parent().hide();
        }
        return false;
    });


    /* pop up invitation à jouer validation dernier formulaire */
    $('#modale_play_finish').live('submit', function() {

        var cUser     = $('.modale_play input[name=modale_play_user]').val();
        var cPlatform = $('.modale_play input[name=modale_play_platform]').val();
        var cGame     = $('.modale_play input[name=modale_play_game]').val();
        var form      = $('#modale_play_finish').serialize();

        /* Requête AJAX */
        $.ajax({
            type: 'GET',
            processData: true,
            url: url+'/member/ajax/playopen/format/html',
            dataType: 'html',
            data: 'user='+cUser+"&platform="+cPlatform+"&game="+cGame+"&"+form,
            beforeSend:function()
            {
                var html = $('#zAjaxLoading').parent().html();
                $('.jqimessage').html(html);
            },
            success: function(html){
                $('.jqimessage').html(html);
            }
        });
        return false;
    });


    /* Popup action membre d'une zone */
    $(".invitation_form input[name=proposition]").click(function() {

        var value = $(this).val();

        if(value != 'other') {
            $('.invitation_form .list_invitation_proposition').slideUp();

       } else {
            $('.invitation_form .list_invitation_proposition').slideDown();
       }

    });
    

    // datepicker
    $('.date_picker').datePicker({clickInput:true});

    /* pop up création d'un tournoi */
    $('.tournament_create').live('click', function() {

        /* Requête AJAX */
        $.ajax({
            type: 'GET',
            processData: true,
            url: url+'/member/ajax/tournamentcreate/format/html',
            dataType: 'html',
            data: "platform="+platformGame+"&game="+game,

            beforeSend:function()
            {
                var html = $('#zAjaxLoading').parent().html();
                $.prompt(html, {
                    buttons: {}
                });
            },
            success: function(html){

                $('.jqimessage').html(html);
                /*$.prompt(html, {
                    buttons: {}
                });*/
            }
        });

        return false;
    });


    /* pop up challenge sur un membre étape console */
    $('.tournamentcreate_platform').live('click', function() {

        var cPlatform = $(this).children(0).attr('alt');

        /* Requête AJAX */
        $.ajax({
            type: 'GET',
            processData: true,
            url: url+'/member/ajax/tournamentcreate/format/html',
            dataType: 'html',
            data: "platform="+cPlatform,
            beforeSend:function()
            {
                var html = $('#zAjaxLoading').parent().html();
                $('.jqimessage').html(html);
            },
            success: function(html){

                $('.jqimessage').html(html);
            }
        });

        return false;
    });


    /* pop up challenge sur un membre étape jeu */
    $('.tournamentcreate_game').live('click', function() {

        var cGame = $(this).attr('href');
        cGame     = explode('_', cGame);

        document.location.href = url+'/tournament/create/infosbase/g/'+cGame[1];

        return false;
    });


    /* Popup action membre d'une zone */
    $(".zone_admin_users select").change(function() {

        var type     = $(this).val();
        var iduser   = $(this).attr('name');
        iduser       = explode('_', iduser);
        iduser       = iduser[1];
        var nickname = $(this).parent().parent().prev().find('p .link').html();
        var avatar   = $(this).parent().parent().prev().find('.avatar').attr('src');
        avatar       = str_replace('48', '96', avatar);

        $('.zone_action_user input[name=iduser]').val(iduser);
        $('.zone_action_user #user_nickname').html(nickname);
        $('.zone_action_user #zone_acceptuser_avataruser').attr('src', avatar);

        /* on récupère le contenu de la modale */
        var text = '';
        if(type == 'accept') {
            text = $('#modale_zone_acceptuser').html();

        } else if(type == 'leave') {
            text = $('#modale_zone_leaveuser').html();

        } else if(type == 'message') {
            text = $('#modale_zone_messageuser').html();

        /* validation de challenge */
        } else if(type == 'enter_result') {

            var ids = $(this).attr('id');
            ids     = explode('_', ids);
            var idchallenge = ids[2];
            var idzone      = ids[2];

            document.location.href = url+'/zone/admin/validchallenge/idzone/'+idzone+'/idchallenge/'+idchallenge;
        }

        if(text != '') {

            $.prompt(text, {
                buttons: {}
            });

            $('div.jqitop').css('border-color', '#DB0000');
            $('div.jqi .jqicontainer').css('border-color', '#DB0000');
            $('div.jqi .jqicontainer h3 ').css('color', '#505C71');
        }

        return false;
    });


    /* Cration d'un challenge par l'admin d'une zone => sélection des participants */
    $(".zone_create_challenge").change(function() {

        var data    = $(this).attr('name');
        var userid  = $(this).val();

        /* Requête AJAX */
        $.ajax({
            type: 'GET',
            processData: true,
            url: url+'/zone/ajax/createchallenge/format/html',
            dataType: 'html',
            data: 'userid='+userid,
            success: function(html){

                $('#create_challenge_'+data).html(html);
            }
        });

        return false;
    });


    /* Popup action challenge d'une zone */
    $(".zone_admin_challenge select").change(function() {

        var type     = $(this).val();

        /* on récupère le contenu de la modale */
        if(type == 'enter_result') {

            var ids = $(this).attr('id');
            ids     = explode('_', ids);
            var idchallenge = ids[2];
            var idzone      = ids[3];

            document.location.href = url+'/zone/admin/validchallenge/idzone/'+idzone+'/idchallenge/'+idchallenge;
        }

        return false;
    });


    /* Slider challenge FP */
    $(".challenge_fp_slider").slider({
                    range: "min",
                    value: 0,
                    min: -10,
                    max: 10,
        step: 1,
                    slide: function(event, ui) {
            $(this).next().next().val($(this).prev().prev().attr('id')+'_'+ui.value);
                    }
            });

    /* drag and drop */
    $("#drag_challenge_user div img").draggable({revert: true, containment: '#zone_drag'});
    $("#drag_challenge_user_default div img").draggable({revert: 'invalid', containment: '#zone_drag'});

    $("#drop_result_avatar_user li").droppable({
        // Lorsque l'on relache un élément sur la poubelle
        drop: function(event, ui){

            /* si vide */
            if($(this).html() == '&nbsp;' || $(this).html() == ' ' || $(this).html() == '') {

                // On supprimer l'élément de la page, le setTimeout est un fix pour IE (http://dev.jqueryui.com/ticket/4088)
                setTimeout(function() {ui.draggable.addClass('hide');}, 1);

                /* on ajoute l'avatar et le pseudo */
                $(this).html(' ');
                $(this).html('<img src="'+ui.draggable.attr('src')+'" alt="" title="'+ui.draggable.attr('title')+'" />');
                $('#nickname_'+$(this).attr('id')).html(substr(ui.draggable.attr('title'), 0, 20));

                /* on enregistre l'id */
                $('input[name='+$(this).attr('id')+']').val(ui.draggable.attr('id'));
            }

        }
    });

    $("#challenge_result_cancel a").click(function() {

        $('#drag_challenge_user img').removeClass('hide');

        $("#drop_result_avatar_user li").html(' ');
        $(".result_user").val(' ');

        $("#result_avatar_user_1v1 a").html(translate["active_deuce"]);
        $("#result_avatar_user_1v1 span").html(' ');
        $("#result_avatar_user_1v1 strong:last").html(translate["loss_point"]);
        $("#result_avatar_user_1v1 strong:first").html(translate["win_point"]);
        $("#result_avatar_user_1v1 input").val(0);

        $("#result_avatar_user_ffa span").html(' ');
    });

    $("#result_avatar_user_1v1 a").click(function() {

        var status = $(this).html();

        if(status == translate["deactive_deuce"]) {

            $(this).html(translate["active_deuce"]);
            $("#result_avatar_user_1v1 strong:last").html(translate["loss_point"]);
            $("#result_avatar_user_1v1 strong:first").html(translate["win_point"]);
            $("#result_avatar_user_1v1 input").val(0);

        } else {
            $(this).html(translate["deactive_deuce"]);
            $("#result_avatar_user_1v1 strong").html(translate["deuce_point"]);
            $("#result_avatar_user_1v1 input").val(1);
        }

        return false;
    });


    /* Page pro */
    $(".pagepro_editarticle").click(function() {

        var form = $('#pagepro_form_editarticle').html();

        $.prompt(form, {
                        buttons: {}
                    });

        return false;
    });


    /* supprime une image de la galerie */
    $('.gallery_img_delete').live('click', function() {

        var link = $(this);

        var id = link.attr('href');
        id = explode('_', id);

        /* Requête AJAX */
        $.ajax({
            type: 'GET',
            processData: true,
            url: url+'/gallery/deletemedia/format/html',
            dataType: 'html',
            data: 'id='+id[1],
            success: function(html){

                link.parent().hide();
            }
        });

        return false;
    });



    //on appelle le code  que si google map est chargé -- solution temporaire
    if(typeof(GBrowserIsCompatible)!='undefined') {

        /* Si le navigateur est compatible avec l'API de Google Maps et si l'initialisation a été faite */
        if (GBrowserIsCompatible()) {

            /* Création d'une nouvelle carte sur la page HOME */
            if($('#map_home').is("div")) {
                map = new GMap2(document.getElementById("map_home"));

                page         = $('#fmap_page').val();
                data         = $('#fmap_data').val();
                platformGame = '';
                game         = 0;
                mod          = 0;
                nbmod        = $('#fmap_nbmod').val();
                award        = 0;
                pagination   = 0;
                find         = $('#fmap_find').val();

            /* Création d'une nouvelle carte sur une page de contenu */
            } else if($('#map_page').is("div")) {
                map = new GMap2(document.getElementById("map_page"));

                page         = $('#fmap_page').val();
                data         = $('#fmap_data').val();
                platformGame = $('#fmap_platform').val();
                game         = $('#fmap_game').val();
                mod          = $('#fmap_mod').val();
                nbmod        = $('#fmap_nbmod').val();
                zone         = $('#fmap_zone').val();
                team         = $('#fmap_team').val();
                award        = $('#fmap_award').val();
                pagination   = $('#fmap_pagination').val();
                find         = $('#fmap_find').val();

            /* Création d'une nouvelle carte sur le dashbaord membre */
            } else if($('#map_dashboard').is("div")) {
                map = new GMap2(document.getElementById("map_dashboard"));

                page         = $('#fmap_page').val();
                data         = $('#fmap_data').val();
                platformGame = $('#fmap_platform').val();
                game         = $('#fmap_game').val();
                friend       = $('#fmap_friend').val();


            /* Création d'une nouvelle carte sur la page d'inscription et création de zone */
            } else if($('#signin_map').is("div")) {
                map = new GMap2(document.getElementById("signin_map"));

                page         = $('#fmap_page').val();

                /* permet de récupérer lat, lng à partir d'une adresse */
                geocoder = new GClientGeocoder();

                map.addControl(new GLargeMapControl3D());
                //map.enableScrollWheelZoom();

                /* initiliase la carte */
                initiate();

                var address = $('#signin_adress').val();

                geocoder.getLocations(address,function(response) {
                    if (!response || response.Status.code != 200) {
                    //alert("\"" + address + "\" not found");
                    } else {

                        place = response.Placemark[0];
                        lat   = place.Point.coordinates[1];
                        lng   = place.Point.coordinates[0];

                        var accuracy = place.AddressDetails.Accuracy;
                        var tabAccuracy = new Array(2,4,6,10,12,13,16,16,17); // en fonction de la précision, défini le zoom

                        point = new GLatLng(lat, lng);
                        map.setCenter(point, tabAccuracy[accuracy]);

                        /* on crée le marker */
                        createMarker(point, 'location');
                    }
                });
            }


            /* si une carte a été créé,on fait toutes les actions nécessaires */
            if($('.map').is("div") && !$('#signin_map').is("div")) {

                /* initialise la carte */
                initiate();

                /* on réinitialise le zoom en cas de prob */
                if(zoom == 0) {
                    zoom = 12;
                }

                /* zoom min */
                G_PHYSICAL_MAP.getMinimumResolution	= function () {return 4};
                G_NORMAL_MAP.getMinimumResolution	= function () {return 4};
                G_SATELLITE_MAP.getMinimumResolution	= function () {return 4};
                G_HYBRID_MAP.getMinimumResolution	= function () {return 4};

                /* on positionne le switch : user / zone */
//                if(page != 'zone' && page != 'userdashboard' && page != 'find_user') {
//
//                    $('.map_switch a').css('display', 'block');
//
//                    var map_switch = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(0, 15));
//                    map_switch.apply(document.getElementById("map_switch_user"));
//                    map.getContainer().appendChild(document.getElementById("map_switch_user"));
//
//                    map_switch = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(0, 45));
//                    map_switch.apply(document.getElementById("map_switch_zone"));
//                    map.getContainer().appendChild(document.getElementById("map_switch_zone"));
//
//                    map_switch = new GControlPosition(G_ANCHOR_TOP_RIGHT, new GSize(0, 75));
//                    map_switch.apply(document.getElementById("map_switch_tournament"));
//                    map.getContainer().appendChild(document.getElementById("map_switch_tournament"));
//                }

                map.addControl(new GLargeMapControl3D());
                //map.enableScrollWheelZoom();
                

                /* on ajoute un évènement dragend sur la carte */
                GEvent.addListener(map, 'dragend', function() {

                    /******/
                    /* on ne rafraichit que si l'utilisateur est sortie de la carte invisible extend */

                    var maxLat = map.getBounds().getNorthEast().lat();
                    var minLat = map.getBounds().getSouthWest().lat();
                    var maxLng = map.getBounds().getNorthEast().lng();
                    var minLng = map.getBounds().getSouthWest().lng();

                    var centerMoveLat = map.getCenter().lat();
                    var centerMoveLng = map.getCenter().lng();

                    var extendY = Math.abs(maxLat - minLat)*extendPercent;
                    var extendX = Math.abs(maxLng - minLng)*extendPercent;

                    if ((centerMoveLng > (centerLng + extendX)) || (centerMoveLng < (centerLng - extendX)) || (centerMoveLat > (centerLat + extendY)) || (centerMoveLat < (centerLat - extendY))){
                        centerLat = map.getCenter().lat();
                        centerLng = map.getCenter().lng();
                        maxLat = map.getBounds().getNorthEast().lat();
                        minLat = map.getBounds().getSouthWest().lat();
                        maxLng = map.getBounds().getNorthEast().lng();
                        minLng = map.getBounds().getSouthWest().lng();

                        /**************************/
                        /* on rafraichit la carte */
                        refreshMap(centerMoveLat, centerMoveLng);


                    } else {

                        /* on rafraichit juste le fil d'ariane */
                        breadCrumb(centerMoveLat, centerMoveLng);
                    }

                    lat = centerMoveLat;
                    lng = centerMoveLng;
                });

                /* on ajoute un évènement zoom sur la carte */
                GEvent.addListener(map, 'zoomend', function(oldLevel, newLevel) {

                    /* pas besoin si on zoom car c'est géré par le moveend */
                    //if(oldLevel <= newLevel) {

                        lat = map.getCenter().lat();
                        lng = map.getCenter().lng();

                        /**************************/
                        /* on rafraichit la carte */
                        refreshMap(lat, lng);
                    //}

                });


                /*************/
                /* évènement */
                $('#breadcrumb a').live('click', function() {

                    /* on récupère la valeur du zoom dans le href */
                    var goZoom = $(this).attr('href');
                    goZoom     = substr(goZoom, 1);

                    /* on zoom, le rafraichissement des données est fait via l'évent zoom de la carte */
                    map.setZoom(parseInt(goZoom));

                    return false;
                });


            }

        /* Si le navigateur n'est pas compatible avec l'API de Google Maps */
        } else{
            alert('Désolé, mais votre navigateur n\'est pas compatible avec Google Maps');
        }
    }


});



/*
 * Effectuer les actions utiles de la map
 * récupère les joueurs
 * récupère les pubs si besoin
 * regénère le fil d'ariane
 * @param lat float
 * @param lng float
 * @param autoZoom bool
 */
function refreshMap(lat, lng, autoZoom) {

    /* valeur par défaut */
    if(autoZoom == undefined) {
        autoZoom = false;
    }

    /*si page de géoloc pas de refresh */
    if(page != 'location') {

        /* on récupère tous les membres de la carte avec cluster */
        if(data == 'user') {
            getArea('member', false);

        /* on récupère toutes les zones de la carte avec cluster */
        } else if(data == 'zone') {
            getArea('zone', autoZoom);

        /* on récupère toutes les tournois de la carte avec cluster */
        } else if(data == 'tournament') {
            getArea('tournament', false);

        /* on récupère une page et ses membres */
        } else if(data == 'zone_user') {
            getAreaZone(autoZoom);

        } else if(data == 'team_user') {
            getAreaTeam(autoZoom);
        }

        /* si besoin recupère les pubs */
        if(map.getZoom() >= zoomPage && page != 'one_zone' && page != 'find_user' && page != 'team' && data != 'zone') {
            //getArea('zone', false, 'pro');
        }

        /* on affiche le fil d'Ariane */
        breadCrumb(lat, lng);


    } else {
        /* utile pour la béta */
        if(city == '') {
            /* on créé le marker */
            createMarker(point, 'location');
        }
    }
}


/*
 * Permet de récupérer les membres ou zones de la carte avec un cluster et d'assigner leur marker + tooltip
 */
function getAreaOld(type) {

    /* on indique que la carte est en train de charger */
    $('#loader').fadeIn();

    map.clearOverlays();

    var maxLat    = map.getBounds().getNorthEast().lat();
    var minLat    = map.getBounds().getSouthWest().lat();
    var maxLng    = map.getBounds().getNorthEast().lng();
    var minLng    = map.getBounds().getSouthWest().lng();
    var zoomLevel = map.getZoom();

    var urlstr = url+"/"+type+"/ajax/area/format/xml?maxlat="+maxLat+"&minlat="+minLat+"&maxlng="+maxLng+"&minlng="+minLng+"&zoom="+zoomLevel+"&platform="+platformGame+"&game="+game+"&mod="+mod+"&award="+award+"&friend="+friend+"&find="+find;

    GDownloadUrl(urlstr, function(data) {

        xml = GXml.parse(data);
        var markers = xml.documentElement.getElementsByTagName("marker");

        for (var i = 0; i < markers.length; i++) {

            /* où se situe le marker */
            var point = new GLatLng(parseFloat(markers[i].getAttribute("lat")),parseFloat(markers[i].getAttribute("lng")));

            /* on crée le marker */
            createMarker(point, markers[i]);
        }

        /* on indique que la carte est prête */
        $('#loader').fadeOut();
    });
}


/*
 * Géocode une adresse et affiche les membres
 * @param address string
 * @param type string selon où on appelle la fonction
 */
function postAddress(address, callback) {

    /* se, valeur par défaut */
    if(callback == undefined) {
        callback = function(){};
    }

    if(!geocoder) {
        /* permet de récupérer lat, lng à partir d'une adresse */
        geocoder = new GClientGeocoder();
    }

    geocoder.getLocations(address,function(response) {
        if (!response || response.Status.code != 200) {
            //alert("\"" + address + "\" not found");
        } else {

            if(map) {
                map.clearOverlays();
            }

            place = response.Placemark[0];
            lat   = place.Point.coordinates[1];
            lng   = place.Point.coordinates[0];

            var accuracy = place.AddressDetails.Accuracy;
            var tabAccuracy = new Array(2,4,6,10,13,13,16,16,17); // en fonction de la précision, défini le zoom

            point = new GLatLng(lat, lng);

            try {
                /* ville */
                if(typeof(response.Placemark[0].AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality) != "undefined") {
                    city = response.Placemark[0].AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName;

                } else if(typeof(response.Placemark[0].AddressDetails.Country.AdministrativeArea.SubAdministrativeArea) != "undefined") {
                    city = response.Placemark[0].AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.SubAdministrativeAreaName;

                } else if(typeof(response.Placemark[0].AddressDetails.Country.AdministrativeArea) != "undefined") {
                    city = response.Placemark[0].AddressDetails.Country.AdministrativeArea.AdministrativeAreaName;
                }

            } catch(err) {
                city = '';
            }

            if(map) {
                map.setCenter(point, tabAccuracy[accuracy]);

                /**************************/
                /* on rafraichit la carte */
                refreshMap(map.getCenter().lat(), map.getCenter().lng());

                /* si page d'inscription */
                if(page == 'location') {
                    /* on créé le marker */
                    createMarker(point, 'location');
                }

            /* utile pour sauvegarder la recherche si sur une page sans carte */
            } else {

                /* Requête AJAX */
                $.ajax({
                    type: 'GET',
                    processData: true,
                    url: url+'/ajaxmap/geolocation/format/html',
                    dataType: 'html',
                    data: 'zoom='+tabAccuracy[accuracy]+'&lat='+lat+'&lng='+lng+'&city='+rawurlencode(no_accent(city)),
                    success: function(html){
                        callback(html);
                    }
                });
            }
        }
    });
}

/**
 * Vérifie la validité d'une adresse email
 * @return bool
 */
function checkEmail(email){

    var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})$/;
    return filter.test(email) ;
}

String.prototype.trim = function() {
    return this.replace(/^\s+/g,'').replace(/\s+$/g,'');
}

/**
 * ajoute à l'objet tableau natif js la possiblité de vérifier si le tableau contient une valeur donnée
 * équivalent js du in_array en php
 */
Array.prototype.contains = function(value) {
    for(var i = 0, l = this.length; i < l; i++) {
        if(this[i] == value) return true;
    }
    return false;
}

/**
 * ajoute à l'objet tableau natif js la possiblité de récupérer le tableau contenant les valeurs de l'un non contenues dans l'autre (paramètre)
 * équivalent js du array_diff en php
 */
Array.prototype.diff = function(values) {
    var result = [];

    for (var i = 0, l = this.length ; i < l ; i ++) {
        if (!values.contains(this[i])) result.push(this[i]);
    }
    return result;
}

/*
 * Ecrit le fil d'arianne de l'adresse
 * @param lat float
 * @param lng float
 */
function breadCrumb(lat, lng) {

    /* on reset le breadcrumb */
    $('#breadcrumb').stop(true, true).fadeOut();
    $('#breadcrumb a, #breadcrumb span').hide();
    $('#breadcrumb #country, #breadcrumb #belt, #breadcrumb #department, #breadcrumb #city').html(' ');

    point = new GLatLng(lat, lng);

    geocoder = new GClientGeocoder(); // on le remet car bug ?!

    if (geocoder) {
        geocoder.getLocations(point,function(response) {
            if (!response || response.Status.code != 200) {
            //alert("\"" + point + "\" not found");
            } else {

                var place = response.Placemark[0];

                /* en fonction du zoom */
                zoom = map.getZoom();

                /* pays */
                if(zoom >= 5 && typeof(place.AddressDetails.Country) != "undefined") {

                    country     = place.AddressDetails.Country.CountryName;
                    countrycode = place.AddressDetails.Country.CountryNameCode;

                    $('#breadcrumb #country').html(country).show();

                    /* région */
                    if(zoom >= 7 && typeof(place.AddressDetails.Country.AdministrativeArea) != "undefined") {

                        district = place.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName;

                        $('#breadcrumb #belt').html(district).show().prev().show();

                        /* département */
                        if(zoom >= 8 && typeof(place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea) != "undefined") {

                            department = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.SubAdministrativeAreaName;

                            $('#breadcrumb #department').html(department).show().prev().show();

                            /* ville */
                            if(zoom >= 12 && typeof(place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality) != "undefined") {

                                city    = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.LocalityName;
                                
                                if(typeof(place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.PostalCode) != "undefined") {
                                    zipcode = place.AddressDetails.Country.AdministrativeArea.SubAdministrativeArea.Locality.PostalCode.PostalCodeNumber;
                                }

                                $('#breadcrumb #city').html(city).show().prev().show();

                                /* si recherche en mode place (par défaut), on met la ville à chaque page */
                                if($('#search_hidden').val() == '#'+constant["PARAM_FIND_PLACE"]) {
                                    $("#search_input").val(city);
                                }
                            }
                        }
                    }
                }
                

                /* on positionne le breadcrumb */
                var address = new GControlPosition(G_ANCHOR_BOTTOM_RIGHT, new GSize(0, 0));
                address.apply(document.getElementById("breadcrumb"));
                map.getContainer().appendChild(document.getElementById("breadcrumb"));


                /* on l'affiche */
                $('#breadcrumb').stop(true, true).fadeIn();

                $("#breadcrumb a:visible").hover(function() {
                    $(this).css({
                        'text-decoration': 'underline',
                        'cursor': 'pointer'
                    });
                },function() {
                    $(this).css({
                        'text-decoration': 'none',
                        'cursor': 'default'
                    });
                });

                $("#breadcrumb a:visible:last").hover(function() {
                    $(this).css({
                        'text-decoration': 'none',
                        'cursor': 'default'
                    });
                });

                if(page != 'mapzone') {

                    /* Requête AJAX */
                    $.ajax({
                        type: 'GET',
                        processData: true,
                        url: url+'/ajaxmap/geolocation/format/html',
                        dataType: 'html',
                        data: 'zoom='+zoom+'&lat='+lat+'&lng='+lng+'&zipcode='+zipcode+'&city='+rawurlencode(no_accent(city))+'&department='+rawurlencode(no_accent(department))+'&district='+rawurlencode(no_accent(district))+'&country='+countrycode+'&countryName='+rawurlencode(no_accent(country)),
                        success: function(html){
                        }
                    });

                }
            }

            /* si page classement d'un jeu, on recharge la partie gauche */
            if(page == 'game_ranking') {

                /* Requête AJAX */
                $.ajax({
                    type: 'GET',
                    processData: true,
                    url: url+'/game/ranking/format/html',
                    dataType: 'html',
                    data: "idgame="+game+"&mod="+mod+"&page="+pagination,
                    beforeSend: function() {
                        $('#page_part_ajax').fadeOut().html(' ');
                        $('#page_ajaxloader').show();
                    },
                    success: function(html){
                        $('#page_ajaxloader').hide();
                        $('#page_part_ajax').html(html).fadeIn();
                    }
                });

            // page home d'un jeu, on recharge les joueurs les plus proches et tournois
            } else if(page == 'game') {

                /* Requête AJAX */
                $.ajax({
                    type: 'GET',
                    processData: true,
                    url: url+'/game/usernear/format/html',
                    dataType: 'html',
                    data: "idgame="+game+"&nbmod="+nbmod,
                    beforeSend: function() {
                        $('#page_part_ajax').fadeOut().html(' ');
                        $('#page_ajaxloader').show();
                    },
                    success: function(html){
                        $('#page_ajaxloader').hide();
                        $('#page_part_ajax').html(html).fadeIn();
                    }
                });


                /* Requête AJAX */
                $.ajax({
                    type: 'GET',
                    processData: true,
                    url: url+'/game/tournamentnear/format/html',
                    dataType: 'html',
                    data: "gameId="+game,
                    beforeSend: function() {
                        $('#page_part_ajax_tn').fadeOut().html(' ');
                        $('#page_ajaxloader_tn').show();
                    },
                    success: function(html){
                        $('#page_ajaxloader_tn').hide();
                        $('#page_part_ajax_tn').html(html).fadeIn();
                    }
                });


            // page home, on recharge les tournois les plus proches
            } else if(page == 'home') {

                /* Requête AJAX */
                $.ajax({
                    type: 'GET',
                    processData: true,
                    url: url+'/index/tournamentnear/format/html',
                    dataType: 'html',
                    beforeSend: function() {
                        $('#closest_tournaments').fadeOut().html(' ');
                        $('#closest_tournaments_loader').show();
                    },
                    success: function(html){
                        $('#closest_tournaments_loader').hide();
                        $('#closest_tournaments').html(html).fadeIn();
                    }
                });

            // page map des zones, on recharge les zones les plus proches
            } else if (page == 'mapzone') {

		var ajaxdivs = $('.bottom_map .ajax');
		var zonedata;
		ajaxdivs.each( function () {
		    zonedata = $(this).attr('id').split('_');
		    loadNearestZones(zonedata[2]);
		})

            }

            /* page tournois d'un jeu, on recharge les tournois les plus proches */
            /*else if(page == 'game_tournament') {

                // Requête AJAX 
                $.ajax({
                    type: 'GET',
                    processData: true,
                    url: url+'/game/tournamentnear/format/html',
                    dataType: 'html',
                    data: "gameId="+game,
                    beforeSend: function() {
                        $('#page_part_ajax').fadeOut().html(' ');
                        $('#page_ajaxloader').show();
                    },
                    success: function(html){
                        $('#page_ajaxloader').hide();
                        $('#page_part_ajax').html(html).fadeIn();
                    }
                });

            }*/

        });
    }
}

/**
 * le slider des jeux sur la home
 */
function homeGameSlider(name) {

    $(name).jCarouselLite({
                            auto: 5000,
                            speed: 750,
                            vertical: true,
                            visible: 1
                        });

}


/**
 * Charge les zones les plus proches pour la page de map des zones
 */
function loadNearestZones(group, typeId) {

    if (typeof group == 'undefined') group = '';
    if (typeof typeId == 'undefined') typeId = 0;

    /* Requête AJAX */
    $.ajax({
	type: 'GET',
	processData: true,
	url: url + '/index/zonenear/format/html',
	dataType: 'html',
	data: 'group=' + group + '&type_id=' + typeId,
	beforeSend: function() {
	    $('#closest_zone_' + group).fadeOut().html(' ');
	    $('#' + group + '_zone_loader').show();
	},
	success: function(html){
	    $('#' + group + '_zone_loader').hide();
	    $('#closest_zone_' + group).html(html).fadeIn();
	}
    });
}


/**
 * Charge les zones d'un type en particulier
 */
function initZoneTypeSelectFilter(order) {

    $('#change_type_zone_select').change(function() {

	// on récupère le groupe et le type et on redirige
	var data = $(this).val().split('_');
	document.location.href = url+'/zone/list/' + data[0] + '/' + data[1] + '/' + order;

	return false;
    });
}

/**
 * Active le résultat du match en fonction du score d'un challenge
 **/
function validChallenge() {
        
    $(".t_score input").focus(function() {
        $(this).val('');
    });
    
    $(".t_score input").keyup(function() {
                
        var scoret1 = $('input[name=score1]').val();
        var scoret2 = $('input[name=score2]').val();
        
        $('#c_user1_result span, #c_user2_result span'). hide();

        /* Si victoire */
        if(Math.max(scoret1, scoret2) == scoret1 && scoret1 != scoret2) {
            $('#c_user1').removeClass().addClass('t_win');
            $('#c_user2').removeClass().addClass('t_loss');
            
            $('#c_user1_result .win'). show();
            $('#c_user2_result .loss'). show();
                
        /* Match nul */
        } else if (scoret1 == scoret2) {
            $('#c_user1').removeClass().addClass('t_draw');
            $('#c_user2').removeClass().addClass('t_draw');
            
            $('#c_user1_result .draw'). show();
            $('#c_user2_result .draw'). show();
            
        /* Défaite */
        } else if (Math.min(scoret1, scoret2) == scoret1 && scoret1 != scoret2) {
            $('#c_user1').removeClass().addClass('t_loss');
            $('#c_user2').removeClass().addClass('t_win');
            
            $('#c_user1_result .loss'). show();
            $('#c_user2_result .win'). show();
        }
        
    });
    
}


/*
 * Créer un tooltip
 * @param infos objet infos du membre
 */
function tooltipPlayer(infos) {

    /* Requête AJAX */
    $.ajax({
        type: 'GET',
        processData: true,
        url: url+'/member/ajax/mapclick/format/html',
        dataType: 'html',
        data: "list="+infos.list_id+"&nbmod="+nbmod,
        beforeSend: function() {

            /* on indique que la carte est en train de charger */
            $('#loader').fadeIn();

        },
        success: function(html){

            /* on affiche la zone au dessus de la map */
            $('.map').append('<p id="click_element_close"><a href="#nogo"><img src="'+img_url+'/icone/close_16.png" alt="" /></a></p><div id="click_element">'+html+'</div>');

            $('.map #click_element_close a').click(function() {

                $('#click_element').fadeOut().remove();
                $('#click_element_close').remove();
            });

            if(page == 'home') {

                if(infos.nb_user == 2) {
                    $('#click_element').children(0).css('margin-top', '80px');
                } else if(infos.nb_user == 3) {
                    $('#click_element').children(0).css('margin-top', '40px');
                } else if(infos.nb_user > 3) {
                    //nada
                } else {
                    $('#click_element').children(0).css('margin-top', '175px');
                }

            } else {

                if(infos.nb_user == 2) {
                    $('#click_element').children(0).css('margin-top', '58px');
                } else if(infos.nb_user == 3) {
                    $('#click_element').children(0).css('margin-top', '20px');
                } else if(infos.nb_user > 3) {
                    //nada
                } else {
                    $('#click_element').children(0).css('margin-top', '128px');
                }
            }


            /* on indique que la carte est en train de charger */
            $('#loader').fadeOut();
        }
    });

}



/*
 * Créer un tooltip pour une tournoi
 * @param infos objet infos du membre
 */
function tooltipTournament(infos) {

    /* Requête AJAX */
    $.ajax({
        type: 'GET',
        processData: true,
        url: url+'/tournament/ajax/mapclick/format/html',
        dataType: 'html',
        data: "list="+infos.list_id,
        beforeSend: function() {

            /* on indique que la carte est en train de charger */
            $('#loader').fadeIn();

        },
        success: function(html){

            /* on affiche la zone au dessus de la map */
            $('.map').append('<p id="click_element_close"><a href="#nogo"><img src="'+img_url+'/icone/close_16.png" alt="" /></a></p><div id="click_element">'+html+'</div>');

            $('.map #click_element_close a').click(function() {

                $('#click_element').fadeOut().remove();
                $('#click_element_close').remove();
            });

            if(page == 'home') {

                if(infos.nb_tournament == 2) {
                    $('#click_element').children(0).css('margin-top', '60px');
                } else if(infos.nb_tournament > 2) {
                    //nada
                } else {
                    $('#click_element').children(0).css('margin-top', '140px');
                }

            } else {

                if(infos.nb_tournament == 2) {
                    $('#click_element').children(0).css('margin-top', '30px');
                } else if(infos.nb_tournament > 2) {
                    //nada
                } else {
                    $('#click_element').children(0).css('margin-top', '120px');
                }
            }


            /* on indique que la carte est en train de charger */
            $('#loader').fadeOut();
        }
    });
}


/*
 * Créer un tooltip
 * @param infos objet infos de la zone
 */
function tooltipZone(infos) {

    /* Requête AJAX */
    $.ajax({
        type: 'GET',
        processData: true,
        url: url+'/zone/ajax/mapclick/format/html',
        dataType: 'html',
        data: "zoneId="+infos.id,
        beforeSend: function() {

            /* on indique que la carte est en train de charger */
            $('#loader').fadeIn();

        },
        success: function(html){

            /* on affiche la zone au dessus de la map */
            $('.map').append('<p id="click_element_close"><a href="#nogo"><img src="'+img_url+'/icone/close_16.png" alt="" /></a></p><div id="click_element">'+html+'</div>');

            $('.map #click_element_close a').click(function() {

                $('#click_element').fadeOut().remove();
                $('#click_element_close').remove();
            });

            if(page == 'home') {
                $('#click_element').children(0).css('margin-top', '175px');
                

            } else {
                $('#click_element').children(0).css('margin-top', '128px');
                
            }


            /* on indique que la carte est en train de charger */
            $('#loader').fadeOut();
        }
    });

}


/*
 * Coupe le texte si trop long
 * @param text string
 */
function cutText(text) {

    if(strlen(text) > 25) {

        text = substr(text, 0, 25)+'...';
    }

    return text;
}

function addSocialNetworksShareButtons(){

    var defaultUrlToShare = window.location;

    //Facebook
    var zFb = $('.zFbShare');
    if(zFb.length > 0) {

        zFb.each(function(index, el){
            
            var element = $(el);

            // détermination de l'url à partager
            var urlToShare = defaultUrlToShare;
            if( element.attr('share_url') != null ) { // si on demande une url personnalisée
                urlToShare  = element.attr('share_url');
                element.removeAttr('share_url');
            }

            // création du lien-bouton
            var fbButton = document.createElement('a');
            fbButton.setAttribute('name', 'fb_share');
            fbButton.setAttribute('share_url', urlToShare);
            fbButton.setAttribute('type', 'icon_link');
            fbButton.innerHTML = '&nbsp;';

            element.append(fbButton);

            // si dernier bouton Fb de la page, on ajoute le script Fb
            if(index == (zFb.length -1) ) {

                var fbScript = document.createElement('script');
                fbScript.setAttribute('src', 'http://static.ak.fbcdn.net/connect.php/js/FB.Share');
                fbScript.setAttribute('type', 'text/javascript');

                element.append(fbScript);
            }
        });
    }

    //Twitter
    var zTw = $('.zTwShare');
    if(zTw.length > 0) {

        zTw.each(function(index, el){

            var element = $(el);

            // détermination de l'url à partager
            var urlToShare = defaultUrlToShare;
            if( element.attr('share_url') != null ) { // si on demande une url personnalisée
                urlToShare  = element.attr('share_url');
                element.removeAttr('share_url');
            }

            // détermination du texte à partager
            var txtToShare = '';
            if( element.attr('share_txt') != null ) { // si on demande une url personnalisée
                txtToShare  = encodeURIComponent(element.attr('share_txt'));
                element.removeAttr('share_txt');
            }

            var twButton = document.createElement('a');
            twButton.setAttribute('target', '_blank');
            twButton.setAttribute('href', 'http://twitter.com/share?url='+urlToShare+'&via=gamersband&text='+txtToShare );
            twButton.innerHTML = '&nbsp;';

            element.append(twButton);
        });
    }
}

function zoneCreateproInvitation() {
    
    $('#fbLink').click(function(){
        $('.zFbShare a').click();
    });

    $('#twLink').click(function(){
        var href = $('.zTwShare a').attr('href') ;
        window.open(href);
    });
}

/**
 * ouvre la modale permettant de proposer un challenge à un joueur
 */
function openChallengePopup(gameId, platformCode, userId) {

    var alreadyPrompt = ($('.jqimessage').length == 1);

    $.ajax({
        type: 'GET',
        processData: true,
        url: url+'/member/ajax/playopen/format/html',
        dataType: 'html',
        data: 'user='+userId+"&platform="+platformCode+"&game="+gameId,
        beforeSend:function()
        {
            var html = $('#zAjaxLoading').parent().html();

            if(alreadyPrompt) {
                $('.jqimessage').html(html);
            }
            else {
                $.prompt(html, {
                    buttons: {}
                });
            }
        },
        success: function(html){
            $('.jqimessage').html(html);
        }
    });
}

/* Onglet compétition */
function initOpenChallengePopup() {

    $('.competition_challenge_popup').click(function(){

        var data = $(this).attr('href');
        data     = explode('_', data);

        openChallengePopup(data[2], data[1], data[3]);
    });
}

/**
 * Js dédié aux news du système de post
 */
function initPostNews() {
    
    $('#post_listcomment .reply').click(function() {
                
        var id = $(this).attr('href');
        id     = explode('_', id);
        
        var form = $('#postcomment_'+id[1]+' .form_reply').html();
        
        if(form != ' ' && form != '') {             
            $('#postcomment_'+id[1]+' .form_reply').html(' ');
            
        } else {
        
            form = $('#post_addcomment').clone();

            form.find('input[name=comment_id]').val(id[1]);
            form.find('input[type=submit]').val($(this).html());

            form.appendTo('#postcomment_'+id[1]+' .form_reply');            
        }
        
    });
    
    $('#post_listcomment .delete').click(function() {
        
        var id  = $(this).attr('href');
        id      = explode('_', id);
        
        /* Requête AJAX */
        $.ajax({
            type: 'GET',
            processData: true,
            url: url+'/post/news/deletecom/format/html',
            dataType: 'html',
            data: 'comment='+id[1]+'&post='+id[2],
            success: function(html){
        
                $('#postcomment_'+id[1]).fadeOut();
            }
        });
        
    });
}

/*******************/
/* fonction utiles */
function substr (str, start, len) {
    str += '';
    var end = str.length;
    if (start < 0) {
        start += end;
    }
    end = typeof len === 'undefined' ? end : (len < 0 ? len + end : len + start);
    return start >= str.length || start < 0 || start > end ? !1 : str.slice(start, end);
}

function explode (delimiter, string, limit) {
    var emptyArray = {
        0: ''
    };

    // third argument is not required
    if ( arguments.length < 2 ||
        typeof arguments[0] == 'undefined' ||
        typeof arguments[1] == 'undefined' ) {
        return null;
    }

    if ( delimiter === '' ||
        delimiter === false ||
        delimiter === null ) {
        return false;
    }

    if ( typeof delimiter == 'function' ||
        typeof delimiter == 'object' ||
        typeof string == 'function' ||
        typeof string == 'object' ) {
        return emptyArray;
    }

    if ( delimiter === true ) {
        delimiter = '1';
    }

    if (!limit) {
        return string.toString().split(delimiter.toString());
    } else {
        // support for limit argument
        var splitted = string.toString().split(delimiter.toString());
        var partA = splitted.splice(0, limit - 1);
        var partB = splitted.join(delimiter.toString());
        partA.push(partB);
        return partA;
    }
}

function rand(min, max) {
    // *     example 1: rand(1, 1);
    // *     returns 1: 1
    var argc = arguments.length;
    if (argc === 0) {
        min = 0;
        max = 2147483647;
    } else if (argc === 1) {
        throw new Error('Warning: rand() expects exactly 2 parameters, 1 given');
    }
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

function strlen (string) {

    var str = string+'';
    var i = 0, chr = '', lgth = 0;

    if (!this.php_js || !this.php_js.ini || !this.php_js.ini['unicode.semantics'] ||
        this.php_js.ini['unicode.semantics'].local_value.toLowerCase() !== 'on') {
        return string.length;
    }

    var getWholeChar = function (str, i) {
        var code = str.charCodeAt(i);
        var next = '', prev = '';
        if (0xD800 <= code && code <= 0xDBFF) { // High surrogate (could change last hex to 0xDB7F to treat high private surrogates as single characters)
            if (str.length <= (i+1))  {
                throw 'High surrogate without following low surrogate';
            }
            next = str.charCodeAt(i+1);
            if (0xDC00 > next || next > 0xDFFF) {
                throw 'High surrogate without following low surrogate';
            }
            return str.charAt(i)+str.charAt(i+1);
        } else if (0xDC00 <= code && code <= 0xDFFF) { // Low surrogate
            if (i === 0) {
                throw 'Low surrogate without preceding high surrogate';
            }
            prev = str.charCodeAt(i-1);
            if (0xD800 > prev || prev > 0xDBFF) { //(could change last hex to 0xDB7F to treat high private surrogates as single characters)
                throw 'Low surrogate without preceding high surrogate';
            }
            return false; // We can pass over low surrogates now as the second component in a pair which we have already processed
        }
        return str.charAt(i);
    };

    for (i=0, lgth=0; i < str.length; i++) {
        if ((chr = getWholeChar(str, i)) === false) {
            continue;
        } // Adapt this line at the top of any loop, passing in the whole string and the current iteration and returning a variable to represent the individual character; purpose is to treat the first part of a surrogate pair as the whole character and then ignore the second part
        lgth++;
    }
    return lgth;
}

function str_replace (search, replace, subject, count) {
    // *     example 1: str_replace(' ', '.', 'Kevin van Zonneveld');

    var i = 0, j = 0, temp = '', repl = '', sl = 0, fl = 0,
            f = [].concat(search),
            r = [].concat(replace),
            s = subject,
            ra = r instanceof Array, sa = s instanceof Array;
    s = [].concat(s);
    if (count) {
        this.window[count] = 0;
    }

    for (i=0, sl=s.length; i < sl; i++) {
        if (s[i] === '') {
            continue;
        }
        for (j=0, fl=f.length; j < fl; j++) {
            temp = s[i]+'';
            repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
            s[i] = (temp).split(f[j]).join(repl);
            if (count && s[i] !== temp) {
                this.window[count] += (temp.length-s[i].length)/f[j].length;}
        }
    }
    return sa ? s : s[0];
}


/*
 * Permet de récupérer un élément dans un xml par son id
 */
function getElementByIdMXL(the_node,the_id) {
    //get all the tags in the doc
    node_tags = the_node.getElementsByTagName('*');
    for (i=0;i<node_tags.length;i++) {

        //is there an id attribute
        if (node_tags[i].getAttribute('id') != undefined) {
            if (node_tags[i].hasAttribute('id')) {

                //if there is, test its value
                if (node_tags[i].getAttribute('id') == the_id) {

                    //and return it if it matches
                    return node_tags[i];
                }
            }
        }
    }
}


/*
 * block la touche entrée
 */
function blockEnter(event)
{
    // Compatibilité IE / Firefox
    if(!event && window.event) {
        event = window.event;
    }
    // IE
    if(event.keyCode == 13) {
        event.returnValue = false;
        event.cancelBubble = true;
    }
    // DOM
    if(event.which == 13) {
        event.preventDefault();
        event.stopPropagation();
    }
}

// script by Josh Fraser (http://www.onlineaspect.com)

function calculate_time_zone() {
    var rightNow = new Date();
    var jan1 = new Date(rightNow.getFullYear(), 0, 1, 0, 0, 0, 0);  // jan 1st
    var june1 = new Date(rightNow.getFullYear(), 6, 1, 0, 0, 0, 0); // june 1st
    var temp = jan1.toGMTString();
    var jan2 = new Date(temp.substring(0, temp.lastIndexOf(" ")-1));
    temp = june1.toGMTString();
    var june2 = new Date(temp.substring(0, temp.lastIndexOf(" ")-1));
    var std_time_offset = (jan1 - jan2) / (1000 * 60 * 60);
    var daylight_time_offset = (june1 - june2) / (1000 * 60 * 60);
    var dst;
    if (std_time_offset == daylight_time_offset) {
        dst = "0"; // daylight savings time is NOT observed
    } else {
        // positive is southern, negative is northern hemisphere
        var hemisphere = std_time_offset - daylight_time_offset;
        if (hemisphere >= 0)
            std_time_offset = daylight_time_offset;
        dst = "1"; // daylight savings time is observed
    }

    return convert_time_zone(std_time_offset)+","+dst;

    var i;
    // check just to avoid error messages
    if (document.getElementById('timezone')) {
        for (i = 0; i < document.getElementById('timezone').options.length; i++) {
            if (document.getElementById('timezone').options[i].value == convert_time_zone(std_time_offset)+","+dst) {
                document.getElementById('timezone').selectedIndex = i;
                break;
            }
        }
    }
}

function convert_time_zone(value) {
    var hours = parseInt(value);
    value -= parseInt(value);
    value *= 60;
    var mins = parseInt(value);
    value -= parseInt(value);
    value *= 60;
    var secs = parseInt(value);
    var display_hours = hours;
    // handle GMT case (00:00)
    if (hours == 0) {
        display_hours = "00";
    } else if (hours > 0) {
        // add a plus sign and perhaps an extra 0
        display_hours = (hours < 10) ? "+0"+hours : "+"+hours;
    } else {
        // add an extra 0 if needed
        display_hours = (hours > -10) ? "-0"+Math.abs(hours) : hours;
    }

    mins = (mins < 10) ? "0"+mins : mins;
    return display_hours+":"+mins;
}

function rawurlencode (str) {
    str = (str+'').toString();
    // Tilde should be allowed unescaped in future versions of PHP (as reflected below), but if you want to reflect current
    // PHP behavior, you would need to add ".replace(/~/g, '%7E');" to the following.
    return encodeURIComponent(str).replace(/ /g, '%20').replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').
                                                                    replace(/\)/g, '%29').replace(/\*/g, '%2A');
}

function no_accent (my_string) {
    var new_string = "";
    var pattern_accent = new Array("é", "è", "ê", "ë", "ç", "à", "â", "ä", "î", "ï", "ù", "ô", "ó", "ö");
    var pattern_replace_accent = new Array("e", "e", "e", "e", "c", "a", "a", "a", "i", "i", "u", "o", "o", "o");
    if (my_string && my_string!= "") {
            new_string = preg_replace (pattern_accent, pattern_replace_accent, my_string);
    }
    return new_string;
}

function preg_replace (array_pattern, array_pattern_replace, my_string)  {
    var new_string = String (my_string);
    for (i=0; i<array_pattern.length; i++) {
            var reg_exp= RegExp(array_pattern[i], "gi");
            var val_to_replace = array_pattern_replace[i];
            new_string = new_string.replace (reg_exp, val_to_replace);
    }
    return new_string;
}



/*************************/
/* UTILISATEURS EN LIGNE */
/*************************/

/**
 * envoie la requête de récupération des utilisateurs en ligne
 *
 * @param string page page concernée
 * @param string data paramètres de la requête
 */
function retrieveOnlineUsers(page, data) {

    socket.send('onlineUsers#' + data + ';');
    
}

/**
 * traite les utilisateurs en ligne récupérés
 *
 * @param array users tableau brut des utilisateurs connectés
 * @param string data paramètres de la requête
 */
function handleOnlineUsers(users, data) {

    var userids = [];
    var lng	= users.length;
    var i	= 0;

    for (i = 0 ; i < lng ; i ++) {
	if (users[i].connected && users[i].id != _userid) userids.push(users[i].id);
    }

    if (userids.length > 0) {

	$.ajax({
	    type: 'GET',
	    processData: true,
	    url: url + '/' + page + '/useronline/format/html',
	    dataType: 'html',
	    data: data + '&userids=' + userids.join('_'),
	    beforeSend: function() {
		$('#ajax_online_users').fadeOut().html(' ');
		$('#page_ajaxloader_online_users').show();
	    },
	    success: function(html){
		$('#page_ajaxloader_online_users').hide();
		$('#ajax_online_users').html(html).fadeIn();
	    }
	});

    } else {
	$('#page_ajaxloader_online_users').hide();
	//$('#ajax_online_users').html("<p class='info_message'>" + translate['no_players_to_display'] + "</p>").fadeIn();
    }

}

/**
 * envoie la requête de vérification des utilisateurs en ligne
 *
 * @param array links ensemble des lines des utilisateurs à vérifier
 */
function checkOnlineUsers(links) {

    var ids = new Array();

    $(links).each(function() {
	$(this).click( function() {return false;});
	ids.push($(this).attr('id'));
    });

    socket.send('askPing#' + ids.join('_') + '#page;');

}

/**
 * active les "pastilles" de l'utilisateur
 *
 * @param array userid identifiant de l'utilisateur
 * @param boolean chatroom indique si l'on est sur une page chatroom
 */
function handlePageOnlineMember(userid, chatroom) {

    chatroom = chatroom || false;

    if ($('.user_chat[href="#nogo_user_' + userid + '"]').is('a')) {

	$('.user_chat[href="#nogo_user_' + userid + '"]:not(.online)').each( function() {
	    $(this).addClass('online');
	    if (!chatroom && parseInt(retrieveChatCookieData('gb_chat_offline')) == 0) {
		$(this).click( function() {
		    handleDirectChatLink(this, 'user_chat');
		    return false;
		});
	    }
	});

    }
}

/**
 * désactive les "pastilles" de l'utilisateur
 *
 * @param array userid identifiant de l'utilisateur
 */
function handlePageOfflineMember(userid) {

    if ($('.user_chat[href="#nogo_user_' + userid + '"]').is('a')) {

	$('.user_chat[href="#nogo_user_' + userid + '"].online').each( function() {
	    $(this).removeClass('online').unbind('click');
	});

    }
}



/***************/
/* NEWSFEEDS   */
/***************/
function initDashboardNewsfeedMember(nbNews) {

    //action sur le bouton de submit
    $('#userStatusForm').submit(function(){

        onsubmitNfStatus(nbNews);
        return false;
    });

    loadAdminNewsfeed(nbNews);
}

function initAdminNewsfeedMember() {

    window.gb_newsfeed_page = 1 ;

    //chargement des news en ajax
    loadAdminNewsfeed();

    //action sur le bouton de submit
    $('#userStatusForm').submit(function(){

        onsubmitNfStatus();
        return false;
    });

    //action sur la demande de news en plus
    $('#button').click(function(){

        window.gb_newsfeed_page++ ;
        loadAdminNewsfeed();
    });
}


function initAdminNewsfeedTeam(teamId) {

    window.gb_newsfeed_page = 1 ;

    //chargement des news en ajax
    loadAdminNewsfeedEntity(undefined, teamId, 'team');

    //action sur le bouton de submit
    $('#userStatusForm').submit(function(){

        onsubmitNfStatusEntity(undefined, teamId, 'team');
        return false;
    });

    //action sur la demande de news en plus
    $('#button').click(function(){

        window.gb_newsfeed_page++ ;
        loadAdminNewsfeedEntity(undefined, teamId, 'team');
    });
}


function initAdminNewsfeedZone(zoneId) {

    window.gb_newsfeed_page = 1 ;

    //chargement des news en ajax
    loadAdminNewsfeedEntity(undefined, zoneId, 'zone');

    //action sur le bouton de submit
    $('#userStatusForm').submit(function(){

        onsubmitNfStatusEntity(undefined, zoneId, 'zone');
        return false;
    });

    //action sur la demande de news en plus
    $('#button').click(function(){

        window.gb_newsfeed_page++ ;
        loadAdminNewsfeedEntity(undefined, zoneId, 'zone');
    });
}

/**
 * charge les news admin
 */
function loadAdminNewsfeed(nbNews){

    var filter = $('#filter').val();
    var dataStr = 'page='+window.gb_newsfeed_page+'&filter='+filter;
    if(nbNews != undefined) dataStr += '&nbNews='+nbNews;

    $.ajax({
        type: 'GET',
        processData: true,
        url: url+'/newsfeed/ajax/getuseradminnews/format/html',
        dataType: 'html',
        data: dataStr,
        beforeSend: function(){
            $('#nf_loader').show();
            $('#status').attr('disabled', 'disabled');
        },
        success: function(data){

            if(data != '') {

                var jqNewsList = $('#zNewsList');

                //la premiere fois
                if(jqNewsList.hasClass('empty')){

                    var ul = document.createElement('ul');
                    ul.setAttribute('id', 'newsList');
                    ul.setAttribute('class', 'nf_template_full');
                    jqNewsList.prepend(ul);

                    $('#zNewsList ul').html(data);
                    
                    jqNewsList.removeClass('empty');
                }
                //si on demande plus
                else{
                    $('#zNewsList ul').append(data);

                    //si plus de news, on masque le bouton
                    if(data == '') $('#button').hide();
                }

                //on masque le loader
                $('#nf_loader').hide();

                //on active le bouton more
                $('#moreBtActive').val(1);

                //action de partage via facebook ou twitter
                $('.shareFb, .shareTw').click(function(){

                    onClickNfShare(this);
                });

                //on réactive la zone de statut
                $('#status').removeAttr('disabled');

                //bug ie7 (motherfucker !)
                document.getElementById('zNewsList').innerHTML += '';

            }
            else {

                //on réactive la zone de statut
                $('#status').removeAttr('disabled');

                if(window.gb_newsfeed_page == 1){
                    $('#nonew_p').show();
                }

                $('#nf_loader').hide();
                $('#button').hide();
            }
        }
    });
}

/**
 * charge les news admin team...
 */
function loadAdminNewsfeedEntity(nbNews, id, type){

    var filter = $('#filter').val();
    var dataStr = 'page='+window.gb_newsfeed_page+'&filter='+filter+'&id='+id;
    if(nbNews != undefined) dataStr += '&nbNews='+nbNews;

    $.ajax({
        type: 'GET',
        processData: true,
        url: url+'/newsfeed/ajax/get'+type+'adminnews/format/html',
        dataType: 'html',
        data: dataStr,
        beforeSend: function(){
            $('#nf_loader').show();
            $('#status').attr('disabled', 'disabled');
        },
        success: function(data){

            if(data != '') {

                var jqNewsList = $('#zNewsList');

                //la premiere fois
                if(jqNewsList.hasClass('empty')){

                    var ul = document.createElement('ul');
                    ul.setAttribute('id', 'newsList');
                    ul.setAttribute('class', 'nf_template_full');
                    jqNewsList.prepend(ul);

                    $('#zNewsList ul').html(data);

                    jqNewsList.removeClass('empty');
                }
                //si on demande plus
                else{
                    $('#zNewsList ul').append(data);

                    //si plus de news, on masque le bouton
                    if(data == '') $('#button').hide();
                }

                //on masque le loader
                $('#nf_loader').hide();

                //on active le bouton more
                $('#moreBtActive').val(1);

                //action de partage via facebook ou twitter
                $('.shareFb, .shareTw').click(function(){

                    onClickNfShare(this);
                });

                //on réactive la zone de statut
                $('#status').removeAttr('disabled');

                //bug ie7 (motherfucker !)
                document.getElementById('zNewsList').innerHTML += '';

            }
            else {

                //on réactive la zone de statut
                $('#status').removeAttr('disabled');

                if(window.gb_newsfeed_page == 1){
                    $('#nonew_p').show();
                }

                $('#nf_loader').hide();
                $('#button').hide();
            }
        }
    });
}

function onClickNfShare(link) {

    //calcul des paramètres
    var params = link.id.split('_');
    var img = $(link).parent().parent().children('.nf_action').children('img');




    //envoi de le requête ajax
    $.ajax({
        type: 'GET',
        processData: true,
        url: url+'/newsfeed/ajax/networkshare',
        dataType: 'html',
        data: 'type='+params[1]+'&id='+params[2],
        beforeSend:function(html){

            $(img).show();
        },
        success: function(html){

            var oldSrc = $(img).attr('src').split('/');
            oldSrc[oldSrc.length -1] = 'valid_green_24.png';

            $(img).attr('src', oldSrc.join('/') );

            //alert(html);
        }
    });
}

function onsubmitNfStatus(nbNews) {

    //on effectue la requête Ajax que si la première page est chargée
    if($('#moreBtActive').val() == 1 ) {

        //valeur du statut
        var statusValue = $('#status').val();

        if(statusValue != '' && statusValue.length <= 340) {

            //on ajoute le statut
            $.ajax({
                type: 'GET',
                processData: true,
                url: url+'/newsfeed/ajax/publish',
                dataType: 'html',
                data: 'status='+statusValue,
                beforeSend:function(html){

                    $('#status, #submit').attr('disabled', 'disabled');
                    $('#callback').html('<img src="'+url+'/public/images/icone/loading.gif" alt="loader" width="26" />');
                },
                success: function(html){

                    $('#zNewsList').addClass('empty').html('<img id="nf_loader" src="'+url+'/public/images/icone/loading.gif" alt="loader" />');

                    window.gb_newsfeed_page = 1 ;
                    loadAdminNewsfeed(nbNews);

                    $('#status').removeAttr('disabled').val('');
                    $('#submit').removeAttr('disabled');
                }
            });
        }

    }

    return false;
}

function onsubmitNfStatusEntity(nbNews, id, type) {

    //on effectue la requête Ajax que si la première page est chargée
    if($('#moreBtActive').val() == 1 ) {

        //valeur du statut
        var statusValue = $('#status').val();

        if(statusValue != '' && statusValue.length <= 340) {

            //on ajoute le statut
            $.ajax({
                type: 'GET',
                processData: true,
                url: url+'/newsfeed/ajax/publish',
                dataType: 'html',
                data: 'status='+statusValue+"&id="+id+"&type="+type,
                beforeSend:function(html){

                    $('#status, #submit').attr('disabled', 'disabled');
                    $('#callback').html('<img src="'+url+'/public/images/icone/loading.gif" alt="loader" width="26" />');
                },
                success: function(html){

                    $('#zNewsList').addClass('empty').html('<img id="nf_loader" src="'+url+'/public/images/icone/loading.gif" alt="loader" />');

                    window.gb_newsfeed_page = 1 ;
                    loadAdminNewsfeedEntity(nbNews, id, type);

                    $('#status').removeAttr('disabled').val('');
                    $('#submit').removeAttr('disabled');
                }
            });
        }

    }

    return false;
}


/**
 * description des variables globales :
 *
 * - window.gb_newsfeed_currentPage     : la page courante
 * - window.gb_newsfeed_maxPage         : la page max déjà accédée
 * - window.gb_newsfeed_finalMaxPage    : la page max qu'il est possible d'accéder
 */
function initPublicNewsfeedMember() {

    window.gb_newsfeed_maxPage = window.gb_newsfeed_currentPage =  1 ;
    window.gb_newsfeed_finalMaxPage = 99999999;

    $('#newsfeedP1').show();
    
    $('#nf_pagin_previous').css('visibility', 'hidden');
    $('#nf_pagin_next').css('visibility', 'hidden');
    $('.nf_pagin_public_wrapper img').css('visibility', 'hidden');

    /*
    $('#nf_pagin_previous').click(function(){

        if(window.gb_newsfeed_currentPage > 1) {

            $('#newsfeedP'+(window.gb_newsfeed_currentPage)).fadeOut(500, function(){

                $('#newsfeedP'+(window.gb_newsfeed_currentPage-1)).fadeIn(500, function(){

                    window.gb_newsfeed_currentPage--;

                    if(window.gb_newsfeed_currentPage > 1) 
                        $('#nf_pagin_previous').css('visibility', 'visible');
                    else
                        $('#nf_pagin_previous').css('visibility', 'hidden');
                    $('#nf_pagin_next').css('visibility', 'visible');
                });
            });
        }
    });

    $('#nf_pagin_next').click(function(){

        //si on n'est pas sur la dernière page
        if(window.gb_newsfeed_currentPage < window.gb_newsfeed_maxPage ) {

            $('#newsfeedP'+(window.gb_newsfeed_currentPage)).fadeOut(500, function(){

                $('#newsfeedP'+(window.gb_newsfeed_currentPage+1)).fadeIn(500, function(){

                    window.gb_newsfeed_currentPage++;

                    $('#nf_pagin_previous').css('visibility', 'visible');

                    if(window.gb_newsfeed_currentPage == window.gb_newsfeed_finalMaxPage)
                        $('#nf_pagin_next').css('visibility', 'hidden');
                    else
                        $('#nf_pagin_next').css('visibility', 'visible');
                });
            });

        }
        //si on est sur la dernière page, on va en chercher une nouvelle en ajax
        else {

            //on n'effectue l'action que si le max n'a pas été trouvé et que celui-ci soit égal à la page courante
            if(window.gb_newsfeed_currentPage < window.gb_newsfeed_finalMaxPage ) {

                //on va chercher sur le serveur une nouvelle page
                $.ajax({
                    type: 'GET',
                    processData: true,
                    url: url+'/newsfeed/ajax/getuserpublicnews/format/html',
                    dataType: 'html',
                    data: 'page='+ (window.gb_newsfeed_currentPage+1) +'&userId='+$('#userId').val(),
                    beforeSend: function(){

                        $('.nf_pagin_public_wrapper img').css('visibility', 'visible');
                    },
                    success: function(data){

                        //si encore des news
                        if(data!='') {

                            $('#newsfeedP'+(window.gb_newsfeed_currentPage )).fadeOut(500, function(){

                                $('#newsListWrapper').append(data);
                                $('#newsfeedP'+(window.gb_newsfeed_currentPage+1)).show();//fadeIn(500);

                                window.gb_newsfeed_currentPage++;
                                window.gb_newsfeed_maxPage++ ;

                                $('#nf_pagin_previous').css('visibility', 'visible');
                                $('#nf_pagin_next').css('visibility', 'visible');
                            });
                        }
                        //si plus de news
                        else {
                            window.gb_newsfeed_finalMaxPage = window.gb_newsfeed_maxPage

                            if(window.gb_newsfeed_currentPage > 1) $('#nf_pagin_previous').css('visibility', 'visible');
                            $('#nf_pagin_next').css('visibility', 'hidden');
                        }

                        $('.nf_pagin_public_wrapper img').css('visibility', 'hidden');
                    }
                });
            }
        }
    });*/
}

/**
 * description des variables globales :
 *
 * @param type string type de l'entité (zone, team...)
 * - window.gb_newsfeed_currentPage     : la page courante
 * - window.gb_newsfeed_maxPage         : la page max déjà accédée
 * - window.gb_newsfeed_finalMaxPage    : la page max qu'il est possible d'accéder
 */
function initPublicNewsfeedEntity(type) {

    window.gb_newsfeed_maxPage = window.gb_newsfeed_currentPage =  1 ;
    window.gb_newsfeed_finalMaxPage = 99999999;

    $('#newsfeedP1').show();

    $('#nf_pagin_previous').css('visibility', 'hidden');
    $('#nf_pagin_next').css('visibility', 'hidden');
    $('.nf_pagin_public_wrapper img').css('visibility', 'hidden');

    /*
    $('#nf_pagin_previous').click(function(){

        if(window.gb_newsfeed_currentPage > 1) {

            $('#newsfeedP'+(window.gb_newsfeed_currentPage)).fadeOut(500, function(){

                $('#newsfeedP'+(window.gb_newsfeed_currentPage-1)).fadeIn(500, function(){

                    window.gb_newsfeed_currentPage--;

                    if(window.gb_newsfeed_currentPage > 1)
                        $('#nf_pagin_previous').css('visibility', 'visible');
                    else
                        $('#nf_pagin_previous').css('visibility', 'hidden');
                    $('#nf_pagin_next').css('visibility', 'visible');
                });
            });
        }
    });

    $('#nf_pagin_next').click(function(){

        //si on n'est pas sur la dernière page
        if(window.gb_newsfeed_currentPage < window.gb_newsfeed_maxPage ) {

            $('#newsfeedP'+(window.gb_newsfeed_currentPage)).fadeOut(500, function(){

                $('#newsfeedP'+(window.gb_newsfeed_currentPage+1)).fadeIn(500, function(){

                    window.gb_newsfeed_currentPage++;

                    $('#nf_pagin_previous').css('visibility', 'visible');

                    if(window.gb_newsfeed_currentPage == window.gb_newsfeed_finalMaxPage)
                        $('#nf_pagin_next').css('visibility', 'hidden');
                    else
                        $('#nf_pagin_next').css('visibility', 'visible');
                });
            });

        }
        //si on est sur la dernière page, on va en chercher une nouvelle en ajax
        else {

            //on n'effectue l'action que si le max n'a pas été trouvé et que celui-ci soit égal à la page courante
            if(window.gb_newsfeed_currentPage < window.gb_newsfeed_finalMaxPage ) {

                //on va chercher sur le serveur une nouvelle page
                $.ajax({
                    type: 'GET',
                    processData: true,
                    url: url+'/newsfeed/ajax/get'+type+'publicnews/format/html',
                    dataType: 'html',
                    data: 'page='+ (window.gb_newsfeed_currentPage+1) +'&'+type+'Id='+$('#entityId').val(),
                    beforeSend: function(){

                        $('.nf_pagin_public_wrapper img').css('visibility', 'visible');
                    },
                    success: function(data){

                        //si encore des news
                        if(data!='') {

                            $('#newsfeedP'+(window.gb_newsfeed_currentPage )).fadeOut(500, function(){

                                $('#newsListWrapper').append(data);
                                $('#newsfeedP'+(window.gb_newsfeed_currentPage+1)).show();//fadeIn(500);

                                window.gb_newsfeed_currentPage++;
                                window.gb_newsfeed_maxPage++ ;

                                $('#nf_pagin_previous').css('visibility', 'visible');
                                $('#nf_pagin_next').css('visibility', 'visible');
                            });
                        }
                        //si plus de news
                        else {
                            window.gb_newsfeed_finalMaxPage = window.gb_newsfeed_maxPage

                            if(window.gb_newsfeed_currentPage > 1) $('#nf_pagin_previous').css('visibility', 'visible');
                            $('#nf_pagin_next').css('visibility', 'hidden');
                        }

                        $('.nf_pagin_public_wrapper img').css('visibility', 'hidden');
                    }
                });
            }
        }
    });
     */
}

/********************/
/* membre
/*******************/

/**
 * page d'accueil du profil public
 */
function memberPublicIndex(userId) {
    checkUsersOnlineStatus( [userId], showOnlineStatusForUsers);
}

/**
 * page 'mes amis' du dashboard membre
 */
function memberAdminFriends(friendsIds) {
    checkUsersOnlineStatus(friendsIds, showOnlineStatusForUsers);
}

/**
 * callback pour afficher la présence des amis sur la page admin du dashboard
 */
function showOnlineStatusForUsers(response) {

console.log(response);

    // pour chaque utilisateur de la page
    $.each(response.steam, function(userId, userData) {

        if(userData.onlineState != 0) {
            $('.online_status.user_'+userId).show();
        }
    });
}

/**
 * vérifie la présence online
 */
function checkUsersOnlineStatus(usersIds, callback ) {

    var dataStr = 'userId[]='+usersIds.join('&userId[]=');

    $.ajax({
        type: 'POST',
        processData: true,
        url: url+'/member/ajax/checkOnlineStatus',
        dataType: 'json',
        data: dataStr,
        success: function(response) {
            callback(response);
        }
    });
}

/************************************/
/* MANIPULATION DES DONNEES LOCALES */
/************************************/

// retourne la chaine de caractères du cookie contenant l'information souhaitée ou -1 si elle n'a pas été trouvée
function retrieveLocalData(key) {

    var cookies = document.cookie.split(';');

    for (var i = 0, n = cookies.length ; i < n ; i ++) {
	var cookie = cookies[i];
	while (cookie.charAt(0) == ' ') cookie = cookie.substring(1, cookie.length);
	if (cookie.indexOf(key + '=') == 0) return cookie.substring((key + '=').length, cookie.length);
    }

    return -1;
}

// retourne la chaine de caractères du cookie contenant l'information souhaitée, sous forme de tableau
function retrieveLocalDataAsArray(key) {

    var str = retrieveLocalData(key);

    return str != 0 && str != -1 ? str.split('_') : [];
}

// donne à la clé spécifiée du cookie la valeur fournie
function storeLocalData(key, data) {

    document.cookie = key.toString() + '=' + data.toString() + '; path=/; domain=' + cookie_domain;
}

// ajoute une valeur à une donnée de cookie de type tableau
function pushLocalDataArray(key, data, unique) {

    if (typeof unique == 'undefined') unique = false;

    var arr = retrieveLocalDataAsArray(key);

    // si la valeur ne doit être présent une seule fois max
    if (unique) {
	if (!arr.contains(data)) arr.push(data);
    } else {
	arr.push(data);
    }

    storeLocalData(key, arr.join('_'));
}

// supprime le cookie spécifié
function destroyLocalData(key) {

    // spécifier une date d'expiration déjà passée fait que le navigateur supprime le cookie tout seul comme un grand
    document.cookie = key.toString() + '=0; expires=Mon, 1 Mar 2010 00:00:00 UTC; path=/; domain=' + cookie_domain;
}

/***************/
/* FORUM       */
/***************/

function initForum(page) {

    //changement css au survol d'éléments
    $('.f_adminaction li').hover(
       function(){ //mouseover
           $(this).addClass('hover');
       },
       function(){ //mouseout
           $(this).removeClass('hover');
       }
    );

    //changement css au survol d'éléments
    $('#f_surf li').hover(
       function(){ //mouseover
           $(this).addClass('hover');
       },
       function(){ //mouseout
           $(this).removeClass('hover');
       }
    );

    //action au clic sur le bouton de réponse à un topic
    $('#answerTopicBt').click(function() {

        $('#title_add').show();
        $('#title_edit').hide();

        $('#postId').val('');
        var url = $('#urlForm').val();
        $('#formPost').attr('action', url);
        $('#formPost textarea').val('');

        window.location.href = '#topicContent';
        $('#topicContent').focus();
    });

    //action au clic sur le bouton de réponse à un topic
    $('.f_post .editPostLink a').click(function(){

        $('#title_add').hide();
        $('#title_edit').show();

        var postId = this.className.substr(1);
        $('#postId').val(postId);
        var url = $('#urlForm').val();
        
        $('#formPost').attr('action', url+'/'+postId);
        $('#formPost textarea').val( $('#pc'+postId).html() );
    });

    //en fonction de la page, on masque certains liens qui ne servent pas à grand chose
    switch(page) {

        case 'section':
            $('.f_section_detail a').hide();
            break;

        case 'topic':
            $('.f_section_detail a').hide();
            $('.f_topic_footer').hide();
            break;

        case 'topicform':
            $('.f_section_detail a').hide();
            break;
    }
}

/****************/
/* PANIER ACHAT */
/****************/
function initCart(product) {
 
    /* supprime une image de la galerie */
    $('input[name=product]').unbind().click(function() {

        var product = $(this).val();
        var promo   = $('input[name=code_promo]').val();

        /* Requête AJAX */
        $.ajax({
            type: 'GET',
            processData: true,
            url: url+'/pro/payment/cart/format/html',
            dataType: 'html',
            data: 'product='+product+'&promo='+promo,
            success: function(html){
                $('#zone_cart').html(html);
            }
        });

    });

    /* supprime une image de la galerie */
    $('input[name=code_promo]').keyup(function() {

        var product = $('input[name=product]:checked').val();
        var promo   = $(this).val();

        if(promo.length > 3) {

            /* Requête AJAX */
            $.ajax({
                type: 'GET',
                processData: true,
                url: url+'/pro/payment/cart/format/html',
                dataType: 'html',
                data: 'product='+product+'&promo='+promo,
                success: function(html){
                    $('#zone_cart').html(html);

                    $('input[name=code_promo]').focus();
                }
            });
        }        

    });
    

    if(product == 'zone') {

        $('.table_zonepro_price').click(function() {

            $('.table_zonepro_price').removeClass('selected');
            $(this).addClass('selected');

            var type = $(this).attr('href');
            type     = substr(type, 1);

            $('.zonepro_cart').hide();

            $('#cart').hide();
            $('#target_btnvalid2').hide();
            $('#target_btnvalid').show();

            $('input[name=product]').removeAttr('checked');

            $('#zonepro_'+type).show();
        });
    }

}

/****************/
/*   ZONE       */
/****************/



/**
 * Charge les zones d'un type en particulier
 */
function initLinkElement(id, typeElement) {
    
    $(id).find(typeElement).click(function() {                
        document.location.href = $(this).attr('class');
        
    }).hover(function() {  
        $(this).css('cursor', 'pointer');
        
    }, function() {         
        $(this).css('cursor', 'default');
        
    });
    
}


function initZoneAdminOperation() {

    /* Recherche une zone ou un tournoi par nom */
    $('#find_operation').keyup(function() {

        /* selon le type de recherche, utilisation de la carte ou non */
        var name   = $(this).val();

        var type    = $('#find_operation_type').val();
        var zoneUrl = $('#zone_url').val();

        if(name != '' && name.length > 2) {

            /* Requête AJAX */
            $.ajax({
                type: 'GET',
                processData: true,
                url: url+'/zone/admin/findoperation/format/html',
                dataType: 'html',
                data: 'name='+name+'&type='+type+'&zoneUrl='+zoneUrl,
                success: function(html){

                    $('#find_operation_list').html(html).show();
                }
            });

        } else {
            $('#find_operation_list').hide();
        }

        return false;
    });


    /* Recherche une zone ou un tournoi par nom */
    $('#find_operation_list a').live('click', function() {

        var type    = $('#find_operation_type').val();
        var id      = $(this).attr('href');
        id          = explode('_', id);
        var name    = $(this).find('strong').html();

        $('input[name='+type+'_id]').val(id[1]);
        $('input[name=name]').val(name);

        $('#find_operation_list').html(' ').hide();

        return false;
    });
}

function initZoneAdminAds() {

    /* sélectionne un contenu pour une campagne de pub */
    $('.list_ads_content .select a').click(function() {

        $('.list_ads_content').find('.current').addClass('hide');
        $('.list_ads_content').find('.select').removeClass('hide');
        $(this).parent().addClass('hide');
        $(this).parent().next().removeClass('hide');

        var id = $(this).attr('href');
        id = substr(id, 9);

        $('input[name=content_id]').val(id);

        return false;
    });
}

function initZoneAdminDeal() {

    /* Changement de coupon dans son form de création */
    $('input[name=dealtype]').change(function() {

        var type = $(this).val();

        if(type == 1) {
            $('#dealtype_2').hide();
            $('#dealtype_1').show();

        } else {
            $('#dealtype_1').hide();
            $('#dealtype_2').show();
        }
    });
}



/*********************/
/* autocomplete user */
function initAutoCompleteUser(type) {

    $('#add_user').keyup(function(){

        var user = $(this).val();

        if(window.gb_autocompleteusertimeout != undefined) {
            window.clearTimeout(window.gb_autocompleteusertimeout);
            delete window.gb_autocompleteusertimeout;
        }

        if(user.length > 2) {
            window.gb_autocompleteusertimeout = setTimeout(searchAutocompleteUser(type), 250);
        }
        else if(user.length == 0) {
            $('#zone_autocomplete_user').slideUp();
        }
    });

    function searchAutocompleteUser(type) {

        var search = $('#add_user').val();

        if(search.length > 2) {
            $.ajax({
                type: 'GET',
                processData: true,
                url: url+'/member/ajax/autocompletename/format/html',
                dataType: 'html',
                data: 'name='+search+'&type='+type,
                beforeSend: function() {
                    $('#add_user').addClass('autocomplete_loading');
                },
                success: function(html){

                    if(html == '') {
                        $('#zone_autocomplete_user').slideUp();
                    }
                    else {
                        $('#zone_autocomplete_user').html(html).show();
                    }
                },
                complete: function() {
                    $('#add_user').removeClass('autocomplete_loading');
                }
            });
        }       

    }
}

function autocompleteUserAddTournamentCompetitor() {

    $('.autocompleteuser_action_t-addcompetitor').click(function(){

        var userId  = $(this).attr('href');
        userId      = explode('_', userId);

        var tournamentId = $('#add_user_tnid').val();

        $.ajax({
                type: 'GET',
                processData: true,
                url: url+'/tournament/ajax/addcompetitor/format/html',
                dataType: 'html',
                data: 'userId='+userId[1]+'&tournamentId='+tournamentId,
                beforeSend: function() {
                    $('#add_user').addClass('autocomplete_loading');
                },
                success: function(html){

                    $('#unconfirmedList').append(html);
                    $('#confirmedCompetitorsForm').show();
                    $('#unconfirmedList_empty').hide();
                    
                    $('#zone_autocomplete_user').slideUp();
                },
                complete: function() {
                    $('#add_user').removeClass('autocomplete_loading');
                }
            });

    });
}

function autocompleteUserAddTournamentAdmin() {

    $('.autocompleteuser_action_t-addadmin').click(function(){

        var userId  = $(this).attr('href');
        userId      = explode('_', userId);

        var tournamentId = $('#add_user_tnid').val();

        $.ajax({
                type: 'GET',
                processData: true,
                url: url+'/tournament/ajax/addadminrights/format/html',
                dataType: 'html',
                data: 'userId='+userId[1]+'&tournamentId='+tournamentId,
                beforeSend: function() {
                    $('#add_user').addClass('autocomplete_loading');
                },
                success: function(html){

                    // suppression du aucun admin si besoin
                    var children = $('#t_listadminValid li').length;
                    if(children == 0) {
                         $('#t_listadminValid').next().remove();
                    }

                    $('#t_listadminValid').append(html);
                    $('#zone_autocomplete_user').slideUp();
                },
                complete: function() {
                    $('#add_user').removeClass('autocomplete_loading');
                }
            });

    });
}

/***************/
/* LES PLUGINS */
/***************/

function callAlert(msg) {

    return window.alert(msg);
}

function callConfirm(msg) {

    return window.confirm(msg);
}

/*
 * jQuery Pluguin Impromptu
 * By: Trent Richardson [http://trentrichardson.com]
 * Version 2.8
 * Last Modified: 12/18/2009
 *
 */
(function($){$.prompt=function(message,options){options=$.extend({},$.prompt.defaults,options);$.prompt.currentPrefix=options.prefix;var ie6=($.browser.msie&&$.browser.version<7);var $body=$(document.body);var $window=$(window);var msgbox='<div class="'+options.prefix+'box" id="'+options.prefix+'box">';if(options.useiframe&&(($('object, applet').length>0)||ie6)){msgbox+='<iframe src="javascript:false;" style="display:block;position:absolute;z-index:-1;" class="'+options.prefix+'fade" id="'+options.prefix+'fade"></iframe>';}else{if(ie6){$('select').css('visibility','hidden');}msgbox+='<div class="'+options.prefix+'fade" id="'+options.prefix+'fade"></div>';}msgbox+='<div class="'+options.prefix+'" id="'+options.prefix+'"><div class="'+options.prefix+'top"><div class="';msgbox+=options.prefix+'close">'+translate["close"]+' <img src="'+img_url+'/icone/close_16.png" alt="" /></div></div><div class="'+options.prefix+'container"><div id="'+options.prefix+'states"></div>';msgbox+='</div></div></div>';var $jqib=$(msgbox).appendTo($body);var $jqi=$jqib.children('#'+options.prefix);var $jqif=$jqib.children('#'+options.prefix+'fade');if(message.constructor==String){message={state0:{html:message,buttons:options.buttons,focus:options.focus,submit:options.submit}};}var states="";$.each(message,function(statename,stateobj){stateobj=$.extend({},$.prompt.defaults.state,stateobj);message[statename]=stateobj;states+='<div id="'+options.prefix+'_state_'+statename+'" class="'+options.prefix+'_state" style="display:none;"><div class="'+options.prefix+'message">'+stateobj.html+'</div><div class="'+options.prefix+'buttons">';$.each(stateobj.buttons,function(k,v){states+='<button name="'+options.prefix+'_'+statename+'_button'+k+'" id="'+options.prefix+'_'+statename+'_button'+k+'" value="'+v+'">'+k+'</button>';});states+='</div></div>';});$jqi.find('#'+options.prefix+'states').html(states).children('.'+options.prefix+'_state:first').css('display','block');$jqi.find('.'+options.prefix+'buttons:empty').css('display','none');$.each(message,function(statename,stateobj){var $state=$jqi.find('#'+options.prefix+'_state_'+statename);$state.children('.'+options.prefix+'buttons').children('button').click(function(){var msg=$state.children('.'+options.prefix+'message');var clicked=stateobj.buttons[$(this).text()];var forminputs={};$.each($jqi.find('#'+options.prefix+'states :input').serializeArray(),function(i,obj){if(forminputs[obj.name]===undefined){forminputs[obj.name]=obj.value;}else if(typeof forminputs[obj.name]==Array||typeof forminputs[obj.name]=='object'){forminputs[obj.name].push(obj.value);}else{forminputs[obj.name]=[forminputs[obj.name],obj.value];}});var close=stateobj.submit(clicked,msg,forminputs);if(close===undefined||close){removePrompt(true,clicked,msg,forminputs);}});$state.find('.'+options.prefix+'buttons button:eq('+stateobj.focus+')').addClass(options.prefix+'defaultbutton');});var ie6scroll=function(){$jqib.css({top:$window.scrollTop()});};var fadeClicked=function(){if(options.persistent){var i=0;$jqib.addClass(options.prefix+'warning');var intervalid=setInterval(function(){$jqib.toggleClass(options.prefix+'warning');if(i++>1){clearInterval(intervalid);$jqib.removeClass(options.prefix+'warning');}},100);}else{removePrompt();}};var keyPressEventHandler=function(e){var key=(window.event)?event.keyCode:e.keyCode;if(key==27){fadeClicked();}if(key==9){var $inputels=$(':input:enabled:visible',$jqib);var fwd=!e.shiftKey&&e.target==$inputels[$inputels.length-1];var back=e.shiftKey&&e.target==$inputels[0];if(fwd||back){setTimeout(function(){if(!$inputels)return;var el=$inputels[back===true?$inputels.length-1:0];if(el)el.focus();},10);return false;}}};var positionPrompt=function(){$jqib.css({position:(ie6)?"absolute":"fixed",height:$window.height(),width:"100%",top:(ie6)?$window.scrollTop():0,left:0,right:0,bottom:0});$jqif.css({position:"absolute",height:$window.height(),width:"100%",top:0,left:0,right:0,bottom:0});$jqi.css({position:"absolute",top:options.top,left:"50%",marginLeft:(($jqi.outerWidth()/2)*-1)});};var stylePrompt=function(){$jqif.css({zIndex:options.zIndex,display:"none",opacity:options.opacity});$jqi.css({zIndex:options.zIndex+1,display:"none"});$jqib.css({zIndex:options.zIndex});};var removePrompt=function(callCallback,clicked,msg,formvals){$jqi.remove();if(ie6){$body.unbind('scroll',ie6scroll);}$window.unbind('resize',positionPrompt);$jqif.fadeOut(options.overlayspeed,function(){$jqif.unbind('click',fadeClicked);$jqif.remove();if(callCallback){options.callback(clicked,msg,formvals);}$jqib.unbind('keypress',keyPressEventHandler);$jqib.remove();if(ie6&&!options.useiframe){$('select').css('visibility','visible');}});};positionPrompt();stylePrompt();if(ie6){$window.scroll(ie6scroll);}$jqif.click(fadeClicked);$window.resize(positionPrompt);$jqib.bind("keydown keypress",keyPressEventHandler);$jqi.find('.'+options.prefix+'close').click(removePrompt);$jqif.fadeIn(options.overlayspeed);$jqi[options.show](options.promptspeed,options.loaded);$jqi.find('#'+options.prefix+'states .'+options.prefix+'_state:first .'+options.prefix+'defaultbutton').focus();if(options.timeout>0)setTimeout($.prompt.close,options.timeout);return $jqib;};$.prompt.defaults={prefix:'jqi',buttons:{Ok:true},loaded:function(){},submit:function(){return true;},callback:function(){},opacity:0.6,zIndex:999,overlayspeed:'slow',promptspeed:'fast',show:'fadeIn',focus:0,useiframe:false,top:"100px",persistent:true,timeout:0,state:{html:'',buttons:{Ok:true},focus:0,submit:function(){return true;}}};$.prompt.currentPrefix=$.prompt.defaults.prefix;$.prompt.setDefaults=function(o){$.prompt.defaults=$.extend({},$.prompt.defaults,o);};$.prompt.setStateDefaults=function(o){$.prompt.defaults.state=$.extend({},$.prompt.defaults.state,o);};$.prompt.getStateContent=function(state){return $('#'+$.prompt.currentPrefix+'_state_'+state);};$.prompt.getCurrentState=function(){return $('.'+$.prompt.currentPrefix+'_state:visible');};$.prompt.getCurrentStateName=function(){var stateid=$.prompt.getCurrentState().attr('id');return stateid.replace($.prompt.currentPrefix+'_state_','');};$.prompt.goToState=function(state){$('.'+$.prompt.currentPrefix+'_state').slideUp('slow');$('#'+$.prompt.currentPrefix+'_state_'+state).slideDown('slow',function(){$(this).find('.'+$.prompt.currentPrefix+'defaultbutton').focus();});};$.prompt.nextState=function(){var $next=$('.'+$.prompt.currentPrefix+'_state:visible').next();$('.'+$.prompt.currentPrefix+'_state').slideUp('slow');$next.slideDown('slow',function(){$next.find('.'+$.prompt.currentPrefix+'defaultbutton').focus();});};$.prompt.prevState=function(){var $next=$('.'+$.prompt.currentPrefix+'_state:visible').prev();$('.'+$.prompt.currentPrefix+'_state').slideUp('slow');$next.slideDown('slow',function(){$next.find('.'+$.prompt.currentPrefix+'defaultbutton').focus();});};$.prompt.close=function(){$('#'+$.prompt.currentPrefix+'box').fadeOut('fast',function(){$(this).remove();});};})(jQuery);


/*
 * jquery limit pour textarea
 */
(function($){$.fn.extend({limit:function(limit,element){var interval,f;var self=$(this);$(this).focus(function(){interval=window.setInterval(substring,100)});$(this).blur(function(){clearInterval(interval);substring()});substringFunction="function substring(){ var val = $(self).val();var length = val.length;if(length > limit){$(self).val($(self).val().substring(0,limit));}";if(typeof element!='undefined')substringFunction+="if($(element).html() != limit-length){$(element).html((limit-length<=0)?'0':limit-length);}";substringFunction+="}";eval(substringFunction);substring()}})})(jQuery);


/**
 * jquery.simpletip 1.3.1. A simple tooltip plugin
 *
 */
(function($){function Simpletip(elem,conf){var self=this;elem=jQuery(elem);var tooltip=jQuery(document.createElement('div')).addClass(conf.baseClass).addClass((conf.fixed)?conf.fixedClass:'').addClass((conf.persistent)?conf.persistentClass:'').html(conf.content).appendTo(elem);if(!conf.hidden)tooltip.show();else tooltip.hide();if(!conf.persistent){elem.hover(function(event){self.show(event)},function(){self.hide()});if(!conf.fixed){elem.mousemove(function(event){if(tooltip.css('display')!=='none')self.updatePos(event);});};}else
{elem.click(function(event){if(event.target===elem.get(0)){if(tooltip.css('display')!=='none')self.hide();else
self.show();};});jQuery(window).mousedown(function(event){if(tooltip.css('display')!=='none'){var check=(conf.focus)?jQuery(event.target).parents('.tooltip').andSelf().filter(function(){return this===tooltip.get(0)}).length:0;if(check===0)self.hide();};});};jQuery.extend(self,{getVersion:function(){return[1,2,0];},getParent:function(){return elem;},getTooltip:function(){return tooltip;},getPos:function(){return tooltip.offset();},setPos:function(posX,posY){var elemPos=elem.offset();if(typeof posX=='string')posX=parseInt(posX)+elemPos.left;if(typeof posY=='string')posY=parseInt(posY)+elemPos.top;tooltip.css({left:posX,top:posY});return self;},show:function(event){conf.onBeforeShow.call(self);self.updatePos((conf.fixed)?null:event);switch(conf.showEffect){case'fade':tooltip.fadeIn(conf.showTime);break;case'slide':tooltip.slideDown(conf.showTime,self.updatePos);break;case'custom':conf.showCustom.call(tooltip,conf.showTime);break;default:case'none':tooltip.show();break;};tooltip.addClass(conf.activeClass);conf.onShow.call(self);return self;},hide:function(){conf.onBeforeHide.call(self);switch(conf.hideEffect){case'fade':tooltip.fadeOut(conf.hideTime);break;case'slide':tooltip.slideUp(conf.hideTime);break;case'custom':conf.hideCustom.call(tooltip,conf.hideTime);break;default:case'none':tooltip.hide();break;};tooltip.removeClass(conf.activeClass);conf.onHide.call(self);return self;},update:function(content){tooltip.html(content);conf.content=content;return self;},load:function(uri,data){conf.beforeContentLoad.call(self);tooltip.load(uri,data,function(){conf.onContentLoad.call(self);});return self;},boundryCheck:function(posX,posY){var newX=posX+tooltip.outerWidth();var newY=posY+tooltip.outerHeight();var windowWidth=jQuery(window).width()+jQuery(window).scrollLeft();var windowHeight=jQuery(window).height()+jQuery(window).scrollTop();return[(newX>=windowWidth),(newY>=windowHeight)];},updatePos:function(event){var tooltipWidth=tooltip.outerWidth();var tooltipHeight=tooltip.outerHeight();if(!event&&conf.fixed){if(conf.position.constructor==Array){posX=parseInt(conf.position[0]);posY=parseInt(conf.position[1]);}else if(jQuery(conf.position).attr('nodeType')===1){var offset=jQuery(conf.position).offset();posX=offset.left;posY=offset.top;}else
{var elemPos=elem.offset();var elemWidth=elem.outerWidth();var elemHeight=elem.outerHeight();switch(conf.position){case'top':var posX=elemPos.left-(tooltipWidth/2)+(elemWidth/2);var posY=elemPos.top-tooltipHeight;break;case'bottom':var posX=elemPos.left-(tooltipWidth/2)+(elemWidth/2);var posY=elemPos.top+elemHeight;break;case'left':var posX=elemPos.left-tooltipWidth;var posY=elemPos.top-(tooltipHeight/2)+(elemHeight/2);break;case'right':var posX=elemPos.left+elemWidth;var posY=elemPos.top-(tooltipHeight/2)+(elemHeight/2);break;default:case'default':var posX=(elemWidth/2)+elemPos.left+20;var posY=elemPos.top;break;};};}else
{var posX=event.pageX;var posY=event.pageY;};if(typeof conf.position!='object'){posX=posX+conf.offset[0];posY=posY+conf.offset[1];if(conf.boundryCheck){var overflow=self.boundryCheck(posX,posY);if(overflow[0])posX=posX-(tooltipWidth/2)-(2*conf.offset[0]);if(overflow[1])posY=posY-(tooltipHeight/2)-(2*conf.offset[1]);}}else
{if(typeof conf.position[0]=="string")posX=String(posX);if(typeof conf.position[1]=="string")posY=String(posY);};self.setPos(posX,posY);return self;}});};jQuery.fn.simpletip=function(conf){var api=jQuery(this).eq(typeof conf=='number'?conf:0).data("simpletip");if(api)return api;var defaultConf={content:'A simple tooltip',persistent:false,focus:false,hidden:true,position:'default',offset:[0,0],boundryCheck:true,fixed:true,showEffect:'fade',showTime:150,showCustom:null,hideEffect:'fade',hideTime:150,hideCustom:null,baseClass:'tooltip',activeClass:'active',fixedClass:'fixed',persistentClass:'persistent',focusClass:'focus',onBeforeShow:function(){},onShow:function(){},onBeforeHide:function(){},onHide:function(){},beforeContentLoad:function(){},onContentLoad:function(){}};jQuery.extend(defaultConf,conf);this.each(function(){var el=new Simpletip(jQuery(this),defaultConf);jQuery(this).data("simpletip",el);});return this;};})();

/**
 * jquery scrollTo
 * @author Ariel Flesler
 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
 */
(function(d){var k=d.scrollTo=function(a,i,e){d(window).scrollTo(a,i,e)};k.defaults={axis:'xy',duration:parseFloat(d.fn.jquery)>=1.3?0:1};k.window=function(a){return d(window)._scrollable()};d.fn._scrollable=function(){return this.map(function(){var a=this,i=!a.nodeName||d.inArray(a.nodeName.toLowerCase(),['iframe','#document','html','body'])!=-1;if(!i)return a;var e=(a.contentWindow||a).document||a.ownerDocument||a;return d.browser.safari||e.compatMode=='BackCompat'?e.body:e.documentElement})};d.fn.scrollTo=function(n,j,b){if(typeof j=='object'){b=j;j=0}if(typeof b=='function')b={onAfter:b};if(n=='max')n=9e9;b=d.extend({},k.defaults,b);j=j||b.speed||b.duration;b.queue=b.queue&&b.axis.length>1;if(b.queue)j/=2;b.offset=p(b.offset);b.over=p(b.over);return this._scrollable().each(function(){var q=this,r=d(q),f=n,s,g={},u=r.is('html,body');switch(typeof f){case'number':case'string':if(/^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(f)){f=p(f);break}f=d(f,this);case'object':if(f.is||f.style)s=(f=d(f)).offset()}d.each(b.axis.split(''),function(a,i){var e=i=='x'?'Left':'Top',h=e.toLowerCase(),c='scroll'+e,l=q[c],m=k.max(q,i);if(s){g[c]=s[h]+(u?0:l-r.offset()[h]);if(b.margin){g[c]-=parseInt(f.css('margin'+e))||0;g[c]-=parseInt(f.css('border'+e+'Width'))||0}g[c]+=b.offset[h]||0;if(b.over[h])g[c]+=f[i=='x'?'width':'height']()*b.over[h]}else{var o=f[h];g[c]=o.slice&&o.slice(-1)=='%'?parseFloat(o)/100*m:o}if(/^\d+$/.test(g[c]))g[c]=g[c]<=0?0:Math.min(g[c],m);if(!a&&b.queue){if(l!=g[c])t(b.onAfterFirst);delete g[c]}});t(b.onAfter);function t(a){r.animate(g,j,b.easing,a&&function(){a.call(this,n,b)})}}).end()};k.max=function(a,i){var e=i=='x'?'Width':'Height',h='scroll'+e;if(!d(a).is('html,body'))return a[h]-d(a)[e.toLowerCase()]();var c='client'+e,l=a.ownerDocument.documentElement,m=a.ownerDocument.body;return Math.max(l[h],m[h])-Math.min(l[c],m[c])};function p(a){return typeof a=='object'?a:{top:a,left:a}}})(jQuery);

/*
    Slimbox v2.04 - The ultimate lightweight Lightbox clone for jQuery
    (c) 2007-2010 Christophe Beyls <http://www.digitalia.be>
*/
(function(w){var E=w(window),u,f,F=-1,n,x,D,v,y,L,r,m=!window.XMLHttpRequest,s=[],l=document.documentElement,k={},t=new Image(),J=new Image(),H,a,g,p,I,d,G,c,A,K;w(function(){w("body").append(w([H=w('<div id="lbOverlay" />')[0],a=w('<div id="lbCenter" />')[0],G=w('<div id="lbBottomContainer" />')[0]]).css("display","none"));g=w('<div id="lbImage" />').appendTo(a).append(p=w('<div style="position: relative;" />').append([I=w('<a id="lbPrevLink" href="#" />').click(B)[0],d=w('<a id="lbNextLink" href="#" />').click(e)[0]])[0])[0];c=w('<div id="lbBottom" />').appendTo(G).append([w('<a id="lbCloseLink" href="#" />').add(H).click(C)[0],A=w('<div id="lbCaption" />')[0],K=w('<div id="lbNumber" />')[0],w('<div style="clear: both;" />')[0]])[0]});w.slimbox=function(O,N,M){u=w.extend({loop:false,overlayOpacity:0.8,overlayFadeDuration:400,resizeDuration:400,resizeEasing:"swing",initialWidth:250,initialHeight:250,imageFadeDuration:400,captionAnimationDuration:400,counterText:"Image {x} of {y}",closeKeys:[27,88,67],previousKeys:[37,80],nextKeys:[39,78]},M);if(typeof O=="string"){O=[[O,N]];N=0}y=E.scrollTop()+(E.height()/2);L=u.initialWidth;r=u.initialHeight;w(a).css({top:Math.max(0,y-(r/2)),width:L,height:r,marginLeft:-L/2}).show();v=m||(H.currentStyle&&(H.currentStyle.position!="fixed"));if(v){H.style.position="absolute"}w(H).css("opacity",u.overlayOpacity).fadeIn(u.overlayFadeDuration);z();j(1);f=O;u.loop=u.loop&&(f.length>1);return b(N)};w.fn.slimbox=function(M,P,O){P=P||function(Q){return[Q.href,Q.title]};O=O||function(){return true};var N=this;return N.unbind("click").click(function(){var S=this,U=0,T,Q=0,R;T=w.grep(N,function(W,V){return O.call(S,W,V)});for(R=T.length;Q<R;++Q){if(T[Q]==S){U=Q}T[Q]=P(T[Q],Q)}return w.slimbox(T,U,M)})};function z(){var N=E.scrollLeft(),M=E.width();w([a,G]).css("left",N+(M/2));if(v){w(H).css({left:N,top:E.scrollTop(),width:M,height:E.height()})}}function j(M){if(M){w("object").add(m?"select":"embed").each(function(O,P){s[O]=[P,P.style.visibility];P.style.visibility="hidden"})}else{w.each(s,function(O,P){P[0].style.visibility=P[1]});s=[]}var N=M?"bind":"unbind";E[N]("scroll resize",z);w(document)[N]("keydown",o)}function o(O){var N=O.keyCode,M=w.inArray;return(M(N,u.closeKeys)>=0)?C():(M(N,u.nextKeys)>=0)?e():(M(N,u.previousKeys)>=0)?B():false}function B(){return b(x)}function e(){return b(D)}function b(M){if(M>=0){F=M;n=f[F][0];x=(F||(u.loop?f.length:0))-1;D=((F+1)%f.length)||(u.loop?0:-1);q();a.className="lbLoading";k=new Image();k.onload=i;k.src=n}return false}function i(){a.className="";w(g).css({backgroundImage:"url("+n+")",visibility:"hidden",display:""});w(p).width(k.width);w([p,I,d]).height(k.height);w(A).html(f[F][1]||"");w(K).html((((f.length>1)&&u.counterText)||"").replace(/{x}/,F+1).replace(/{y}/,f.length));if(x>=0){t.src=f[x][0]}if(D>=0){J.src=f[D][0]}L=g.offsetWidth;r=g.offsetHeight;var M=Math.max(0,y-(r/2));if(a.offsetHeight!=r){w(a).animate({height:r,top:M},u.resizeDuration,u.resizeEasing)}if(a.offsetWidth!=L){w(a).animate({width:L,marginLeft:-L/2},u.resizeDuration,u.resizeEasing)}w(a).queue(function(){w(G).css({width:L,top:M+r,marginLeft:-L/2,visibility:"hidden",display:""});w(g).css({display:"none",visibility:"",opacity:""}).fadeIn(u.imageFadeDuration,h)})}function h(){if(x>=0){w(I).show()}if(D>=0){w(d).show()}w(c).css("marginTop",-c.offsetHeight).animate({marginTop:0},u.captionAnimationDuration);G.style.visibility=""}function q(){k.onload=null;k.src=t.src=J.src=n;w([a,g,c]).stop(true);w([I,d,g,G]).hide()}function C(){if(F>=0){q();F=x=D=-1;w(a).hide();w(H).stop().fadeOut(u.overlayFadeDuration,j)}return false}})(jQuery);

// AUTOLOAD CODE BLOCK (MAY BE CHANGED OR REMOVED)
if (!/android|iphone|ipod|series60|symbian|windows ce|blackberry/i.test(navigator.userAgent)) {
	jQuery(function($) {
		$("a[rel^='lightbox']").slimbox({counterText: false, overlayOpacity: 0.6}, null, function(el) {
			return (this == el) || ((this.rel.length > 8) && (this.rel == el.rel));
		});
	});
}


/*
 * CrossSlide jQuery plugin v0.6.2
 *
 * Copyright 2007-2010 by Tobia Conforto <tobia.conforto@gmail.com>
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation; either version 2 of the License, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc., 51
 * Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 */
(function(){var d=jQuery,a=(d.fn.startAnimation?"startAnimation":"animate"),c="pause plugin missing.";function e(h){for(var g=1;g<arguments.length;g++){h=h.replace(new RegExp("\\{"+(g-1)+"}","g"),arguments[g])}return h}function f(){arguments[0]="CrossSlide: "+arguments[0];throw new Error(e.apply(null,arguments))}function b(i){var g=1;var h=i.replace(/^\s*|\s*$/g,"").split(/\s+/);if(h.length>3){throw new Error()}if(h[0]=="center"){if(h.length==1){h=["center","center"]}else{if(h.length==2&&h[1].match(/^[\d.]+x$/i)){h=["center","center",h[1]]}}}if(h.length==3){g=parseFloat(h[2].match(/^([\d.]+)x$/i)[1])}var j=h[0]+" "+h[1];if(j=="left top"||j=="top left"){return{xrel:0,yrel:0,zoom:g}}if(j=="left center"||j=="center left"){return{xrel:0,yrel:0.5,zoom:g}}if(j=="left bottom"||j=="bottom left"){return{xrel:0,yrel:1,zoom:g}}if(j=="center top"||j=="top center"){return{xrel:0.5,yrel:0,zoom:g}}if(j=="center center"){return{xrel:0.5,yrel:0.5,zoom:g}}if(j=="center bottom"||j=="bottom center"){return{xrel:0.5,yrel:1,zoom:g}}if(j=="right top"||j=="top right"){return{xrel:1,yrel:0,zoom:g}}if(j=="right center"||j=="center right"){return{xrel:1,yrel:0.5,zoom:g}}if(j=="right bottom"||j=="bottom right"){return{xrel:1,yrel:1,zoom:g}}return{xrel:parseInt(h[0].match(/^(\d+)%$/)[1])/100,yrel:parseInt(h[1].match(/^(\d+)%$/)[1])/100,zoom:g}}d.fn.crossSlide=function(i,k,l){var g=this,j=this.width(),h=this.height();if(g.length!=1){f("crossSlide() must be called on exactly 1 element")}g.get(0).crossSlideArgs=[i,k,l];k=d.map(k,function(m){return d.extend({},m)});if(!i.easing){i.easing=i.variant?"swing":"linear"}if(!l){l=function(){}}(function(o){var m=0;function n(q,p){p.onload=function(r){m++;k[q].width=p.width;k[q].height=p.height;if(m==k.length){o()}};p.src=k[q].src;if(q+1<k.length){n(q+1,new Image())}}n(0,new Image())})(function(){if(!i.fade){f("missing fade parameter.")}if(i.speed&&i.sleep){f("you cannot set both speed and sleep at the same time.")}var A=Math.round(i.fade*1000);if(i.sleep){var z=Math.round(i.sleep*1000)}if(i.speed){var o=i.speed/1000,v=Math.round(A*o)}g.empty().css({overflow:"hidden",padding:0});if(!/^(absolute|relative|fixed)$/.test(g.css("position"))){g.css({position:"relative"})}if(!g.width()||!g.height()){f("container element does not have its own width and height")}if(i.shuffle){k.sort(function(){return Math.random()-0.5})}for(var t=0;t<k.length;++t){var m=k[t];if(!m.src){f("missing src parameter in picture {0}.",t+1)}if(o){switch(m.dir){case"up":m.from={xrel:0.5,yrel:0,zoom:1};m.to={xrel:0.5,yrel:1,zoom:1};var x=m.height-h-2*v;break;case"down":m.from={xrel:0.5,yrel:1,zoom:1};m.to={xrel:0.5,yrel:0,zoom:1};var x=m.height-h-2*v;break;case"left":m.from={xrel:0,yrel:0.5,zoom:1};m.to={xrel:1,yrel:0.5,zoom:1};var x=m.width-j-2*v;break;case"right":m.from={xrel:1,yrel:0.5,zoom:1};m.to={xrel:0,yrel:0.5,zoom:1};var x=m.width-j-2*v;break;default:f("missing or malformed dir parameter in picture {0}.",t+1)}if(x<=0){f("impossible animation: either picture {0} is too small or div is too large or fade duration too long.",t+1)}m.time_ms=Math.round(x/o)}else{if(!z){if(!m.from||!m.to||!m.time){f("missing either speed/sleep option, or from/to/time params in picture {0}.",t+1)}try{m.from=b(m.from)}catch(w){f('malformed "from" parameter in picture {0}.',t+1)}try{m.to=b(m.to)}catch(w){f('malformed "to" parameter in picture {0}.',t+1)}if(!m.time){f('missing "time" parameter in picture {0}.',t+1)}m.time_ms=Math.round(m.time*1000)}}if(m.from){d.each([m.from,m.to],function(p,C){C.width=Math.round(m.width*C.zoom);C.height=Math.round(m.height*C.zoom);C.left=Math.round((j-C.width)*C.xrel);C.top=Math.round((h-C.height)*C.yrel)})}var s,y;y=s=d(e('<img src="{0}"/>',m.src));if(m.href){y=d(e('<a href="{0}"></a>',m.href)).append(s)}if(m.onclick){y.click(m.onclick)}if(m.alt){s.attr("alt",m.alt)}if(m.rel){y.attr("rel",m.rel)}if(m.href&&m.target){y.attr("target",m.target)}y.appendTo(g)}delete o;function n(D,C){var E=[0,A/(D.time_ms+2*A),1-A/(D.time_ms+2*A),1][C];return{left:Math.round(D.from.left+E*(D.to.left-D.from.left)),top:Math.round(D.from.top+E*(D.to.top-D.from.top)),width:Math.round(D.from.width+E*(D.to.width-D.from.width)),height:Math.round(D.from.height+E*(D.to.height-D.from.height))}}var u=g.find("img").css({position:"absolute",visibility:"hidden",top:0,left:0,border:0});u.eq(0).css({visibility:"visible"});if(!z){u.eq(0).css(n(k[0],i.variant?0:1))}var B=i.loop;function q(O,p){if(O%2==0){if(z){var E=O/2,S=(E-1+k.length)%k.length,P=u.eq(E),M=u.eq(S);var L=function(){l(E,P.get(0));M.css("visibility","hidden");setTimeout(p,z)}}else{var H=O/2,S=(H-1+k.length)%k.length,R=u.eq(H),M=u.eq(S),F=k[H].time_ms,N=n(k[H],i.variant?3:2);var L=function(){l(H,R.get(0));M.css("visibility","hidden");R[a](N,F,i.easing,p)}}}else{var D=Math.floor(O/2),G=Math.ceil(O/2)%k.length,Q=u.eq(D),C=u.eq(G),T={},K={visibility:"visible"},J={};if(G>D){K.opacity=0;J.opacity=1;if(i.doubleFade){T.opacity=0}}else{T.opacity=0;if(i.doubleFade){K.opacity=0;J.opacity=1}}if(!z){d.extend(K,n(k[G],0));if(!i.variant){d.extend(T,n(k[D],3));d.extend(J,n(k[G],1))}}if(d.isEmptyObject(J)){var L=function(){l(G,C.get(0),D,Q.get(0));C.css(K);Q[a](T,A,"linear",p)}}else{if(d.isEmptyObject(T)){var L=function(){l(G,C.get(0),D,Q.get(0));C.css(K);C[a](J,A,"linear",p)}}else{var L=function(){l(G,C.get(0),D,Q.get(0));C.css(K);C[a](J,A,"linear");Q[a](T,A,"linear",p)}}}}if(i.loop&&O==k.length*2-2){var I=L;L=function(){if(--B){I()}}}if(O>0){return q(O-1,L)}else{return L}}var r=q(k.length*2-1,function(){return r()});r()});return g};d.fn.crossSlideFreeze=function(){this.find("img").stop()};d.fn.crossSlideStop=function(){this.find("img").stop().remove()};d.fn.crossSlideRestart=function(){this.find("img").stop().remove();d.fn.crossSlide.apply(this,this.get(0).crossSlideArgs)};d.fn.crossSlidePause=function(){if(!d.fn.pause){f(c)}this.find("img").pause()};d.fn.crossSlideResume=function(){if(!d.fn.pause){f(c)}this.find("img").resume()}})();


/**
 * prend le dernier event handler de l'événement spécifié et le place en tête
 *
 * @param string event l'évenement pour lequel changer l'ordre des handlers
 */
(function($) {
    $.fn.lastToFirstEventHandler = function(eventName) {  
        
        var elementDom = this[0],
        elementData = jQuery.data(elementDom),
        events = (elementData.events ? elementData.events : elementData.__events__),
        handlers = events[eventName];

        // s'il n'y a qu'un seul handler, on quitte
        if (handlers.length == 1) return;

        // Insert last handler at first index.
        handlers.splice(0, 0, handlers.pop());
        
      
    };
})(jQuery);


/**
 * jCarouselLite - jQuery plugin to navigate images/any content in a carousel style widget.
 * @requires jQuery v1.2 or above
 *
 * http://gmarwaha.com/jquery/jcarousellite/
 *
 * Copyright (c) 2007 Ganeshji Marwaha (gmarwaha.com)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 * Version: 1.0.1
 * Note: Requires jquery 1.2 or above from version 1.0.1
 */
(function($){$.fn.jCarouselLite=function(o){o=$.extend({btnPrev:null,btnNext:null,btnGo:null,mouseWheel:false,auto:null,speed:200,easing:null,vertical:false,circular:true,visible:3,start:0,scroll:1,beforeStart:null,afterEnd:null},o||{});return this.each(function(){var b=false,animCss=o.vertical?"top":"left",sizeCss=o.vertical?"height":"width";var c=$(this),ul=$("ul",c),tLi=$("li",ul),tl=tLi.size(),v=o.visible;if(o.circular){ul.prepend(tLi.slice(tl-v-1+1).clone()).append(tLi.slice(0,v).clone());o.start+=v}var f=$("li",ul),itemLength=f.size(),curr=o.start;c.css("visibility","visible");f.css({overflow:"hidden",float:o.vertical?"none":"left"});ul.css({margin:"0",padding:"0",position:"relative","list-style-type":"none","z-index":"1"});c.css({overflow:"hidden",position:"relative","z-index":"2",left:"0px"});var g=o.vertical?height(f):width(f);var h=g*itemLength;var j=g*v;f.css({width:f.width(),height:f.height()});ul.css(sizeCss,h+"px").css(animCss,-(curr*g));c.css(sizeCss,j+"px");if(o.btnPrev)$(o.btnPrev).click(function(){return go(curr-o.scroll)});if(o.btnNext)$(o.btnNext).click(function(){return go(curr+o.scroll)});if(o.btnGo)$.each(o.btnGo,function(i,a){$(a).click(function(){return go(o.circular?o.visible+i:i)})});if(o.mouseWheel&&c.mousewheel)c.mousewheel(function(e,d){return d>0?go(curr-o.scroll):go(curr+o.scroll)});if(o.auto)setInterval(function(){go(curr+o.scroll)},o.auto+o.speed);function vis(){return f.slice(curr).slice(0,v)};function go(a){if(!b){if(o.beforeStart)o.beforeStart.call(this,vis());if(o.circular){if(a<=o.start-v-1){ul.css(animCss,-((itemLength-(v*2))*g)+"px");curr=a==o.start-v-1?itemLength-(v*2)-1:itemLength-(v*2)-o.scroll}else if(a>=itemLength-v+1){ul.css(animCss,-((v)*g)+"px");curr=a==itemLength-v+1?v+1:v+o.scroll}else curr=a}else{if(a<0||a>itemLength-v)return;else curr=a}b=true;ul.animate(animCss=="left"?{left:-(curr*g)}:{top:-(curr*g)},o.speed,o.easing,function(){if(o.afterEnd)o.afterEnd.call(this,vis());b=false});if(!o.circular){$(o.btnPrev+","+o.btnNext).removeClass("disabled");$((curr-o.scroll<0&&o.btnPrev)||(curr+o.scroll>itemLength-v&&o.btnNext)||[]).addClass("disabled")}}return false}})};function css(a,b){return parseInt($.css(a[0],b))||0};function width(a){return a[0].offsetWidth+css(a,'marginLeft')+css(a,'marginRight')};function height(a){return a[0].offsetHeight+css(a,'marginTop')+css(a,'marginBottom')}})(jQuery);
