function GoAgence(id) {
    xt_click(this, 'C', 'recherche_agences', 'dep_' + id, 'N');
    this.location.href = "/recherche-agences/agences/?find=" + id;
}

function GoRegion(id) {
    xt_click(this, 'C', 'actualites_region', 'espace_' + id, 'N');
    this.location.href = id + "/";
}

function openVideo(uri) 
{
    var oWnd = radopen('/videos/?file=' + uri, 'wVideo');
    //oWnd.center();
}

function openEnergie(id) 
{
    var oWnd = radopen('consommation_energetique.aspx?id=' + id, 'wConso');
    //oWnd.center();
}


function openSimulateur(uri, win) 
{
    var oWnd = radopen(uri, win);
    //oWnd.center();
}


/**
 * @name SquareHabitatJs 
 * création et définition de la classe contenant la logique métier propre au fonctionnement du site square habitat
 */
var SquareHabitatJs = function () {
    // initialisation des paramètres par défaut    
    this._current = '';
    this._stepped = false;
    this._rechercheResultsPage = 1;

    this._hidePopinOnScroll = false;
    this._hidePopinOnEscape = true;
    this._hidePopinOnOutsideClick = true;

    this._mapHilightConf = {
        fill: true,
        fillColor: '000000',
        fillOpacity: 0.2,
        stroke: false,
        strokeColor: 'ff0000',
        strokeOpacity: 1,
        strokeWidth: 1,
        fade: true,
        alwaysOn: false,
        neverOn: false,
        groupBy: false,
        onmousemove: function (event, area) { },
        onmouseout: function (event, area) { }
    };

    this._beforePNGFixShow = '#plus';
    this._bgPNG2Fix = '';
};

/**
 * @name SquareHabitatJs.prototype
 * valorisation du prototype de la classe 
 */
SquareHabitatJs.prototype = {
    /**
    * @name SquareHabitatJs.initialize
    * fonction executé lorsque le chargement de la page est terminé et que le DOM est prêt      
    */
    initialize: function () {
        this.initPrefilled();
        this.initPopin();

        if (this.isCurrent('home')) {
            this.initClouds();
        }

        if (this.isCurrent('recherche')) {
            this.initRecherche();
        }

        if (this.isCurrent('profil')) {
            this.initSteps();
        }

        if (this.isCurrent('agences')) {
            this.initAgences();
        }


        if (this.isCurrent('programme')) {
            this.initProgramme();
        }

        if (this.isCurrent('bien')) {
            this.initBien();
        }

        if (this.isCurrent('lot')) {
            this.initLot();
        }

        if (this.isCurrent('agences-recherche')) {
            this.initMapAgences();
        }

        /* Sylvain
        if(this.isCurrent('agences-liste')){
        this.initAgencesListe();
        }
        
        */
        if (this.isCurrent('actu-region')) {
            this.initActualitesRegion();
        }

        if (this.isCurrent('vacances')) {
            this.initMapVacances();
        }

        if (this.isCurrent('plan-du-site')) {
            this.initPlan();
        }

        if (this.isCurrent('contact')) {
            this.initContact();
        }

        if (this.isCurrent('integrer-squarehabitat')) {
            this.initRecrutementFormulaire();
        }

        this.initPreSearchs();
    },

    /**
    * @name SquareHabitatJs.register2Newsletter
    * intercepte la soumission du formulaire d'inscription à la newsletter
    * @param string email 
    * @see SquareHabitatJs.ajax     
    */
    register2Newsletter: function (email) {
        /*
        this.ajax({
        type: 'GET',
        url: '/recherche-service',
        data: this.toQueryString(criterias),
        ok: function(html_response){
        this.showPopin('popin-nl', function(){
        $('#popin-container').find('.box-inner').html(html_response);   
        });
        }
        });  
        */
        this.showPopin('popin-nl');
        return false;
    },

    /**
    * @name SquareHabitatJs.initContact
    * intercepte la soumission du formulaire de contact      
    */
    initContact: function () {
        $('#form-contact').submit(function (e) {
            return true;
        });
    },

    /**
    * @name SquareHabitatJs.initRecrutementFormulaire
    * initialisation des fonctionnalités du formulaire de recherche d'emploi      
    */
    initRecrutementFormulaire: function () {
        var pager_links = $('#page li a'),
        offres = $('#offres-liste li'),
        displayed = 5;
        pager_links.each(function (eq) {
            var obj = $(this),
            min = (displayed * eq),
            max = (displayed * eq) + displayed;
            obj.click(function (e) {
                e.preventDefault();
                pager_links.removeClass('on');
                obj.addClass('on');
                offres.hide().filter(function (index) {
                    return index >= min && index < max;
                }).show();
                return false;
            });
        });
    },

    /**
    * @name SquareHabitatJs.initMapVacances
    * initialise la carte des vacances      
    */
    /*
    initMapVacances: function () {
    var carte = $('#carte-france'),
    conf = this._mapHilightConf;
    if (carte.length > 0) {
    carte.maphilight(conf);
    }
    },
    */
    /** Sylvain : On n'utilisape l'appel ajax... on mets tout dans la page :-)
    * @name SquareHabitatJs.fillPopinVacances
    * Remplit la popin lorsqu'un endroit est cliqué sur la carte des vacances
    */
    /*
    fillPopinVacances: function (obj) {
    // faire une requête asynchrone ici, @see SquareHabitatJs.ajax()
    $('#popin-villes-resultcopy').html('<li><a href="#" title="Cannes"><span>Cannes</span></a></li>' +
    '<li><a href="#" title="Le Cannet"><span>Le Cannet</span></a></li>' +
    '<li><a href="#" title="Grasse"><span>Grasse</span></a></li>' +
    '<li><a href="#" title="Mandelieu"><span>Mandelieu</span></a></li>');
    },*/

    /**
    * @name SquareHabitatJs.initPlan
    * initialisation des événements de déploiement      
    */
    initPlan: function () {
        $('#plan-du-site').find('img').click(function () {
            var obj = $(this),
            show = obj.attr('src') == '/css/i/plus.jpg';
            obj.parent('li').children('ul').toggle();
            obj.attr('src', show ? '/css/i/minus.jpg' : '/css/i/plus.jpg');
        });
    },

    /**
    * @name SquareHabitatJs.initBiensListe
    * fonction executée lorsque la page contient une liste de biens
    * cette fonction intercepte les actions de tri et de changement de page de résultat      
    */
    initBiensListe: function () {
        this.initSorter(function (criteria, order) {
            SH.getResultatsRechercheBiens(SH._rechercheResultsPage, { criteria: criteria, order: order });
        });
        this.initPager(function (index) {
            SH.getResultatsRechercheBiens(index);
        });
    },

    /**
    * @name SquareHabitatJs.initAgencesListe
    * fonction executée lorsque la page contient une liste de d'agences
    * cette fonction intercepte les actions de tri et de changement de page de résultat      
    */
    initAgencesListe: function () {
        this.initSorter(function (criteria, order) {
            alert('Trier page ' + SH._rechercheResultsPage + ' par ' + criteria + ' ' + order);
        });
        this.initPager(function (index) {
            alert('Afficher page ' + index);
            SH.getResultatsRechercheBiens(index);
        });
    },

    /**
    * @name SquareHabitatJs.initActualitesRegion
    * initialise la carte interactive des agences square habitat, par région 
    * @uses $.fn.maphilight         
    */
    initActualitesRegion: function () {
        $('#carte-actualites-region').maphilight(this._mapHilightConf);
    },

    /**
    * @name SquareHabitatJs.initPreSearchs
    * initialise les push vers le formulaire de recherche principal, met à jour le panneau 
    */
    initPreSearchs: function () {
        var tabs = $('#tabs');

        if (tabs.length > 0 && tabs.hasClass('pre-search')) {
            $('#localite').keyup(function () {
                $('#city').children('span').text(SH.getNiceLocation($(this).val()));
            });
        }
    },

    /**
    * @name SquareHabitatJs.initMapAgences
    * initialise la carte interactive des agences square habitat, par département, une bulle est affichée au survol
    * @uses $.fn.maphilight 
    */
    initMapAgences: function () {
        var conf = this._mapHilightConf;
        conf.onmousemove = function (event, area) {
            var txts = area.attr('alt').split('/'), bubble = $('#carte_france_bubble');
            if (bubble.length == 0) {
                bubble = $('<div class="departement" id="carte_france_bubble" style="top:30px;right:320px;"><dl><dt>Département</dt><dd>Nombre d\'agences</dd></dl></div>').hide().appendTo($('body'));
            }
            $('#carte_france_bubble').css({
                left: event.pageX - 120,
                top: event.pageY - 75
            }).find('dt').text(txts[0]).end().find('dd').text(txts[1]).end().show();
        };
        conf.onmouseout = function (event, area) {
            $('#carte_france_bubble').hide();
        };
        $('#carte_france').maphilight(conf);        //---Sylvain
    },

    /**
    * @name SquareHabitatJs.initAgences
    * fonction executée lorsqu'on se trouve sur une page de type "Agences" (page carrefour)
    */
    initAgences: function () {
        this.initCarrousels();
    },


    /**
    * @name SquareHabitatJs.initAgences
    * fonction executée lorsqu'on se trouve sur une page de type "Agences" (page carrefour)
    */
    initProgramme: function () {
        this.initCarrousels();
    },

    /**
    * @name SquareHabitatJs.initBien
    * fonction execurtée lorsqu'on se trouve sur une page de type "Bien"
    * initialise les carrousels ainsi que le clic affichant la consommation énergétique
    */
    initBien: function () {
        this.initCarrousels();
        var diapo = $('#diapo'),
        ul = diapo.find('.fulls ul'),
        fulls = ul.children(),
        links = diapo.find('.items-overlay li a'),
        img_width = SH.getItemWidth(fulls.eq(0).children('img'));
        if (links.length == 0) $('#photo-numero').text("");
        links.each(function (eq) {
            var obj = $(this);
            obj.click(function (e) {
                e.preventDefault();
                if (!obj.hasClass('on')) {
                    links.removeClass('on');
                    obj.addClass('on');
                    ul.animate({ left: -parseInt(img_width * eq) + 'px' });
                    $('#photo-numero').find('strong').text(eq + 1);
                }
                return false;
            });
        });
        $('#consommation_energetique').click(function (e) {
            var obj = $(this),
            plusminus = obj.children('img');
            obj.parent('dd').children('table').toggle();
            plusminus.attr('src', plusminus.attr('src') == '/css/i/plus.jpg' ? '/css/i/minus.jpg' : '/css/i/plus.jpg');

            return false;
        });
    },

    /**
    * @name SquareHabitatJs.initCarrousels
    * initialise les carrousels présents dans le document
    */
    initCarrousels: function () {
        $('.carrousel').each(function (eq) {
            var carrousel = $(this),
            overlay = carrousel.find('.items-overlay'),
            arrows = carrousel.find('.browse'),
            navis = carrousel.find('.navi a'),
            items = overlay.children(),
            max_left = 0,
            item_width = SH.getItemWidth(items.eq(0));
            items.each(function () {
                max_left += SH.getItemWidth($(this));
            });
            max_left -= SH.getItemWidth(overlay.parent());

            var moveOverlay = function (next) {
                if (next >= 0) {
                    next = 0;
                    arrows.eq(0).animate({ opacity: 0.3 }, 'fast').css('cursor', 'default');
                } else {
                    arrows.eq(0).animate({ opacity: 1 }, 'fast').css('cursor', 'pointer');
                }
                if (next <= -max_left) {
                    next = -max_left;
                    arrows.eq(1).animate({ opacity: 0.3 }, 'fast').css('cursor', 'default');
                } else {
                    arrows.eq(1).animate({ opacity: 1 }, 'fast').css('cursor', 'pointer');
                }
                overlay.animate({ left: next + 'px' });
                if (navis.length > 0) {
                    navis.removeClass('on');
                    navis.eq(parseInt((-next / item_width) / 2)).addClass('on');
                }
            };
            arrows.click(function () {
                var step = $(this).hasClass('left') ? item_width : -item_width;
                var actual = parseInt(overlay.css('left'));
                var next = actual + step;
                moveOverlay(next);
            });
            navis.click(function () {
                moveOverlay(-((parseInt($(this).text()) - 1) * (item_width * 2)));
            });
        });
    },

    /**
    * @name SquareHabitatJs.initSorter
    * initialise l'action de tri, execute la fonction donnée en callback à chaque clic sur une option de tri
    * @param function callback     
    */
    initSorter: function (callback) {
        $('#tri dd a').live('click', function (e) {
            e.preventDefault();

            SH._sortCriteria = $(this).parent('dd').attr('class');
            SH._sortOrder = $(this).attr('class') == 'down' ? 'DESC' : 'ASC'
            if (typeof callback == 'function')
                callback(SH._sortCriteria, SH._sortOrder);

            /*var sort_criteria = $(this).parent('dd').attr('class');
            //var sort_order = $(this).attr('class') == 'down' ? 'DESC' : 'ASC';
            if (typeof callback == 'function')
            callback(sort_criteria, sort_order);

            */
            return false;
        });
    },

    /**
    * @name SquareHabitatJs.initPager
    * initialise l'action de changement de page, execute la fonction donnée en callback à chaque clic sur un numéro de page
    * @param function callback
    */
    initPager: function (callback) {
        $('#page li a').live('click', function (e) {
            e.preventDefault();
            var index, obj = $(this),
            classname = obj.attr('class'),
            links = $('#page li a');
            if (classname == 'previous')
                index = SH._rechercheResultsPage - 1;
            else if (classname == 'next')
                index = SH._rechercheResultsPage + 1;
            else
                index = classname.substring(5, obj.hasClass('on') ? classname.indexOf(' ') : classname.length);
            if (index <= 0) index = 1;
            if (index >= links.length - 1) index = links.length - 2;
            SH._rechercheResultsPage = index;
            links.removeClass('on').eq(index).addClass('on');
            if (typeof callback == 'function')
                callback(index);
            return false;
        });
    },

    /**
    * @name SquareHabitatJs.initRecherche
    * initialise toutes les fonctions nécessaires au fonctionnement de la recherche de biens
    */
    initRecherche: function () {
        this.initSliders();
        this.initRechercheTabs();
        this.initPlus();

       /* $('#result-container').find('.more-goods').find('a').click(function (e) {

            e.preventDefault();
            if (!$(this).hasClass('less-goods')) {
                $(this).addClass('less-goods').text('- de biens par page');
                $('#contentmain').addClass('more-goods');
            } else {
                $(this).removeClass('less-goods').text('+ de biens par page');
                $('#contentmain').removeClass('more-goods');
            }
            return false;
        });
        */

        $('#ckMaison').click(function () {
            SH.updateCriterias()
        });

        $('#ckAppartement').click(function () {
            SH.updateCriterias()
        });

        $('#ckTerrain').click(function () {
            SH.updateCriterias()
        });

        $('#ckParking').click(function () {
            SH.updateCriterias()
        });

        $('#ckDivers').click(function () {
            SH.updateCriterias()
        });

        for (i = 1; i <= 5; i++) {
            $('#ckPiece' + i).click(function () {
                SH.updateCriterias()
            });
        }

        $('#ckPlusParking').click(function () {
            SH.updateCriterias()
        });

        $('#ckPlusGarage').click(function () {
            SH.updateCriterias()
        });

        $('#ckPlusCave').click(function () {
            SH.updateCriterias()
        });

        $('#ckPlusBalcon').click(function () {
            SH.updateCriterias()
        });

        $('#ckPlusTerrasse').click(function () {
            SH.updateCriterias()
        });

        $('#ckPlusPiscine').click(function () {
            SH.updateCriterias()
        });

        $('#ckPlusTennis').click(function () {
            SH.updateCriterias()
        });

        SH.updateCriterias();

    },

    /**
    * @name SquareHabitatJs.getResultatsRechercheBiens
    * execute une requête asynchrone vers le serveur dans le but de récupérer les biens correspondant aux critères actuels
    * cette fonction est automatiquement appelée lors d'un changement d'option de tri ou de page de résultat
    * @param int pageIndex
    * @param string sortOrder
    */
    getResultatsRechercheBiens: function (pageIndex, sortOrder) {
        var criterias = this.getCriterias();
        if (sortOrder) criterias.sort = sortOrder;

        this.ajax({
            type: 'GET',
            url: '/recherche-biens/biens/ListeBiensByCritere.aspx',
            data: this.toQueryString(criterias),
            ok: function (html_response) { },
            success: function (html_response) {
                $('#result').html(html_response);
            }

        });
        return;
    },

    /**
    * @name SquareHabitatJs.initPopin
    * initialise les évenements liés à la popin, 
    * cache la popin au scroll, cache la popin à l'appui sur ECHAP
    */
    initPopin: function () {
        if (this._hidePopinOnScroll)
            $(window).scroll(function () {
                if ($('#popin-layout').is(':visible'))
                    SH.hidePopin();
            });
        if (this._hidePopinOnEscape)
            $(document).keyup(function (e) {
                if (e.which == 27)
                    SH.hidePopin();
            });
    },

    /**
    * @name SquareHabitatJs.initSteps
    * initialise l'affichage des étapes au roll-hover 
    */
    initSteps: function () {
        var steps = $('.step'),
        step_links = steps.find('h2 a'),
        descs = steps.find('.desc');
        step_links.each(function (eq) {
            $(this).hover(function () {
                if (!$(this).hasClass('on')) {
                    step_links.removeClass('on');
                    $(this).addClass('on');
                    descs.removeClass('step-on').hide().eq(eq).addClass('step-on').show();
                    if (!SH._stepped) {
                        $('#steps').animate({ height: '235px' });
                        SH._stepped = true;
                        if (SH.isLtIE7()) {
                            $('#board').animate({ bottom: '10px' });
                        }
                    }
                }
            });
        });
    },

    /**
    * @name SquareHabitatJs.initClouds
    * initialise l'affichage des nuages de mots-clés au survol, sur la page d'accueil
    * le fade n'est pas actif sur IE
    */
    initClouds: function () {
        var clouds = $('.cloud');
        clouds.hover(function () {
            clouds.find('dd').hide();
            if (!$.browser.msie)
                $(this).children('dd').fadeIn();
            else
                $(this).children('dd').show();
        }, function () {
            if (!$.browser.msie)
                $(this).children('dd').fadeOut();
            else
                $(this).children('dd').hide();
        });
    },

    /**
    * @name SquareHabitatJs.initPrefilled
    * initialise les champs pré-remplis
    */
    initPrefilled: function () {
        $('.prefilled').each(function () {
            var obj = $(this);
            obj.focus(function () {
                if (obj.val() == obj.data('defaultText')) {
                    obj.val('');
                }
                obj.addClass('changed');
            }).blur(function () {
                if (obj.val() == '') {
                    obj.val($(this).data('defaultText')).removeClass('changed');
                }
            }).data('defaultText', obj.attr('value'));
        });
    },

    /**
    * @name SquareHabitatJs.initPlus
    * initialise le click sur les options supplémentaires à cocher lors d'une recherche de biens
    * (fait passer les photos les unes sur les autres)
    */
    initPlus: function () {
        var cols = $('#plus .col');
        cols.each(function (eq) {
            var obj = $(this),
            imgs = obj.find('img');
            obj.find(':checkbox').click(function () {
                var cb = $(this), maxIndex = 0, zIndex = 0;
                if (cb.is(':checked')) {
                    imgs.each(function () {
                        zIndex = parseInt($(this).css('z-index'));
                        if (zIndex > maxIndex) {
                            maxIndex = zIndex;
                        }
                    });
                    cb.prev('img').css('z-index', maxIndex + 1);
                } else {
                    cb.prev('img').css('z-index', 1);
                }
            });
        });
        cols.find('input:checked').prev('img').css('z-index', 5);
    },

    /**
    * @name SquareHabitatJs.initRechercheTabs
    * initialise le click sur les onglets dans la page de recherche de biens
    */
    initRechercheTabs: function () {
        var tab_links = $('#tab li a');
        tab_links.each(function (i) {
            $(this).click(function (e) {
                e.preventDefault();
                $('#tabs').children('div').hide().eq(i).show();
                tab_links.removeClass('on').eq(i).addClass('on');
                if (i < tab_links.length - 1) {
                    $('#field-specify').show();
                } else {
                    $('#field-specify').hide();
                }
                return false;
            });
        });
        $('#tabs').children('div').hide().eq(0).show();
    },

    /**
    * @name SquareHabitatJs.refineSearch
    * Click sur le bouton permettant d'affiner la recherche de biens
    */
    refineSearch: function () {
        $('#tab li .on').parent('li').next().children('a').click();
    },

    /**
    * @name SquareHabitatJs.initSliders
    * initialise les sliders dans la page de recherche de biens
    */
    initSliders: function () {
        $("#SliderSurface").slider({ from: 0, to: 300, scale: ['indéfini', 20, 40, 60, 80, 100, 120, 140, 160, 180, 200, 220, 240, 260, 280, '300et+'], limits: false, step: 1, dimension: '&nbsp;m<small>2</small>', skin: "round_plastic", callback: function (value) { SH.updateCriterias() } });
        if ($("#rdAchat").is(":checked"))
            $("#SliderPrix").slider({ from: 0, to: 3000000, heterogeneity: ['56/500000', '61/600000', '83/1000000', '88/1500000', '94/2000000'], scale: ['indéfini', 50, 100, 150, 200, 250, 300, 350, 400, 450, 500, 600, 700, 800, 900, '1M', '1.5M', '2M', '3Met+'], limits: false, step: 1000, dimension: '&nbsp;&euro;', skin: "round_plastic", callback: function (value) { SH.updateCriterias() } });
        else
            $("#SliderPrix").slider({ from: 0, to: 60000, heterogeneity: ['48/1000', '52/1500', '66/3000', '71/5000', '76/10000'], scale: ['indéfini', 100, 200, 300, 400, 500, 600, 700, 800, 900, '1000', '1500', '2000', '2500', '3000', '5000', '10K', '20K', '30K', '40K', '50K', '60Ket+'], limits: false, step: 100, dimension: '&nbsp;&euro;', skin: "round_plastic", callback: function (value) { SH.updateCriterias() } });
    },

    /**
    * @name SquareHabitatJs.updateProjectLocation
    * met à  jour la ville affichée sur le panneau
    * @param string cityLocation
    */
    updateProjectLocation: function (cityLocation, lati, longi) {
        if (!isNaN(parseInt(lati)) && !isNaN(parseInt(longi))) {
            //pointeur proj
            //latitude 51.08° dunkerque, 1° = 16.88 px (145px/8.59°), 69px hauteur origine, 5px = 1/2 pointer
            //logitude 189 grenwish origine, 1° = 11.22 px (146px/13.01°)
            $("#pointer_proj").css({ display: 'inline', left: parseInt(189 + (11.22 * longi) - 5), top: parseInt(((51.08 - lati) * 16.88) + 69 - 5) })
            //pointer france
            $("#pointer_france").css({ display: 'inline', left: parseInt(51 + (9.99 * longi) - 5), top: parseInt(((51.08 - lati) * 14.90) + 3 - 5) })
        }
        else {
            $("#pointer_proj").css({ display: 'none' })
            $("#pointer_france").css({ display: 'none' })
        }
        $('#city span').text(cityLocation.replace(/(-)/g, " ").replace(/\s\([0-9]{2,5}\)$/, ""));
    },

    /**
    * @name SquareHabitatJs.updateProjectBudget
    * Met à  jour le post-it des prix
    * @param float minPrice
    * @param float maxPrice
    */
    updateProjectBudget: function (minPrice, maxPrice) {
        if (minPrice == 0 && maxPrice)
            $('#what').children('li:eq(1)').text('');
        else
            $('#what').children('li:eq(1)').text('Budget : ' + minPrice + ' à ' + maxPrice + ' €');
    },


    /**
    * @name SquareHabitatJs.updateProjectSurface
    * met à  jour le post-it des informations principales
    * @param array types
    * @param array pieces
    * @param float minSurface
    * @param float maxSurface
    */
    updateProjectSurface: function (types, pieces, minSurface, maxSurface) {
        var lib_pieces = '',
        lib_surface = '',
        nb_pieces = 0,
        list_types = '';

        $.each(pieces, function (i, value) {
            var suffix = i >= pieces.length - 2 ? ' ou ' : ', ';
            (value == 5) ? lib_pieces += '5 et +' : lib_pieces += value
            lib_pieces += suffix
            nb_pieces += parseInt(value)
        });
        $.each(types, function (i, value) {
            var suffix = i >= types.length - 2 ? ' ou ' : ', ';
            list_types += value + suffix;
        });

        if (list_types.length > 0) list_types = list_types.substring(0, list_types.length - 4);

        if (lib_pieces.length > 0) {
            if (list_types.length > 0)
                lib_pieces = ' de ' + lib_pieces

            lib_pieces = lib_pieces.substring(0, lib_pieces.length - 4) + ' pièce';
            if (nb_pieces > 1)
                lib_pieces += 's '
        }

        if (parseInt(minSurface) > 0 || parseInt(maxSurface) > 0)
            lib_surface = ' (' + minSurface + '-' + maxSurface + 'm²)'

        $('#what').children('li:eq(0)').text(this.capitalize(list_types + lib_pieces + lib_surface));
    },


    /**
    * @name SquareHabitatJs.updateProjectPlus
    * met à jour le post-it des plus
    * @param array[]string plus
    */
    updateProjectPlus: function (plus) {
        var whatelse = $('#whatelse').empty();
        $.each(plus, function (i, value) {
            whatelse.append('<li>' + value + '</li>');
        });
    },


    /**
    * @name SquareHabitatJs.updateCriterias
    * met à jour l'ensemble des critères sur les post-it en fonction des choix utilisateurs
    */
    updateCriterias: function () {
        var criterias = this.getCriterias();
        this.updateProjectBudget(criterias.budget.min, criterias.budget.max);
        this.updateProjectSurface(criterias.types, criterias.pieces, criterias.surface.min, criterias.surface.max);
        this.updateProjectPlus(criterias.plus);
        this.updateProjectLocation(criterias.localisation.commune, criterias.localisation.lati, criterias.localisation.longi);
    },


    /**
    * @name SquareHabitatJs.getCriterias
    * retourne l'ensemble des critères choisis sous la forme d'un objet
    * @return object criterias
    */
    getCriterias: function () {
        return {
            budget: { min: this.niceNumber(this.getSelectedPrixMin()), max: this.niceNumber(this.getSelectedPrixMax()) },
            surface: { min: this.getSelectedSurfaceMin(), max: this.getSelectedSurfaceMax() },
            types: this.getSelectedTypes(),
            pieces: this.getSelectedPieces(),
            localisation: { commune: this.getSelectedLocation(), lati: this.getSelectedLati(), longi: this.getSelectedLongi() },
            plus: this.getSelectedPlus()
        };
    },

    /**
    * @name SquareHabitatJs.getSelectedTypes
    * récupère les types cochés et retourne un tableau contenant leur libellé
    * @return array[]string selected
    */
    getSelectedTypes: function () {
        var selected = [];
        $('#type').find('input:checked').each(function () {
            selected.push($(this).next('label').text());
        });
        return selected;
    },

    /**
    * @name SquareHabitatJs.getSelectedPieces
    * récupère les pièces cichées par l'internaute et retourne un tableau contenant leur libellé
    * @return array[]string selected
    */
    getSelectedPieces: function () {
        var selected = [];
        $('#piece').find('input:checked').each(function () {
            selected.push($(this).val());
        });
        return selected;
    },

    /**
    * @name SquareHabitatJs.getSelectedPlus
    * récupére les options (plus) choisies et retourne un tableau
    * @return array[]string selected
    */
    getSelectedPlus: function () {
        var selected = [];
        $('#plus').find('input:checked').each(function () {
            selected.push($(this).next('label').text());
        });
        return selected;
    },

    /**
    * @name SquareHabitatJs.getSelectedLocation
    * récupére la valeur saisie dans le champ "localisation"
    * @return string location
    */
    getSelectedLocation: function () {
        return $('#hidCommune').val()
    },

    getSelectedLati: function () {
        return $('#hidLat').val()
    },

    getSelectedLongi: function () {
        return $('#hidLong').val()
    },

    getSelectedSurfaceMin: function () {
        return $('#SliderSurface').val().split(";")[0];
    },

    getSelectedSurfaceMax: function () {
        return $('#SliderSurface').val().split(";")[1];
    },

    getSelectedPrixMin: function () {
        return $('#SliderPrix').val().split(";")[0];
    },

    getSelectedPrixMax: function () {
        return $('#SliderPrix').val().split(";")[1];
    },

    /**
    * @name SquareHabitatJs.getItemWidth
    * retourne la largeur d'un élément en prenant en compte padding, borders et margins
    * @return int width
    */
    getItemWidth: function (jQEl) {
        return jQEl.outerWidth(true);
    },

    /**
    * @name SquareHabitatJs.getItemHeight
    * retourne la hauteur d'un élément en prenant en compte padding, bordures et margins'
    * @return int height
    */
    getItemHeight: function (jQEl) {
        return jQEl.outerHeight(true);
    },

    /**
    * @name SquareHabitatJs.getNiceLocation
    * retourne la localisation choisie modifiée (nettoyée)
    * @return string safeLocation
    */
    getNiceLocation: function (unsafeLocation) {
        // le vraie nom de ville peut-être récupérée via webservice type google map ou directement par le serveur
        // ou simplement nettoyée en enlevant les caractères spéciaux
        unsafeLocation = this.trim(unsafeLocation);
        return unsafeLocation;
    },

    /**
    * @name SquareHabitatJs.createGMapFromAddress
    * Créer une instance de carte google map pour une adresse textuelle donnée et un identifiant de conteneur HTML
    * @param string address
    * @param int gmapId 
    * @return bool success    
    */
    createGMapFromAddress: function (address, gmapId) {
        var addressInfos = { 'address': address };
        var map_options = {
            zoom: 14,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var map = new google.maps.Map(document.getElementById(gmapId), map_options);
        var geoclient = new google.maps.Geocoder();
        geoclient.geocode(addressInfos, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                map.setCenter(results[0].geometry.location);
                var marker = new google.maps.Marker({
                    map: map,
                    position: results[0].geometry.location,
                    title: addressInfos.address
                });
                return true;
            }
            return false;
        });
    },

    /**

    * @name SquareHabitatJs.createGMapFromCoordinates
    * créer une instance de carte google map pour des coordonnées GPS données et un identifiant de conteneur HTML
    * @param float latitude
    * @param float longitude
    * @param string infos
    * @param int gmapId
    * @return bool success   
    */
    createGMapFromCoordinates: function (latitude, longitude, infos, gmapId) {
        var lat = parseFloat(latitude);
        var lng = parseFloat(longitude);
        var latlng = new google.maps.LatLng(lat, lng);
        var mapInfos = { 'title': infos };
        var map_options = {
            zoom: 14,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };

        var map = new google.maps.Map(document.getElementById(gmapId), map_options);
        var geoclient = new google.maps.Geocoder();

        geoclient.geocode({ 'latLng': latlng }, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                var marker = new google.maps.Marker({
                    map: map,
                    position: latlng,
                    title: mapInfos.title
                });
                return true;
            }
            return false;
        });
    },

    /**
    * @name SquareHabitatJs.showPopin
    * affiche la popin d'ID popinId et execute une fonction de retour lorsqu'affichée
    * si aucune fonction de retour n'est passée, aucune n'est executée
    * @param string popinId
    * @param optional function callback
    * @param optional object obj
    */
    showPopin: function (popinId, callback, obj) {
        var layout = $('#popin-layout'),
        popin_content = $('#' + popinId).clone().find('script').remove().end().show();
        if (popin_content.length > 0) {
            popin_content.find('*[id]').each(function () { $(this).attr('id', $(this).attr('id') + 'copy'); });
            var scroll_top = $(window).scrollTop();
            if (layout.length == 0) {
                layout = $('<div id="popin-layout"></div>').css({
                    top: 0,
                    display: 'none'
                }).appendTo('body').append('<div id="popin-container"></div>');
            }
            layout.css({
                paddingTop: scroll_top,
                height: $(document).height() - scroll_top,
                width: $(document).width(),
                overflow: 'hidden'
            });
            var container = layout.children('div').empty().append(popin_content).css({
                left: ($(window).width() - parseInt(popin_content.css('width'))) / 2
            }).find('*').show().end();
            layout.fadeIn('medium', function () {
                if (typeof callback == 'function') {
                    if (typeof obj == 'object') {
                        callback(obj);
                    } else {
                        callback();
                    }
                }
            });

            container.css({
                marginTop: ($(window).height() - popin_content.outerHeight(true)) / 2
            });
        }

        return false;
    },

    /**
    * @name SquareHabitatJs.hidePopin
    * caches la popin actuellement affichée
    */
    hidePopin: function () {
        $('#popin-layout').fadeOut('fast');
    },

    /**
    * @name SquareHabitatJs.isCurrent
    * Vérifies si la classe donnée fait partie des classes de la page courante
    * @param string className
    * @return bool success
    */
    isCurrent: function (className) {
        if (this._current == '') {
            var content_inner = $('#content-inner');
            if (content_inner.length > 0)
                this._current = content_inner.attr('class');
            else
                this._current = 'default';
        }
        return this._current == className || this._current.indexOf(' ' + className) > -1 || this._current.indexOf(className + ' ') > -1;
    },

    /**
    * @name SquareHabitatJs.ajax
    * execute une fonction AJAX utile pour permettre de gérer un loading global au site
    * en cas de succès, la fonction ok() est appelée
    * @param object params
    * @see jQuery.ajax
    */
    ajax: function (params) {
        // faire quelque-chose avant le lancement de la requête asynchrone (montrer une image de chargement?)
        params.complete = function () {
            // faire quelque-chose après le lancement de la requête asynchrone (cacher l'image de chargement?)
            params.ok();
        };
        $.ajax(params);
    },

    /**
    * @name SquareHabitatJs.isDefined
    * Vérifies si une variable est définie
    * @return bool success
    */
    isDefined: function (val) {
        return val != null && val != 'undefined';
    },

    /**
    * @name SquareHabitatJs.isInt
    * Vérifies si une variable est un entier
    * @return bool isint
    */
    isInt: function (val) {
        return ((parseFloat(value) == parseInt(value)) && !isNaN(parseInt(value)));
    },

    /**
    * @name SquareHabitatJs.trim
    * Enlèves les espaces situés avant et après la chaine
    * @return string trimmedstring
    */
    trim: function (str) {
        return str.replace(/^\s+/g, '').replace(/\s+$/g, '')
    },

    /**
    * @name SquareHabitatJs.without
    * tronque une chaine représentant une mesure
    * @return string truncated
    */
    without: function (str, measure_char) {
        var indexofchar = str.indexOf(measure_char);
        if (indexofchar == -1) return str;
        if (str.length == measure_char.length) return 0;
        return parseFloat(str.substring(0, indexofchar));
    },

    /**
    * @name SquareHabitatJs.capitalize
    * met la première lettre d'une chaine en majuscule
    * @return string capitalized
    */
    capitalize: function (str) {
        return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
    },

    /**
    * @name SquareHabitatJs.toQueryString
    * transforme un objet en une chaine de caractères constituant une URL paramètrable
    * @param object obj
    * @param optional string key_prefix
    * @return string url
    */
    toQueryString: function (obj, key_prefix) {
        var str = '', key;
        key_prefix = (!key_prefix) ? '' : key_prefix + '_';
        for (key in obj) {
            if (typeof obj[key] != 'object') {
                str += encodeURIComponent(key_prefix + key) + '=' + encodeURIComponent(obj[key]) + '&';
            } else if (this.isArray(obj[key])) {
                str += encodeURIComponent(key_prefix + key) + '=' + encodeURIComponent(obj[key].join(',')) + '&';
            } else {
                str += this.toQueryString(obj[key], key);
            }
        };
        return str;
    },

    /**
    * @name SquareHabitatJs.niceNumber
    * écrit un nombre de manière à ce qu'il soit lisible facilement par l'internaute
    * @param float number
    */
    niceNumber: function (number) {
        if (number > 1000)
            number = Math.round(number / 1000) * 1000;
        if (number > 1000000)
            return parseFloat(number / 1000000).toPrecision(2).replace('.', ',') + 'M';
        number = parseInt(number);
        number += '';
        var x = number.split('.'),
        x1 = x[0],
        x2 = x.length > 1 ? '.' + x[1] : '',
        rgx = /(\d+)(\d{3})/;
        while (rgx.test(x1))
            x1 = x1.replace(rgx, '$1' + ' ' + '$2');
        return x1 + x2;
    },

    /**
    * @name SquareHabitatJs.isArray
    * @return bool isarray
    */
    isArray: function (obj) {
        return typeof obj == 'object' && (obj instanceof Array);
    },

    /**
    * @name SquareHabitatJs.isLtIE6
    * retourne un booléen statuant si oui ou non le navigateur actuel est une version d'internet explorer inférieure à 7
    * @return bool isltie7
    */
    isLtIE7: function () {
        return $.browser.msie && $.browser.version < 7;
    },

    /**
    * @name SquareHabitatJs.fixIE
    * Gère la transparence sur les PNG pour IE6, les blocs contenant les images à appliquer le filtre doivent être visibles
    */
    fixIE: function () {
        var beforeshow = $(this._beforePNGFixShow).show();
        $('img[src$=.png]').each(function () {
            var obj = $(this);

            var prevStyle = '';
            var strNewHTML = '';
            var imgId = (obj.attr('id')) ? 'id="' + obj.attr('id') + '" ' : '';
            var imgClass = (obj.attr('class')) ? 'class="imgfixed ' + obj.attr('class') + '" ' : 'class="imgfixed" ';
            var imgTitle = (obj.attr('title')) ? 'title="' + obj.attr('title') + '" ' : '';
            var imgAlt = (obj.attr('alt')) ? 'alt="' + obj.attr('alt') + '" ' : '';
            var imgAlign = (obj.attr('align')) ? 'float:' + obj.attr('align') + ';' : '';
            var imgHand = (obj.parent().attr('href')) ? 'cursor:hand;' : '';
            var imgPos = (obj.css('position')) ? obj.css('position') : 'relative';
            var imgFloat = (obj.css('float')) ? obj.css('float') : 'none';
            var imgWidth = obj.attr('width');
            var imgHeight = obj.attr('height');

            if (this.style.border) {
                prevStyle += 'border:' + this.style.border + ';';
                this.style.border = '';
            }
            if (this.style.padding) {
                prevStyle += 'padding:' + this.style.padding + ';';
                this.style.padding = '';
            }
            if (this.style.margin) {
                prevStyle += 'margin:' + this.style.margin + ';';
                this.style.margin = '';
            }
            var imgStyle = (this.style.cssText);

            strNewHTML += '<span ' + imgId + imgClass + imgTitle + imgAlt;
            strNewHTML += 'style="position:' + imgPos + ';float:' + imgFloat + ';white-space:pre-line;display:inline-block;background:transparent;' + imgAlign + imgHand;
            strNewHTML += 'width:' + imgWidth + 'px;height:' + imgHeight + 'px;';
            strNewHTML += 'filter:progid:DXImageTransform.Microsoft.AlphaImageLoader' + '(src=\'' + obj.attr('src') + '\', sizingMethod=\'crop\');';
            strNewHTML += imgStyle + '"></span>';
            if (prevStyle != '') {
                strNewHTML = '<span style="position:relative;display:inline-block;' + prevStyle + imgHand + 'width:' + imgWidth + 'px;' + 'height:' + imgHeight + 'px;' + '">' + strNewHTML + '</span>';
            }

            obj.hide();
            obj.after(strNewHTML);
        });

        if (this._bgPNG2Fix != '')
            $(this._bgPNG2Fix).each(function () {
                var bgIMG = jQuery(this).css('background-image');
                if (bgIMG.indexOf(".png") != -1) {
                    var iebg = bgIMG.split('url("')[1].split('")')[0];
                    jQuery(this).css('background-image', 'none');
                    jQuery(this).get(0).runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + iebg + "',sizingMethod='crop')";
                }
            });

        beforeshow.hide();
        $('#content-inner.actu-region, #content-inner.vacances').height(550);
        $('.section1 .box-238.pub .box-inner, .section2 .box-238.pub .box-inner, .section3 .box-238.pub .box-inner, .section4 .box-238.pub .box-inner, .section5 .box-238.pub .box-inner, .section6 .box-238.pub .box-inner').css({
            backgroundPosition: '0 0'
        });
    }
};

// création de l'instance SquareHabitatJs
var SH = new SquareHabitatJs();
$(document).ready(function(){
    // lorsque le DOM est prêt on initialise l'instance SH
    SH.initialize();
    if(SH.isLtIE7()){
        // si le navigateur utilisé est IE et sa version < 7 alors on fixe les soucis d'image et de layout
        SH.fixIE();
    }
});
