/* BUGS


- Sous IE6, la liste ne s'agrandit pas jusqu'en bas au premier chargement.
- Sous IE6, la petite popup ne se cache pas bien quand on ouvre la grande.


*/

/*
var sString = "Ceci est un test, nous allons compter combien de fois le mot test apparait dans ceci est un test";
var sOcc = 'test';
var iCpt = substr_count (sString, sOcc);
document.write(iCpt); 
*/
function substr_count( haystack, needle, offset, length ) {
   //Debug.trace2("substr_count"); 
    var pos = 0, cnt = 0;
 
    if(isNaN(offset)) offset = 0;
    if(isNaN(length)) length = 0;
    offset--;
 
    while( (offset = haystack.indexOf(needle, offset+1)) != -1 ){
        if(length > 0 && (offset+needle.length) > length){
            return false;
        } else{
            cnt++;
        }
    }
   //Debug.trace2("- resut : " + cnt); 
    return cnt;
}

function __(key) {
    ////Debug.trace3("__ translating : " + key);
    //traducteur
    
    if (LABELS[key])
        return LABELS[key];
    
    ////Debug.trace2("- " + key + " <strong>no translation found</strong>");
    // ////Debug.count("No translation");
    // ////Debug.displaySpies();
    return key;
}

function Slider2(id2, absMin, absMax, steps) { //INUTILE
    alert("Slider2 Utilisé");
   //Debug.trace("Slider2 constructor called: " + id2);
    this.id2 = id2;
    this.min = null; //valeur actuelle du curseur min
    this.max = null;
    this.absMin = absMin; //valeur min du curseur
    this.absMax = absMax;
    this.steps = steps; //nombre de pas
    
    this.focusValMin = null;
    this.focusValMax = null;
    
    //init
    var me = this;
    this.min = $('#slider' + this.id2 + 'Min').val();
    this.max = $('#slider' + this.id2 + 'Max').val();
    
    this.create();
    
    //positionnement du curseur max
    $('#slider' + this.id2).slider( "moveTo", this.max , 1 );
    
    //positionnement du curseur min
    $('#slider' + this.id2).slider( "moveTo", this.min , 0 );
    
    //Action à faire à l'entree sur le champ Min
    $("#slider"+ this.id2 + "Min").focus(function() {

       //Debug.trace2("Focus on: " + $(this).attr('id') );
        
        me.focusValMin = $("#slider"+ me.id2 + "Min").val();
        
       //Debug.trace3("- Focus value: " + me.focusValMin);
    });
    
    //Action à faire à l'entree sur le champ Max
    $("#slider"+ this.id2 + "Max").focus(function() {

       //Debug.trace2("Focus on: " + $(this).attr('id') );
        
        me.focusValMax = $("#slider"+ me.id2 + "Max").val();
        
       //Debug.trace3("- Focus value: " + me.focusValMax);
    });
    
    //Action à faire à la sortie du champ Min
    $("#slider"+ this.id2 + "Min").blur(function() {
        
       //Debug.trace2($(this).attr('id') + " blur: " + me.focusValMin + " -> " + $("#slider"+ me.id2 + "Min").val() );

        me.onInputChange();
    });
    
    //Action à faire à la sortie du champ Max
    $("#slider"+ this.id2 + "Max").blur(function() {
        
       //Debug.trace2($(this).attr('id') + " blur: " + me.focusValMax + " -> " + $("#slider"+ me.id2 + "Max").val() );
        
        me.onInputChange();
    });
    

    //Action à faire à la sortie des champs Min et Max
    /*
    $("#sliderXXX"+ this.id2 + "Min , #slider"+ this.id2 + "Max").blur( function() {
        me.onInputChange();
    } );
    */

}
Slider2.prototype = {
    
    create: function() {
       //Debug.trace2("Slider2.create started: " + this.id2);
        var me = this;
        var onSlide = function() {

           //Debug.trace2("Slider2.onSlide " + me.id2 + " min: " + $('#slider' + me.id2).slider('value', 0) + " max: " + $('#slider' + me.id2).slider('value', 1));
            
            $('#slider' + me.id2 + 'Min').val( $('#slider' + me.id2).slider('value', 0));
            $('#slider' + me.id2 + 'Max').val( $('#slider' + me.id2).slider('value', 1));
            App.sliderMoved();
        };
        //var o = { min: this.absMin, max: this.absMax, startValue: this.min, steps: this.steps, range: true, slide: onSlide };
        var o = { min: this.absMin, max: this.absMax, steps: this.steps, range: true, slide: onSlide };
        $('#slider' + this.id2).slider(o);
    },

    onInputChange: function() {
       //Debug.trace2("Slider2.onInputChange started: " + this.id2);    
        this.refresh();
    },
    
    refresh: function() {
    
       //Debug.trace("Slider2.refresh started: " + this.id2);
        
        this.min = $('#slider' + this.id2 + 'Min').attr('value');
        this.max = $('#slider' + this.id2 + 'Max').attr('value');
        
       //Debug.trace2("- min: " + this.min);        
       //Debug.trace2("- max: " + this.max);
        
        $('#slider' + this.id2).slider( "moveTo", this.min , 0, true);
        $('#slider' + this.id2).slider( "moveTo", this.max , 1 );
    }

};

$.fn.extend({

    check: function() {
        return this.each(function() { this.checked = true; });
    },
    
    uncheck: function() {
        return this.each(function() { this.checked = false; });
    },
    
    toggle: function() {
        return this.each(function() { this.checked = !this.checked; });
    },
    
    extractNumber: function( html ) {
        //Extrait les nombres du contenu html d'un élément
        //utilisation : $("#element").extractNumber() ou $.fn.extractNumber("1'000'000")

        if ( !html ) { //si on a passé aucun paramètres, on va rechercher le contenu html de l'élément
            html = $(this).html();
        }

        //si on a toujours rien, on retourne...
        if ( !html) {
            return
        }

       //Debug.trace2("$.extractNumber: " + html);
        
        var aVirer = [ "m2", ".-", ".--", "pièces" ]; //liste des chaines à supprimer immédiatement
        var returnMax = [ "max" , "Max", "MAX", "illimité" , "Illimité" , "ILLIMITE"]; //liste de valeurs qui retournent le maximum
        var returnZero = [ "indifférent" ]; //liste de valeurs qui retournent zéro
        var result = "";
        var numbers2 = [ "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" , "." , "," ];
        //alert( html.charAt(0));
        //alert( html.length );
        //alert(numbers2);
        
        $( aVirer ).each( function() { //on commence par nettoyer
           //Debug.trace3(this);
            if( html.indexOf(this) != -1 ) {
               //Debug.trace3("****VIRER******");
                //le début de la chaine
                var tmp = html.substr(0, html.indexOf(this) );
               //Debug.trace3("- tmp: " + tmp);
                //la fin de la chaine
                //var start = indexOf(this) + this.length
                tmp += html.substr( html.indexOf(this) + this.length , html.length);
               //Debug.trace3("- tmp: " + tmp);
                html = tmp;
            }
        }); 
        
        if( $.inArray( html, returnMax) != -1 ) {
            return Number.MAX_VALUE;
        }
        
        if( $.inArray( html, returnZero) != -1 ) {
            return 0;
        }        
        
        for ( i = 0 ; i < html.length ; i++) {
            
            if( $.inArray( html.charAt(i), numbers2 ) != -1 ) {
                result += html.charAt(i);
                //alert( html.charAt(i) );
            }
            
        }
       //Debug.trace2( "-> " + result );
        return result;
    }
    
});

/* optimisation, mise en cache des $("elem") */
var e = [];
function ce(id) { //cache e
    //Debug.trace2("ce: " + id);
    if ( !e[id] ) {
        //Debug.trace2("-- not found -> create");
        e[id] = $(id);
        //Debug.count("ce -> new");
    //} else {
        //Debug.trace2("-- from cache");
        //Debug.count("ce -> cache");
    }
    /*//Debug.displaySpies();*/
    return e[id];
} 

var App = {
    
    //id: null, //id du bien affiché

    safari: true, // est mis à false par detectNavigator si on a pas affaire à safari (ou chrome)
    ie6: true, // est mis à false par detectNavigator si on a pas affaire à IE6
    
    hash : null,
    hasTimer: null,
    
    delay: 100, //Delay utilisé pour les temporisations (pour éviter que ca parte dans tous les sens) [ms]
    initialized: false, // est-ce que les biens ont déjà étés affichés?
    
    mouseX: null, //position de la souris
    mouseY: null,
    
    ready: false, //Application prête à aller chercher les données
    blockNextClick: true, //Est-ce que le prochain click est bloqué?
    
    goods: null,    
    list: null,
    bigMap: null,
    
    hasBigMap: false,
    hasSmallMap: false,
    hasBigList: false,
    hasSmallList: false,
    
    tmp: false, //variable temporaire utilisée pour tricher...
    
    //e: [], //liste des éléments (optimisation);
    
    hasSmallPopup: false,
    hasBigPopup: false,
    
    mapResizeTimer: null,
    mapResizeDelay: 500, // [ms]
    
    oldHeight: null, //pour la vérification du resize
    oldWidth: null,
    
    loadAll: true, // false: on recharge en fonction de la zone d'affichage de la map, true: Tout est chargé à l'initialisation de l'application
    goodsLoadLaunched: false, //La demande de chargement des biens à déjà étée faite.
    
    reloadOnZoomIn: false, // false: on ne force pas le reload au changement de zoom, true: On force le reload pour décharger l'application au cas ou on fait un zoom in
    showFullList: false, // false: n'affiche que les quelques premiers biens dans la petite liste, true: affiche tout
    listMode: "ul", // table ou ul //INUTILE!!! on utlilse que le mode liste
    
    mode: "normal", // bigMap
    
    home: true, // est-ce qu'on est sur la home page?
    promo: false, // est-ce qu'on est sur la page promo?
    
    elementDetector: function() {
        //Recherche les divers éléments dans le code html pour savoir ce qu'il faut remplir
    
       //Debug.trace("App.elementDetector started");
        //Debug.startSpy("App.elementDetector");        
        //Détection de la présence de bigMap
        // id: gMap class: big
        if( ce("#gMap").hasClass("big")) {
           //Debug.trace2("- BigMap found");
            App.hasBigMap = true;
        } else {
            App.hasBigMap = false;
        }
        
        /* on a pas de small map...
        if( ce("#gMap").hasClass("small")) {
           //Debug.trace2("- smallMap found");
            App.hasSmallMap = true;
        } else {
            App.hasSmallMap = false;
        }
        */
        
        
        
        //Détection de la présence de la petite liste
        // id: tableBiens class: small
        if( ce('#tableBiens').hasClass("small")) {
           //Debug.trace2("- Small List found");
            App.hasSmallList = true;
        } else {
            App.hasSmallList = false;
        }
        
        if( ce('#tableBiens').hasClass("big")) {
           //Debug.trace2("- Big List found");
            App.hasBigList = true;
        } else {
            App.hasBigList = false;
        }
        
        
        
        //Détection de la présence du petit popup
        // id: detailPopup class: small
        if( ce('#detailPopup').hasClass("small")) {
           //Debug.trace2("- SmallPopup found");
            App.hasSmallPopup = true;
        } else {
            App.hasSmallPopup = false;
        }
        
        //Détection de la présence du grand popup
        //id="detailBigPopup" class="big"
        if( ce('#detailBigPopup').hasClass("big") ) {
           //Debug.trace2("- BigPopup found");
            App.hasBigPopup = true;
        } else {
            App.hasBigPopup = false;
        }
        
        //Debug.stopSpy("App.elementDetector");           
    },
    
    modeDetector: function() {
        //Détecte le mode dans lequel on se trouve en fonction des éléments présents
    
       //Debug.trace("App.modeDetector started");
        
        if( App.hasBigMap && App.hasSmallList ) {
            App.mode = "bigMap";
        } else if( App.hasSmallList || App.hasBigMap ) {
            App.mode = "test";
        }
        
       //Debug.trace2("- mode: " + App.mode);
        

        
        
    },
    
    detectHome: function() {
        //Détection de la page d'accueil
        //(et des autres pages aussi...)
        
       //Debug.trace2("App.detectHome");
        
        if( ce('#btn-accueil').parent().hasClass('selected') ){
            App.home = true;
        } else {
            App.home = false;
        }
        
        if( ce('#btn-sur-plan').parent().hasClass('selected') ){
            App.promo = true;
        } else {
            App.promo = false;
        }
        
    },    
    
    displayLoader: function() {
        //Affiche le loader principal
        
       //Debug.trace("App.displayLoader started");
        //Debug.count("App.displayLoader");
        ce('#mainLoader').css( "visibility" , "visible" );
        //
        if( DEBUG > -10 ) {
            //ce("body").css("background-color" , "red");
        }
        //Debug.stop("Loader Displayed");
    },
    
    removeLoader: function() {
        //Supprime le loader principal
        
       //Debug.trace("App.removeLoader started " + App.bigMap.ready + " " + App.list.ready);
        
        //on vérifie que l'application est vraiment prête
        var notReady = false;
        if ( App.hasBigMap ) {
            if ( !App.bigMap.ready ) {
                notReady = true;
            }
        }
      
      
        if ( App.hasSmallList && !App.home ) {
            if ( !App.list.ready ) {
                notReady = true;
            }
        }
        
        
        if ( !notReady ) {
            ce('#mainLoader').css( "visibility" , "hidden" );    
        } else {
           //Debug.trace("-- not ready");    
        }
      
        
        
        
        //Debug.count("App.removeLoader");
        
        if( DEBUG > -10 ) {
            //ce("body").css("background-color" , "black");
        }
        //Debug.stop("Loader removed");
        //Chrono.stop();
    },
    
    detectNavigator: function() { //0ms IE6
    
        
    
        if($.browser["safari"]) {
            App.safari = true;
           //Debug.trace("<strong>Browser is safari: auto-scroll logging disabled</srong>");
        } else {
            App.safari = false;
        }
        
        if($.browser["msie"]) {
            if( $.browser["version"] == "6.0") {
                App.ie6 = true;
                //alert("IE6 not fully supported by this beta version of the application.\nPlease use IE7, Firefox or Safari.");
            } else {
                App.ie6 = false;
            }
        } else {
            App.ie6 = false;
        }
        
        
        /*
        $.each($.browser, function(i, val) { 
            //code += i + ": " + val + "\n";
            //Debug.trace(i + ": " + val);
        });
        */
        
        
    },
            
    preInitXXX: function() { //0ms IE
    
   
        
        //Création du tableau d'éléments
        //$(document) déjà définit
        e['window'] = $(window);
        //e['mainLoader'] = $("#mainLoader");
        //e['gMap'] = $("#gMap");
        //e['tableBiens'] = $("#tableBiens");
        //e['detailPopup'] = $("#detailPopup");
        //e['detailBigPopup'] = $("#detailBigPopup");
        //e['btn-accueil'] = $("#btn-accueil");
        //e['btn-sur-plan'] = $("#btn-sur-plan");
        //e['detailBigPopup .backgroundMask'] = $("#detailBigPopup .backgroundMask");
        //e['gMapTools2'] = $("#gMapTools2");
        //e['logo a'] = $("#logo a");
        //e['langs a'] = $("#langs a");
        //e['blanc'] = $("._blanc");
        //e['planAccesPR'] = $("#planAccesPR");
        //e['onglets li a'] = $("#onglets li a");
        //e['result'] = $("#result");
        //e['resultCTC'] = $("#resultCTC");
   
    
    },
    
    init: function() {
        //alert( MODEAFF );
        if ( MODEAFF == 1 ) {
            App.initMode1();
        } else if ( MODEAFF == 2 ) {
            alert("ERROR!! Mode 2 should not use JS");
        } else if ( MODEAFF == 3 ) {
            App.initMode3();
        }
    },
    
    initMode1: function() {
        //Initialisation de l'application
        
        counters['InitStartedAt'] = new Date();
        
        //on redirge le click de la page sur le logo sur #accueil
        $("#logo").click( function() {
            ce("#btn-accueil").parent().click();
            App.blockNextClick = true;
            return false;
        });
        
        
        
        App.detectNavigator(); //0 ms IE6
        
        if( App.ie6 ) {
            alert('Internet explorer 6 ne peut pas afficher la version "Carte" de ce site. Veuillez utiliser un navigateur plus récent.');
            window.location.replace('?modeAff=3');
        }
        
        counters['dinit'] = new Date();
        
        Debug.init(); //65 ms IE6 (0ms sans debug)
        counters['DebugInitDoneAt'] = new Date();
        
        //affichage des compteurs de démarrage
        //Debug.displayStartStat();
        
        Debug.startSpy("App.init");

        //Chrono.start();
        
        
        //mise en cache de l'objet window
        e['window'] = $(window); //0 ms IE6
        
       
       
        
        //$(window).click(alert("alert windows click"));
        
        //SpeedTest.RunTest();
        if( DEBUG > -10 ) {
            //alert("speedTest 1: " + SpeedTest.Test_jQuery() );
        }
        

        
        /* transparences css */
          
        
        /* 0ms IE6 */
        
        if (!App.ie6) { // on ignore ca si on est sur IE6
            ce('#detailBigPopup .backgroundMask').css("opacity",0.8)
            ce("#mainLoader").css("opacity",0.8)
        }
          
        

        
       //Debug.trace("<strong>App.init started</strong>");    
        
        //Debug.startSpy("total");

        //détection du hash ( 0ms IE6)
        App.hash = App.getHash();
        if( App.hash ) {
           Debug.trace("hash: " + App.hash );
        } else {
           Debug.trace("no hash");
        }  

        
        
        //interception du click (0ms)
         
                
        e['document'].click(function() {
            App.click("main");

            if ( App.blockNextClick ) {
               //Debug.trace2("** Main click blocked **"); 
                return false;
            } else {
               //Debug.trace2("** Main click allowed **");
                App.blockNextClick = true;
               //Debug.trace2("- blockNextClick set");
            }
            
            
        }); //0ms
        
        //on active le click sur certains éléments
        ce('#inscrForm').click( function() {
            App.click("inscrForm");
        });
        ce('#inscrForm2').click( function() {
            App.click("inscrForm");
        });
        
        ce('#logo a').click( function() {
            App.blockNextClick = false;    
        });
        
        ce('#langs a').click(function() {
            App.blockNextClick = false;
        }); //plus lent... y'en a deux...
       
        $('.noBlock').click(function() {
            App.blockNextClick = false;
        });        
        
        
        //configuration du _blanc ON EN A PAS!!
        //ce('._blanc').attr("target","_blanc");
        
        
        App.elementDetector(); //31ms
        

        App.modeDetector(); //0ms
        

        
        counters['searchToolsInitAt'] = new Date();


        SearchTools.init(); //532ms


        
        counters['searchToolsLoadedAt'] = new Date();      
        
        
        
        //Resize pour mettre en place les elements
  
       
        App.placeElements(); //235ms
/*
        for( i = 1000 ; i < 100 ; i++ ) {
            $('#gMap').height('800px');
        }
*/   

        counters['ElementPlacedAt'] = new Date();
  
        
        
        
        


        
        //Mémorisation de la taille de la fenêtre
        App.oldHeight = e['window'].height();
        App.oldWidth = e['window'].width();


       //Debug.trace("Window size: " + App.oldWidth + " x " + App.oldHeight );


        
        
        //configuration du menu
        

        Menu.init();

        
        
        
        
        ce('#planAccesPR').click(function() {
            //on envoie l'utilisateur sur google map
            //window.open("http://maps.google.ch/maps?f=q&hl=fr&geocode=&q=2,+boulevard+Georges-Favon&sll=46.20474,6.1408&sspn=0.009549,0.018947&ie=UTF8&ll=46.20379,6.139705&spn=0.009905,0.018947&z=16&iwloc=addr");
            //App.bigMap.centerOnPR();
            App.click("planAccesPR");
            //return false; // bloque la propagation du click
        });


        
        
        //Configuration du modeSwitcher
        ModeSwitcher.init();





        
        if( App.mode == "normal") {
           //Debug.trace2("App.init : mode normal");
            App.removeLoader();
        } else {
           //Debug.trace2("App.init : autres mode");        
            
            //affiche le loader
            App.displayLoader();
            
            
            //Initialisation de la liste des biens
            App.goods = new Goods();
            
            App.goods.init(); //Initialise les icônes.
            
            
           
            Debug.startSpy("App.init14");             
            
            
            
            if( App.hasBigMap ) {
                App.bigMap = new BigCarte("#gMap");
                Debug.startSpy("bigMap.init()");
                App.bigMap.init(); //triggera mapReady et mapMoveEnd
                Debug.stopSpy("bigMap.init()");
                //configuration du click sur la carte plan d'accès

            }
            
          
            
            if( App.hasSmallPopup ) { 
                App.popup = new SmallPopup("#detailPopup");
            }
            
            if( App.hasBigPopup ) {
                App.details = new BigPopup("#detailBigPopup");
            }



     
            //Initialisation du comportement à la modification de la taille de la fenêtre
            e['window'].scroll( function() { App.doOnScroll(); } );
            e['window'].resize( function() { App.doOnResize(); } );
            e['window'].unload( function () { App.unLoad(); } );
    
      
            
            if( App.hasSmallList ) {    
                //App.list = new List("#tableBiens div tbody");
                App.list = new List("#tableBiens div");
                App.list.init();
            }
            


           //Debug.trace2("** Application is ready to load goods **");
            App.ready = true;



            //App.loadGoods();
            //Nouvelle méthode! ON PEUT LE FAIRE PLUS TOT!!

            App.goods.getAllGoodsFromServer();
            
            //Debug.stop("App.init END");
        
        }
        

        
        
        //alert("App.init End");

        App.startHashTimer();
        Debug.stopSpy("App.init14");
                
        //Debug.startSpy("App.init5"); 

        
        Debug.stopSpy("App.init");
        //Debug.displaySpies();
        
        //Debug.stop("App.init end");
        
    },
    
    initMode3: function() {
        //alert("initMode3");
        App.removeLoader();
        
        Debug.init(); //65 ms IE6 (0ms sans debug)
        
        //mise en cache de l'objet window
        e['window'] = $(window); //0 ms IE6
        
        /*
        //interception du click (0ms)        
        e['document'].click(function() {
        
            App.click("main");
            
            if ( App.blockNextClick ) {
               //Debug.trace2("** Main click blocked **"); 
                return false;
            } else {
               //Debug.trace2("** Main click allowed **");
                App.blockNextClick = true;
               //Debug.trace2("- blockNextClick set");
            }
            
            
        }); //0ms
        
        ce('#logo a').click( function() {
            App.blockNextClick = false;    
        });
        ce('#langs a').click(function() {
            App.blockNextClick = false;
        }); //plus lent... y'en a deux...
        */
        
        //Menu.init();
        
        SearchTools.initMode3();
    },
    
    click: function( from ) {
       //Debug.trace2(">>> App.click " + from);
    
        //fermeture du menu principal
        if( ( from != "Menu" ) && ( from != "Menu.container" ) ) {
            Menu.closeAll();
            
        }
        
        if( from == "Menu") {
            
        }
        
        //fermeture du formulaire dans BigPopup
        if( from == "BigPopup.container" ) {
            App.details.hideInteresse();
        }
        
        //autorisation d'execution de l'action du click
        //alert(from);
        if( from == "planAccesPR" ) {
           //Debug.trace2("- blockNextClick unset");
            App.blockNextClick = false;
        }
        
        if( from == "inscrForm") {
            Debug.trace2("inscrForm Click");
            var openUrl = ce('#inscrForm').attr("href");
            Debug.trace2( openUrl);
            window.open( openUrl );
            //App.blockNextClick = false;
            
        }
        
        
        
        //fermeture de la petite popup
        App.popup.hide();
        
        
    },
    
    advancedUser: function() {
       //Debug.trace2("App.advancedUser");
        //alert("advanced");
        ce('#gMapTools2').addClass("advanced");
    },
    
    normalUser: function() {
       //Debug.trace2("App.normalUser");
         ce('#gMapTools2').removeClass("advanced");
    },
    
    timerMenuEnd: function() {
       //Debug.trace2("App.timerMenuEnd");
        //alert("end");
        
        //on ferme le menu
        
        
    },
    
    goodsInitialized: function() {
        //Triggé par Goods.init... inutile??
    
       //Debug.trace2("App.goodsInitialized");
    },
    
    allGoodsLoadedFromServer: function(d) {
       //Debug.trace2("App.allGoodsLoaded");
       //Debug.trace("Before first good treatment");
        App.goods.firstGoodsTreatment(d);
        //alert("all goods loaded");
    },
    
    firstGoodsTreatmentDone: function() {
       //Debug.trace2("App.firstGoodsTreatmentDone");
        
        
        
        //App.goods.selectGenre("ALL"); //mode par défaut... inutile
        
        //Génération du nuage de tags
        
        TagCloud.init();
        
        
        
        
        App.goods.selectGoods();
        //alert("firstGoodTreatmentDone");

        //alert("open popup" + FIRSTGOODID);
        
        //alert(App.goods.linesBKP[FIRSTGOODID]);
        
        
        //Affichage du bien en promo!!
       //Debug.trace2("searching for promo...");
        var obj = App.goods.searchID(FIRSTGOODID);
        //alert(obj.id);
        
        //on vérifie qu'il existe avant de l'afficher
        if(obj) {
           //Debug.trace2("<strong>-- Opening promo</strong>");
            App.bigMap.centerOnObj(obj);

            App.selectGoodImmediate(obj);        
            if ( App.hasBigMap ) {
                App.bigMap.placeTopMarker(obj);
            }
        }
        
        
       //Debug.trace2("searching for Hash (onglets)...");
        //GESTION DU HASH click sur les onglets
        ce('#onglets li a').each(function() {
           //Debug.trace2("fg: HASH: " + $(this).attr("id") );
            var h = "btn-" + App.hash;
            if( $(this).attr("id") == h ) {
               //Debug.trace2("FOUND");
                $(this).parent().click();
            }
        });
        
       //Debug.trace2("searching for Hash (fiche)...");
        // GESTION DU HASH        
        //si on a #fiche/id on recherche l'id... si on l'a, on affiche
        if( App.hash.substr(0,6) == "fiche/") {
           //Debug.trace2("** HASH fiche!! **");
            //alert( App.hash.substring(6,App.hash.length) );
            obj = App.goods.searchID( App.hash.substring( 6, App.hash.length ) );
            //alert(obj);
            if(obj) {
               Debug.trace2("-- Opening: " + obj.id);
                App.showDetails(obj);
                if ( App.hasBigMap ) {
                    App.bigMap.placeTopMarker(obj);
                }
            } else {
               Debug.trace2("-- do not exist");
            }
            
        } 
        
        //Debug.stop("end fgtd");
        
        
        
    },
    
    goodsSelected: function() {
       //Debug.trace2("App.goodsSelected");
        
       //Debug.trace("goods ready to be loaded...");
        
        // !!!On part du principe qu'on a forcément une bigMap... 
        
        

        
        
        App.updateMap();
        
                //TEST !!!
        //on recentre sur les biens si on est en mode LOC
        if( App.goods.genreSelected == "LOC") {
            App.bigMap.centerOnBounds();
        }        
        
        
        //CREATION DE LA LISTE

        if( !App.home ) { //on a pas de liste sur la home page
            App.updateList();
        }    
            
    },
    
    updateMap: function() {
       //Debug.trace2("App.updateMap");
        
        App.bigMap.updateMap();
        
    },
    
    updateList: function() {
       //Debug.trace2("App.updateList");
        
        App.list.createList();
        //alert("update List");
    },
    
    updateListOnMapChanged: function() {
       //Debug.trace2("App.updateListOnMapChanged");
    
        //AFAIRE optimiser pour ne le faire que si c'est indspensable...
        if( !App.home ) {
            App.updateList();
        } else {
           //Debug.trace2("- home -> abort");
        }
    },
       
    showDetails: function(obj) {
       //Debug.trace2("App.showDetails: " + obj.no);
        App.displayLoader();
        //on ferme la petite fiche...
        //Debug.stop("before");
        App.popup.hide();
        //Debug.stop("after");
        App.details.loadFiche(obj);
        
        //FOIRE AVEC SAFARI!!!
        //App.setHash("fiche/" + obj.id);
        
        //App.showDetailsOLD(obj);
    },
    
    showDetailsOLD: function(obj) {
        //Affiche les détails du bien (ouvre le grand popup)
        
       //Debug.trace("App.showDetails started: " + obj.no);
        //Debug.count("App.showDetails");
        
        //chargement du bien dans le div détail
        if( App.hasBigPopup ) {
            
            //efface le carousel
            App.details.emptyCarouselLi();
            
            //efface la description
            App.details.emptyDescription();
            
            //efface les données
            App.details.emptyData();

            //Ouvre le popup
            App.details.show();


            
            //EFFACER AUSSI L'IMAGE ET LE TITRE H3
            

            
            //Prépare le bigPopup 
            //Charge l'image, le titre et fixe le numéro
            App.goods.fillBigPopup(obj);
            
            //Chargement des données
            App.details.loadData();
            
            //on charge la déscription du bien
            App.details.loadDescription(); //triggera detailDataLoaded
            
            
            //lance le chargement du carousel
            App.details.loadCarouselLi(); //triggera detailCarouselLiLoaded
        }
        
    },
    
    hideDetails: function() {
        //Masque le bigPopup
    
       //Debug.trace("App.hideDetails started"); 
        
        App.details.hide();
    },
    
    detailFicheLoaded: function(data) {
       //Debug.trace2("App.detailFicheLoaded");
        //alert("data Loaded");
        App.details.updateFiche(data);

        //Ouvre le popup
        App.details.show();
        //on vire le loader
        App.removeLoader();
    },
    
    detailCarouselLiLoaded: function(data) {
        //Est lancé quand le serveur à renvoyé les li du carousel
        
       //Debug.trace2("App.detailCarouselLiLoaded started"); 

        //charge le carousel
        App.details.updateCarousel(data);
    },
    
    detailDescriptionLoaded: function(data) {
        //Est lancé quand le bigPopup à recu la description du serveur
        
        //Debug.stopSpy("Description Loading");
        //Debug.displaySpies();
       //Debug.trace2("App.detailDescriptionLoaded");
        
        //alert(data);
        
        App.details.updateDescription(data);
    
    },
        
    detailDataLoaded: function(data) {
       //Debug.trace2("App.detailDataLoaded");
        
        //alert(data);
        App.details.updateData(data);
    },
    
    detailsOutClick: function() {
        //Est triggé par un click à côté de la zone detail de la big popup
        
       //Debug.trace("App.detailsOutClick started"); 
        
        App.hideDetails();
    },
    
    detailsCloseClick: function() {
        //Est triggé par un click sur le bouton close dans la popup détail

       //Debug.trace("App.detailsCloseClick started"); 
        
        App.hideDetails();
    },
    
    detailsMarkClick: function() {
        //Au click sur le bouton "je suis intéressé"
        
       //Debug.trace2("App.detailsMarkClick");
    
        //alert("markClick: " + App.goods.active);
        App.markGood(App.goods.active)
    },
    
    detailsContainerClick: function() {
        //Est triggé par un click dans la zone container du bigPopup (pour annuler le click out)
        
       //Debug.trace2("App.detailsContainerClick started"); 

    },
    
    sendMailResult: function(data) {
       //Debug.trace2("App.sendMailResult");
        
        if( data == "ok") {
            ce('#result').html(__('message-ok'));
            App.details.hideForm();
        } else {
            //alert(data);
            ce('#result').html('<strong class="error">' + data + '</strong>');
        }
        
        
        //alert(data);
    },
    
    sendMailResultCTC: function(data) {
       //Debug.trace2("App.sendMailResultCTC");
        
        if( data == "ok") {
            ce('#resultCTC').html(__('message-ok') );
            Menu.hideCTCForm();
        } else {
            //alert(data);
            ce('#resultCTC').html('<strong class="error">' + data + '</strong>');
        }
        
        
        //alert(data);
    },
    
    bigPopupFilled: function() {
        //Lancé quand le big popup est remplit
        
       //Debug.trace2("App.bigPopupFilled started"); 

    },
    
    listShowAllClicked: function() {
       //Debug.trace2("App.listShowAllClicked");
        
        //on mémorise le parametre de showFullList
        var mem = App.showFullList;
        
        //on force l'affichage de tout...
        App.showFullList = true;
        
        App.updateList();
        
        //on restaure l'ancienne valeur
        App.showFullList = mem;
    },
    
    listTableCreated: function() {
        //La liste des biens a été créée
        
       //Debug.trace("App.listTableCreated");
        
        App.goods.displayInfos();
        
        App.removeLoader();
        
    },
    
    listTableCreationAborted: function() {
       //Debug.trace3("App.listTableCreationAborted");
    },
    
    rowClicked: function(obj) {
        //Lancé par un click sur une ligne de la liste des biens
        
       //Debug.trace("App.rowClicked started: " + obj.no); 

        //Affiche les détails
        
        App.showDetails(obj);
    },
    
    rowHover: function(obj) {
        
       //Debug.trace2("App.rowHover: " + obj.no); 
        //alert("row Hover " + ID);
        App.selectGood(obj);
        
        if ( App.hasBigMap ) {
            App.bigMap.placeTopMarker(obj);
        }
        
    },
      
    markerClicked: function(ID) {
        //
        
       //Debug.trace2("App.markerClicked: " + ID);
    
        App.markGood(ID);
    },
    
    unMarkerClicked: function(ID) {
       //Debug.trace2("App.unMarkerClicked: " + ID);
        
        App.unMarkGood(ID);
    },
    
    markGood: function(ID) {
        //Marque un bien comme intéressant
        
       //Debug.trace2("App.markGood: " + ID);
        
        App.goods.markGood(ID);
    },
    
    unMarkGood: function(ID) {
       //Debug.trace2("App.unMarkGood: " + ID);
        
        App.goods.unMarkGood(ID);
    },
    
    goodMarked: function(ID) {
       //Debug.trace2("App.goodMarked: " + ID);
    },
    
    goodAlreadyMarked: function(ID) {
        //Ne devrait pas arriver
        
        //Debug.count("ALREADY-MARKED");
        //Debug.displaySpies();
       //Debug.trace2("App.goodAlreadyMarked: " + ID);
        
        //si le bien est déjà marqué, on enlève la marque
        App.unMarkGood(ID);
        
    },
    
    selectGood: function(obj) {
        //Sélectionne un bien

       //Debug.trace2("App.selectGood started"); 
        //Debug.startSpy("Activate");

        App.goods.select(obj); //triggera goodActivated
       

        
    },
    
    selectGoodImmediate: function(obj) {
        //sélectionne le bien immédiatement (bypasse le timer)
    
       //Debug.trace2("App.selectGoodImmediate: " + obj.no); 
        //Debug.startSpy("Activate");

        App.goods.selectNow(obj); //triggera goodActivated
    },
    
    selectGoodImmediateOLDXXX: function(ID) {
        //sélectionne le bien immédiatement (bypasse le timer)
    
       //Debug.trace2("App.selectGoodImmediate started"); 
        //Debug.startSpy("Activate");

        App.goods.selectNow(ID); //triggera goodActivated
    },
    
    goodActivated: function() {
        //est déclanché quand le bien est activé
        
       //Debug.trace("App.goodActivated");         

        //Positionnement de la popup
        if( App.hasSmallPopup ) {
            App.popup.setPosition(); //triggera popupPlaced
        }
 /*       
        //si on a une bigMap, on place le marker au top
        if ( App.hasBigMap ) {
            App.bigMap.placeTopMarker(ID);
        }
 */       
        

    },
    
    goodAlreadyActivated: function(obj) {
        //est déclanché quand le bien est déjà activé
    
       //Debug.trace2("App.goodAlreadyActivated: " + obj.no);
        //Debug.count("Already Activated");
        
        //pour l'instant, on fait pareil...
        App.goodActivated(obj);
    },
    
    popupPlaced: function() {
        //est lancé par le popup une fois qu'il est placé
        
       //Debug.trace2("App.popupPlaced started"); 
        
        //une fois que le popup est placé, on l'affiche
        if( App.hasSmallPopup ) {
            App.popup.show();
        }
        
    },
    
    popupShowed: function(ID) {
        //Est lancé par le popup une fois qu'il est affiché
        
       //Debug.trace2("App.popupShowed: " + ID); 
        //Debug.stopSpy("Activate");
        //Debug.displaySpies();
    },
    
    popupHidden: function(ID) {
        //est lancée par le popup une fois qu'il s'est masqué
        
       //Debug.trace("App.popupHidden: " + ID);
    },
    
    outOfList: function() {
        //est trigggé par la fin du hover sur la liste de biens
        
       //Debug.trace("App.outOfList started");
        //Debug.count("App.outOfList");
        //Debug.displaySpies();

        //on annule la sélection du bien (pour qu'on puisse passer très vite sur la liste sans que tout bouge)
        App.goods.clearSelectTimer();
        
        //on ferme la popup
        if( App.hasSmallPopup ) {
            App.popup.hide();
        }
        
    },
    
    mapReady: function() {
        //est déclanché par la carte lorsqu'elle est prête
        
       //Debug.trace("App.mapReady started"); 
        //Debug.count("mapReady");

    },
    
    mapMoveStart: function() {
        //est déclanché par la map AVANT le déplacement
        
        //SERT A RIEN
    
       //Debug.trace3("App.mapMoveStart started"); 
        //Debug.count("mapMoveStart");
        
        //Rechargement des biens
        //App.mapChanged(); 
        
        //Debug.displayMapInfo();
        
        

    },
    
    mapChanged: function() {
        //Déclanché par la fonction resize (entre autre)
        
       //Debug.trace("App.mapChanged started");
        //Debug.count("App.mapChanged");
        
        //on repositionne les éléments INUTILE????
        App.placeElements();
        
        //Vérifier si la map a vraiment étée redimentionnée!! (IE 6 déconne avec ca...)
        //INUTILE?? on vérifie déjà si la fenêtre à vraiment étée redimentionnée...
        App.bigMap.onResize();
        App.bigMap.calculateNeSw();
        //Debug.displayMapInfo();
        
       //Debug.trace3("-o-ne " + App.bigMap.oldNe );
       //Debug.trace3("-n-ne " + App.bigMap.ne );
       //Debug.trace3("-o-sw " + App.bigMap.oldSw );
       //Debug.trace3("-n-sw " + App.bigMap.sw );
       //Debug.trace3("-o-zoom " + App.bigMap.oldZoom );
       //Debug.trace3("-n-zoom " + App.bigMap.zoom );
        
        //on regarde si on a fait un zoom
        var zoomOut = false;
        var zoomIn = false;
        
        if( App.bigMap.oldZoom < App.bigMap.zoom ) {
           //Debug.trace3("- zoomIn -> true");
            zoomIn = true;
        }
        
        if( App.bigMap.oldZoom > App.bigMap.zoom ) {
           //Debug.trace3("- zoomIn -> true");
            zoomOut = true;
        }
                
        
        
        App.bigMap.oldZoom = App.bigMap.zoom;
        
        
        if( ( App.bigMap.oldSw == App.bigMap.sw ) && ( App.bigMap.oldNe == App.bigMap.ne ) ) {
            
           //Debug.trace("- map NOT resized !!!");
            //Debug.count("resize NOT validated");
            //Debug.displaySpies();
        
        } else {
        
           //Debug.trace("- resize validated");
            //Debug.count("resize validated");
            //Debug.displaySpies();
            
            App.bigMap.oldSw = App.bigMap.sw;
            App.bigMap.oldNe = App.bigMap.ne;
        
            App.onMapReallyChanged();
            
        }
    },
    
    onMapReallyChangedOLD: function() {
        
       //Debug.trace2("App.onMapReallyChanged");
                       
        if(App.ready) {
            
           //Debug.trace("- App is ready");
            
            //Si les coordonnées de la carte sont en dehors des coordonnées des biens, on recharge. Sinon, on lance uniquement un refresh de la liste

            //si on a forcé le reload au zoom in et qu'on a un zoomIn ou que la carte n'est plus dans la zone
            if( ( App.reloadOnZoomIn && zoomIn ) || ( !App.bigMap.onGoods() ) ) {
               //Debug.trace2("- Out of zone -> reload");                
                //Rechargement des biens
                
                App.reloadGoods();
                
            } else {
                
                //alert("refresh");
            
               //Debug.trace2("- Abort");
                //Debug.count("Map Zone on Goods zone");
                //Debug.displaySpies();
                App.refreshGoods();
            }
          
        }
   
    },
    
    onMapReallyChanged: function() {
       //Debug.trace2("App.onMapReallyChanged");    
        
        //on ne fait rien sur la carte parceque tous les biens sont chargés... Le marker manager gérera tout seul
        
        //on met à jour la liste, car elle peut changer en fonction des biens affichés sur la map
        
        App.updateListOnMapChanged();
        //alert("onMapReallyChanged");
        
        
    },
    
    mapMoveEnd: function() {
        //est déclanché par la carte lorsque le move est terminé
        
       //Debug.trace("App.mapMoveEnd started"); 
        
        if(App.ready){

            //Debug.count("mapMoveEnd Ready");
            
            //on recalcule la postion de la map
            //App.bigMap.calculateNeSw();
            
            // on recharge tous les biens
            //App.reloadGoods();
            App.mapChanged();
            
            /*
            if( App.hasSmallPopup ) {
                App.popup.hide();
            }
            */
            
        } else {
        
            //Debug.count("mapMoveEnd NOT Ready");
            
        }
        
    },
    
    mapZoomEnd: function() {
       Debug.trace2("App.map.ZoomEnd");
       Debug.trace(App.bigMap.map.getZoom() + " max: " + App.bigMap.maxZoom);
       App.bigMap.checkMaxZoom();
    },
    
    mapMouseOver: function(obj) {
        //est déclanché par un mouseover sur un des biens sur la carte
        
       //Debug.trace2("App.mapMouseOver started: " + obj); 

        //on met en place le point bleu!
        //si on a une bigMap, on place le marker au top
        if ( App.hasBigMap ) {
            App.bigMap.placeTopMarker(obj);
        } /* else ca devrait jamais arriver!! */
        
    },
      
    mapTopMarkerMouseOver: function(obj) {
       //Debug.trace2("App.mapTopMarkerMouseOver " + obj.no);
        //alert("over");
        App.selectGoodImmediate(obj);
    },
    
    mapMouseOut: function() {
        //est déclanché par un mouseout sur un des biens de la carte
        
       //Debug.trace2("App.mapMouseOut started"); 
        
    },
    
    mapTopMarkerMouseOut: function() {
        //mouse out du topMarker
        
        if( App.hasSmallPopup ) {
            App.popup.hide();
        }
        
    },
        
    mapMouseClick: function(obj) {
        //est déclanché par un click sur un marker de la carte
        
       //Debug.trace("App.mapMouseClick: " + obj.no);
        
        App.showDetails(obj);
    },
    
    moveToolsUsed: function(T) {
       //Debug.trace2("App.moveToolsUsed");
        
        //alert(T);
        
        //on repasse en mode utilisateur normal
        App.normalUser();
        
        //panDirection(dx,  dy) +1 is right and down, -1 is left and up
        
        switch( T ) {
        
            case "TL":
                App.bigMap.map.panDirection( 1 , 1 );
                break;
            case "T":
                App.bigMap.map.panDirection( 0 , 1 );
                break;
            
            case "TR":
                App.bigMap.map.panDirection( -1 , 1 );
                break;
                
            case "CL":
                App.bigMap.map.panDirection( 1 , 0 );
                break;
            
            case "CR":
                App.bigMap.map.panDirection( -1 , 0 );
                break;
                
            case "BL":
                App.bigMap.map.panDirection( 1 , -1 );
                break;
                
            case "B":
                App.bigMap.map.panDirection( 0 , -1 );
                break;
            
            case "BR":
                App.bigMap.map.panDirection( -1 , -1 );
                break;
                
            
            
            case "C":
                App.bigMap.map.returnToSavedPosition();
                break;
                
            case "ZI":
                App.bigMap.map.zoomIn();
                break;
                
            case "ZO":
                App.bigMap.map.zoomOut();
                break;
                
            case "ZL":
                App.bigMap.centerOnBounds();
                break;
                
        }
        
    },    
    
    mapGoodsDisplayed: function() {
        //est renvoyé par la map une fois que les biens sont chargés
        
       //Debug.trace("<strong>App.mapGoodsDisplayed</strong>");
        ////////////////////////////
        App.removeLoader();
    }, 
    
    sliderMoved: function() { //INUTILE
        //est déclanché par un mouvement d'un slider
        
       //Debug.trace3("App.sliderMoved");
        
        if(App.ready) {
            //App.searchToolUsed();
        }
    },
    
    inputChanged: function(slider) {
        alert(slider + " input changed");
    },
       
    searchToolUsed: function() {
       //Debug.trace2("App.searchToolUsed"); 
        
        //Les critères de sélection ont probablement bougé, on lance une resélection des biens
        
        App.goods.selectGoods();
        
        //alert("searchToolUsed");
    },
    
    limiterResetClick: function() {
       //Debug.trace2("App.limiterResetClick");
        //alert("reset");
        SearchTools.resetForm();
        App.searchToolUsed();
    },
    
    ongletClicked: function( id ) {
        //Est triggé par un click sur un des onglets du sélecteur de type de biens (tous, a louer, a vendre, promotions)
        
       Debug.trace2("App.ongletClicked: " + id);
        
        //alert("click " + id);
        
        
        //on ferme la popup
        if( App.hasSmallPopup ) {
            App.popup.hide();
        }
        
        //on affiche le loader
        App.displayLoader();
        
        
        App.tmp = id;
        
        //Debug.stop("test");
        
        setTimeout("App.ongletClickedSuite()", 10 );

       
    },
    
    ongletClickedSuite: function() {
       //Debug.trace2("App.ongletClickedSuite");

        var id = App.tmp;

        //on recalcule goods.genreSelected en fonction du bouton cliqué
        
        switch( id ) {
            
            case "btn-accueil":  
                
                App.bigMap.maxZoom = App.bigMap.maxZoomVente;
                App.goods.setGenre("ALL");
                //alert("blabla tous");
                App.setHash("accueil");
                break;

            case "btn-a-louer":
                App.bigMap.maxZoom = App.bigMap.maxZoomAutre;
                App.goods.setGenre("LOC");
                App.setHash("a-louer");
                //alert("blabla loc");
                break;
                
            case "btn-a-vendre":
                App.bigMap.maxZoom = App.bigMap.maxZoomVente;
                App.goods.setGenre("VENTE");
                App.setHash("a-vendre");
                break;            
            
            case "btn-sur-plan":
                App.bigMap.maxZoom = App.bigMap.maxZoomAutre;
                App.goods.setGenre("PROMO");
                App.setHash("sur-plan");
                //alert("A FAIRE");
                //return false;
                break;
            
        }
        
        App.detectHome();
        
        //pour afficher la page correcte
        App.placeElements();
        
        SearchTools.resetForm();

        
        //Affichage des bons éléments dans le moteur de recherche
        SearchTools.placeElements();
        
        
        App.searchToolUsed();

        
    },
    
    setHash: function(hash) {
       //Debug.trace2("App.setHash");
        this.stopHashTimer();
        location.hash = hash;
        App.hash = hash;
       //Debug.trace2("--> " + App.hash);
        App.startHashTimer();
    },
    
    getHash: function() {
       //Debug.trace2("App.getHash");
        var hash = location.hash.replace(/#/, "");
        hash = hash.replace(/%20/, " ");
        return hash;
    },
    
    _checkHashChange: function() {
        //// /*Debug.trace2("App._checkHashChange");*/
        var new_hash = location.hash.replace(/#/, '');
        if( location.hash.replace(/#/, '') != App.hash) {
            //alert("hash changed");
           //Debug.trace("!!!HASH CHANGED!!! : " + App.hash + " : " + new_hash);
            App.hash = new_hash;
            App.init();
           
            //App.init();
        }
    },
    
    startHashTimer: function() {
       //Debug.trace2("startHashTimer");
        //DETECTION DU CHANGEMENT DE HASH
       //Debug.trace2("***DESACTIVE***");
        this.hashTimer = setInterval(this._checkHashChange, 100);
    },
    
    stopHashTimer: function() {
       //Debug.trace2("stopHashTimer");
        clearInterval(this.hashTimer);
    },
    
    tagCloudClick: function(id) {
        
        Debug.trace2("App.tagCloudClick: " + id);
        
        //alert("click : " + id);
        
        //on positionne sur le bon onglet
        
        if ( id.indexOf("LOC") == 4 ) { //format id: tag-LOC-APP
            //alert("LOC");
            
            //on sélectionne le type de bien.
            var t = id.substr( 8 , id.length );
            //alert(t);

            SearchTools.resetForm();
            SearchTools.uncheckAll();
            
            //on coche le bon élément
            ce("#checkbox-" + t).check();
            
            
            //on bloque le prochain reset du formulaire
            SearchTools.blockNextReset = true;
            
            //on fait croire au click sur l'onglet

            ce("#btn-a-louer").parent().click();

        }
        
        if ( id.indexOf("VENTE") == 4 ) { //format id: tag-VENTE-APP
        
        
            //on sélectionne le type de bien.
            var t = id.substr( 10 , id.length );
            //alert(t);
            
            SearchTools.resetForm();
            //On décoche tout
            SearchTools.uncheckAll();
            
            //on coche le bon élément
            ce("#checkbox-" + t).check();
        
            //on bloque le prochain reset du formulaire
            SearchTools.blockNextReset = true;
            
            //on fait croire au click sur l'onglet
            ce("#btn-a-vendre").parent().click();
        }

        if ( id.indexOf("PLAN") == 4 ) { //format id: tag-PLAN-APP
        
        
            //on sélectionne le type de bien.
            var t = id.substr( 9 , id.length );
            //alert(t);
            
            SearchTools.resetForm();
            //On décoche tout
            SearchTools.uncheckAll();
            
            //on coche le bon élément
            ce("#checkbox-" + t).check();
        
            //on bloque le prochain reset du formulaire
            SearchTools.blockNextReset = true;
            
            //on fait croire au click sur l'onglet
            ce("#btn-sur-plan").parent().click();
        }


        
        
    
    },
    
    mainSearchSelectorUsed: function() {
        //est déclanché quand on a cliqué sur un des boutons à louer, à vendre
        
       //Debug.trace("App.mainSearchSelectorUsed"); 
        
        App.placeElements();
        App.searchToolUsed();
    },
    
    unLoad: function() {
        //au déchargement de la page...
    
       //Debug.trace("App.unLoad started"); 
        GUnload();
    },

    windowOnload: function() {        
       //Debug.trace("App.windowOnload started"); 
    },
    
    infosDisplayed: function() {
       //Debug.trace2("App.infoDisplayed");
        
        App.placeElements();
    },
    
    placeElements: function() {
    
        //repositionne les éléments de la fenêtre
        
       //Debug.trace("App.placeElements");
        //Debug.count("App.placeElements");
        //Debug.displaySpies();
        
        
        
        
        if( App.home ){
            App.showHome();
        } else {
            App.hideHome();
        }
        
        
        
        //Agrandissement des div qui ont la class resize
        
        //recherche de la hauteur de la fenêtre
        tailleFenetre = e['window'].height();
        //recherche de la position du scroll (pour adapter la taille du box
        scrollTop = e['document'].scrollTop();
        
        //Debug.stop("tailleFenetre: " + tailleFenetre);
        
        
       //Debug.trace3("- tailleFenetre: " + tailleFenetre);
       //Debug.trace3("- scrollTop: " + scrollTop);
        
        //ce("div.resize").each( function() {

          //  hautBox = $(this).offset().top;

           // hauteur = tailleFenetre - hautBox - 10 + scrollTop;
        
            //$('#debug').html('tailleFenetre : '+tailleFenetre+'<br>scrollTop : '+scrollTop+'<br>hautBox : '+hautBox+'<br>hauteur : '+hauteur);
            //this.style.height = hauteur + 'px';
            //$(this).height( hauteur + 'px');
            //alert(hauteur);
         

            
        //});

        //127
        ce('#container32').height(e['window'].height() - 137 + 'px');
        
        
        //redimentionnement du loader
        //275
        ce('#mainLoader').height(e['window'].height() - 285 + 'px');
        
        
        /* INUTILE SI ON AFFICHE PAS LES BOUTONS DE GAUCHE */
        //Adaptation de la taille des boutons de gauche en fontion de la hauteur du topBox
        //recherche de la hauteur du topBox
        
        /*
        topBoxHeight = $("#topBox").height();
        aHeight = (topBoxHeight-1)/3-8;
        aHeightLast = aHeight - 9;
        aHeight = aHeight+"px";
        aHeightLast = aHeightLast+"px";
        $("#menu a").css("min-height",aHeight);
        $("#menu .last a").css("min-height",aHeightLast);    
        */
    
        //position du gMapLoader
        
        /*
        if( App.hasBigMap ) {
            //recherche de la largeur du loader
            var largeurLoader = ce("#gMapLoader").width();
            //recherche le la largeur de la map
            var largeurMap = ce('#gMap').width();
            //recherche de la hauteur du loader
            var hauteurLoader = ce("#gMapLoader").height();
            //recherche de la hauteur de la map
            var hauteurMap = ce('#gMap').height();
            
            //calcul de la position top left en conséquence
            var left = (largeurMap - largeurLoader) / 2;
            var top = (hauteurMap - hauteurLoader) / 2;
            
            //attribution de la position
            ce("#gMapLoader").css("top", top);
            ce("#gMapLoader").css("left", left);
            
            
            
        }
        */
    
    

    },
    
    showHome: function() {
       //Debug.trace("App.hideHome");
        ce("#homeDiv").show();
        ce('#tableBiens').hide();
        ce("#info").hide();
        ce("#searchContainer").hide();
    },
    
    hideHome: function() {
       //Debug.trace("App.hideHome");
        ce("#homeDiv").hide();
        ce('#tableBiens').show();
        ce("#info").show();
        //remise en place du searchContainer
        ce("#searchContainer").addClass("visible");
        ce("#searchContainer").show();
    },
    
    resize: function() {
        //Appellé au resize de la fenêtre
        
       //Debug.trace("App.resize started");   
        
        //BUG : verifier si l'application a vraiment étée redimentionnée à cause d'IE 
        var h = e['window'].height();
        var w = e['window'].width();
        
       //Debug.trace2( "- width: "+ App.oldWidth + " -> " + w);
       //Debug.trace2( "- height: " + App.oldHeight + " -> " + h);
    
        //Debug.startSpy("* App.resize *");
        
        if( ( h == App.oldHeight ) && ( w == App.oldWidth ) ) {

           //Debug.trace2("App.resize: WRONG RESIZE");
            //Debug.count("WRONG RESIZE");
            //Debug.displaySpies();
            //on fait quand même un placeElements...
            //App.placeElements();
            
        } else {

           //Debug.trace2("App.resize: TRUE RESIZE");
            //Debug.count("TRUE RESIZE");
            //Debug.displaySpies();

            //on mémorise la taille
            App.oldHeight = h;
            App.oldWidth = w;
              
            if(App.ready) {
                
               //Debug.trace2("- App is ready");
                
                //on temporise le mapResized pour pas en faire milles d'un coups
                
                clearTimeout( App.mapResizeTimer);
                
                //Debug.count("SetTimer: mapChanged");
                
                App.mapResizeTimer = setTimeout ( "App.mapChanged()" , App.mapResizeDelay ) ;
                
                
            } else {
                
               //Debug.trace2("- App is NOT ready"); 
            
            }

        }
        


        
        
        //Debug.stopSpy("* App.resize *");
        //Debug.displaySpies();

    },
    
    doOnScroll: function(data) {
        //Action à effectuer au scroll de la fenêtre
        //BUG : ATTENTION safari et chrome vont renvoyer un scroll au scroll d'un div interne!!!
        
        if(!App.safari){
            
           //Debug.trace2("App.doOnScroll started");
            
            this.resize();
        } else {
        
           //Debug.trace("<strong>Browser is safari: doOnScroll disabled</srong>");
        
        }
        
        //Debug.count("App.doOnScroll");

        
    },
    
    doOnResize: function() {
        //A faire au redimentionnement de la fenêtre
        
        //alert("do onresize");
        
       //Debug.trace2("App.doOnResize started"); 
        //Debug.count("App.doOnResize");    
        
        //ATTENTION NE PAS RECHARGER QUAND ON A PAS DE BIGMAP??
    
        this.resize();
        
        /*
        if(App.ready) {
            
            //Rechargement des biens
            App.reloadGoods(); 
        }
        */
        
    },
    
    showAddress: function(address) {
        //recentre la map sur l'adresse sélectionnée
        
       //Debug.trace("App.showAddress started"); 
        //METTRE CA PLUTOT DANS CARTE
        
        if (App.bigMap.geocoder) {
            App.bigMap.geocoder.getLatLng(
                address,
                function(point) {
                    if (!point) {
                        alert(address + " not found");
                    } else {
                        App.bigMap.map.setCenter(point);
                        var marker = new GMarker(point);
                        App.bigMap.map.addOverlay(marker);
                        marker.openInfoWindowHtml(address+" "+point);
                    }
                }
            );
        }   
    },
    
    spiesClick: function() {
        
        //Debug.spies = {};
        //Debug.counters = {};
        //Debug.startSpy("total");
        ////Debug.count("manual refresh");
       //Debug.displaySpies();
        
    },
    
    menuOpen: function(m) {
       //Debug.trace("App.menuOpen " + $(m).attr('id') );
        //alert(m);
        App.setHash( "m" + $(m).attr('id') );
    },
    
    afficherToutClick: function() {
       //Debug.trace2("App.afficherToutClick");
        
        if( App.hasBigMap) {
            App.bigMap.centerOnBounds();
        }
        
    }
    
};

function Goods() {
    //Constructeur
    
   //Debug.trace("Goods Constructor Called");
    
    this.dataCache = null; //Liste des biens INUTILE
    this.linesBKP = []; //backup de la liste des biens
    this.nbLoad = null; //Nombre de fois que les biens ont étés chargés
    this.total = null; //Nombre total de biens
    this.totalLoc = 0; //Nombre de biens en location
    this.totalVente = 0; //Nombre de biens à la vente
    this.totalPromo = 0; //Nombre de biens en promotion
    this.typesLoc = [];
    this.typesVente = [];
    this.typesPromo = [];
    this.found = null;
    this.displayed = null;
    
    this.nbGoodsOnTheMap = 0; //nombre de biens sur la carte (calculé par la liste)
    
    this.sort = null; //ordre actuel de tri
    
    this.showPSD = true; //afficher les prix sur demande
    this.showOnlyMeuble = false; //N'afficher que les biens meublés
    this.prixMin = 0;
    this.prixMax = Number.MAX_VALUE;
    this.loyerMin = 0;
    this.loyerMax = Number.MAX_VALUE;
    this.piecesMin = 0;
    this.piecesMax = Number.MAX_VALUE;
    this.surfaceMin = 0;
    this.surfaceMax = Number.MAX_VALUE;
    
    
    
    this.nbSelected = 0; 
    
    this.idInt = []; //id des biens qui ont étés marqués //INUTILE
    
    this.timer = null; //Timer pour la requête ajax
    this.delay = 100; //temporisation avant d'aller chercher les données [ms]
    
    this.timer2 = null; //Timer pour la sélection du bien
    this.delay2 = 20;
    
    this.active = null; //bien actif
    
    this.icons = {};
    this.iconPref = {w: 21, h: 21, ax: 11, ay: 11};
    this.GENRES = ["LOC", "VENTE", "PLAN"];
    this.TYPES = ["APP", "APM" , "MAI", "TER", "PAR", "LCO", "IMM"];
    
    this.genreSelected = "ALL";
    this.oldGenreSelected = null; //ancien genre sélectionné INUTILE??
    
    //Uniquement pour MapIconMarker //INUTILE
    this.GENRESCOLORS = { LOC: "#FFFF00", VENTE: "#FF6600", PLAN: "#0000FF", DEFAULT: "#FF00FF" };
    this.GENRESSHAPES = { LOC: "circle", VENTE: "roundrect", PLAN: "roundrect", DEFAULT: "circle" };
    
    
    this.mapMarkers = [];
    
    this.infoPlace = "#info"; //endroit ou seront affichées les infos.
    
    this.oldU = null; //Pour mémoriser la requête précédente et ignorer si c'est la même
    
    /* Coordonnées entre lesquelles se trouvent les biens */
    this.s = null;
    this.n = null;
    this.e = null;
    this.w = null;
    this.offset = 1; //extention de la zone d'affichage (1 = 100% dans tous les sens -> 9x )
    
    /* pour la recherche*/
    //this.affiner = false;
    //this.affinerPlus = false;
    
    
     
}
Goods.prototype = {
    
    init: function() {
        //initialisation des biens
        
       //Debug.trace("Goods.init started");
        //Debug.count("Goods.init");
        
        this.initIcons();

        App.goodsInitialized();
    },
    
    setGenre: function(genre) {
       //Debug.trace2("Goods.setGenre: " + genre);
        this.genreSelected = genre;
    },
    
    loading: function() {
        //Affichage du message de loading des biens
    
       //Debug.trace2("Goods.loading displayed");
        
        ce(this.infoPlace).html("Chargement...");        
    },
    
    displayInfos: function() {
       //Debug.trace2("Goods.displayInfos");
        
        //var html= "map: " + this.nbGoodsOnTheMap + " - list: " + App.list.nbRows + " - sel: " + this.nbSelected + " - total: ";
        
        var html = ['<span class="nbResult">' , this.nbSelected , ' biens</span> trouvés' ] ;
        if (this.nbSelected != this.nbGoodsOnTheMap)
            html.push( ' et <span class="nbResult">' , this.nbGoodsOnTheMap , '</span> affichés sur la carte') ;
        html.push('.');
        /*
        switch( this.genreSelected) {
        
            case "LOC" :
                html += this.totalLoc;
                break;
                
            case "VENTE" :
                html += this.totalVente;
                break;

            case "PROMO" :
                html += this.totalPromo;
                break;
            
        }
        */
        
        //INTERNATIONALISER
        // quand les deux sont égaux, ne mettre que la première partie de la carte...
        
        ce(this.infoPlace).html(html.join(''));

    },
        
    clearSelectTimer: function() {
        //Annulation du timer de sélection du bien
    
       //Debug.trace2("Goods.clearSelectTimer started");    
        
        if(this.timer2){
            clearTimeout(this.timer2);
        }
    },
    
    markGood: function(ID) {
        //marque un bien
        
       //Debug.trace2("Goods.markGood: " + ID);
        
        this.dataCache[ID].mark();
    },
    
    unMarkGood: function(ID) {
        //démarque un bien
        
       //Debug.trace2("Goods.unMarkGood: " + ID);
        
        this.dataCache[ID].unMark();
    },
    
    select: function(obj) {
        //Sélectionne un bien après un certain délais
    
       //Debug.trace2("Goods.select started: " + obj.no);
      
        //Temporisation...
        //this.clearSelectTimer();
        var me = this;
        //var code = "me.selectNow(" + ID + ")";
        
        //Debug.count("SetTimer: selectNow");
        
        //this.timer2 = setTimeout( function() {
            me.selectNow(obj);
        //}, this.delay2 ); 
        

    },
    
    selectNow: function(obj) {
        //Sélectionne un bien immédiatement
    
       //Debug.trace("Goods.selectNow started: " + obj.no);
        
        if( this.active === obj ) { // Si le bien est déjà sélectionné
            App.goodAlreadyActivated(obj);
        } else {        
            
            if( this.active != null) {
                //this.dataCache[this.active].desactivate();
                this.active.desactivate();
            }
            
            this.active = obj;
            
            //Lance la procédure d'activation du bien
            //this.dataCache[this.active].activate();
            obj.activate();
        }
        
    },
    
    searchID: function(id) {
        
       //Debug.trace2("Goods.searchID: " + id);
        Debug.startSpy("searchID");
        //renvoie l'objet qui à l'id id
        var found = null;
        $(this.linesBKP).each(function(i,l) {
           //Debug.trace3(l.id + " " + id);
            if(l.id == id) {
                //alert("FOUND");
               //Debug.trace2("--> found");
                found = this;
                //return this;
            }
        });
        //alert("not found");
        Debug.stopSpy("searchID");
        return found;
        
    },
    
    getAllGoodsFromServer: function() {
       //Debug.trace("Goods.getAllGoodsFromServer");
        
        var u = document.location.protocol + '//' + document.location.host + '/fr/ajax/getObjects';
        
        $.getJSON(u, {}, function(data) {
            //me.linesBKP = data.lines.slice();
           //Debug.trace("**DATA RECEIVED**");
            App.allGoodsLoadedFromServer(data);
        });
        
        
    },
    
    firstGoodsTreatment: function(data) {
       //Debug.trace("Goods.firstGoodsTreatment");
        Debug.startSpy("firstGoodTreatment");
        //alert("firstGoodTreatment");
        
        
        //Debug.startSpy("firstGoodTreatment");
        
  
        
        
        //on plante tous les biens dans dataCache
        this.linesBKP = data.lines;
       
        //LIMITATION
        if ( LIMIT != 0 ) {
            this.linesBKP.length = LIMIT;
           //Debug.trace("** nb goods limited to: " + LIMIT + " **");
        }        

        
        //var t1 = new Date();

        this.total = data.total;
        this.found = data.found;
        this.totalVente = data.vente
        this.totalLoc = data.loc
        this.totalPromo = data.promo
        this.displayed = data.displayed;
        this.totalVente = 0;
        this.totalLoc = 0;
        this.totalPromo = 0;

        //var t2 = new Date();
        
        //Debug.stop( t2 - t1 );
        
        //on sépare les biens trop proches
 
        var me = this;
     
     
        
  
        /* jusque la : 0ms IE6 */
  
        $.each(this.linesBKP, function(i, b) {
            
            //Décalage des biens qui sont à la même place...
            
            //on recherche dans tous les biens qui suivent s'il y en a qui ont la même lat
            ////Debug.trace3("- Detecte empliage");

            /*
            //FAIRE FAIRE CA AU SERVEUR!!
            for (y = ( i + 1 ) ; y < me.total ; y++) {
                if(me.linesBKP[i].lat == me.linesBKP[y].lat ) {
                    ////Debug.trace3("-- Same lat");
                    //on vérifie si on a la même longitude
                    if(me.linesBKP[i].lng == me.linesBKP[y].lng ) {
                        ////Debug.trace3("-- Same lng");
                        ////Debug.trace3("*** déplacer le point ***");
                        ////Debug.trace3(i + "=" + y + ": " + me.linesBKP[y].lng );
                        var newLng = parseFloat(me.linesBKP[y].lng) + 0.0005;
                        me.linesBKP[y].lng = newLng.toString();
                        ////Debug.trace3("-> " + me.linesBKP[y].lng );
                    } else {
                        ////Debug.trace3("-- Diffent lng -> abort");
                    }
                } else {
                    ////Debug.trace2("- " + y + " ok");
                }
            }
            
            */
            


            //Le bien est tout seul sur sa position, on peut l'initialiser
            
            
            //résolution du problèmes du nombres de pières pour ne plus afficher 3.0 pièces...
            
/*
            if( this.nb_pieces == Math.ceil( this.nb_pieces ) ) {
                this.nb_pieces = Math.ceil( this.nb_pieces ) ;                    
            }
*/
            
            
            //comptage (les biens sont soit en vente soit en location)

            
            if(this.genre == "VENTE") {
                //me.totalVente ++ ;
                //recherche des types
                if( $.inArray( this.type , me.typesVente ) == -1 ) {
                    me.typesVente.push(this.type);
                }
                
            } else { // Location
                //me.totalLoc ++;
                if( $.inArray( this.type , me.typesLoc ) == -1 ) {
                    me.typesLoc.push(this.type);
                }
                
            }
            
            //comptage des promos
            
            if(this.promo) {
                //me.totalPromo ++;
                
                if( $.inArray( this.type , me.typesPromo ) == -1 ) {
                    me.typesPromo.push(this.type);
                }
                
                
            };
            

        
            b.no = i;
            
            // Jusque la: 93 ms IE6 
            
            
            b = $.extend(b, Good.prototype); //80ms
            //Good.call(this); //Inutile (y'a rien dans le goodConstructor)
            
            //mise en cache de l'icône
            this.icon = this.returnIcon();
            
            //Création du marker
            //this.createMapMarker3(); //200ms
            //on va faire ca plus tard quand on connaitra la priorité...

            //Création de la ligne de liste
            this.li = this.getLi(); //300ms
            //this.row = $('#' + this.getRowID());
            
            this.dst = 10000000; //on fixe une distance très loin du centre...
            
            //Reformatage de certains éléments
            //if(this.prix == null) {this.prix = 0;}
            //if(this.loyer == null) {this.loyer = 0;}
            //this.prix = parseFloat(this.prix);
            
            //if(this.promo == "f"):
            
            //if(this.psd == "f") {this.psd = false} else {this.psd = true};
            ////Debug.trace3(this.no + " prix: " + this.prix + " loyer: " + this.loyer + " " + this.psd);
            
            /*if(this.genre == "LOC") {
                this.montantNum = parseFloat(this.loyer);
            } else { //VENTE
                this.montantNum = parseFloat(this.prix);
            }*/
            
            this.surface = parseFloat(this.surface); //A FAIRE SUR LE SEVEUR!
            this.nb_pieces = parseFloat(this.nb_pieces);
            
            
            /* Attribution de la priorité pour l'affichage */
            //si c'est un parking, on lui met une priorité 10 autrement 20
            
            if (this.type == "PAR") {
                this.priority = 100;
            } else {
                this.priority = 0;
            }
            
            
            
        });
        
        //on trie par priorité et on crée les markers
        
        this.sortBy('priority');
        
        $.each(this.linesBKP, function(i, b) {
            //Debug.trace2(this.type);
            this.createMapMarker3(); //200ms    
        });
        
        
  
 
        //alert(this.typesVente);
        //alert(this.typesLoc);
        //alert(this.typesPromo);
        
        //Les biens sont initialisés et sont dans linesBkp  
       
        
        
        //Debug.stopSpy("firstGoodTreatment");
        //Debug.displaySpies();
       //Debug.trace("-- done");
        

        
        Debug.stopSpy("firstGoodTreatment");
        
        App.firstGoodsTreatmentDone();
        
    },
    
    selectGoods: function() {
       //Debug.trace("Goods.selectGoods");
        //Debug.startSpy("selectGoods");
        //on va récupérer les valeurs des champs de sélection
        
        Debug.startSpy("selectGoods");
        
        //si on est sur la page d'accueil, on ne filtre rien!!
        if(App.home) {
            //on met selected à tous les biens!
            $(this.linesBKP).each( function() {
                this.selected = true;
            });
   
        } else {
        
            //on cherche s'il faut afficher les prix sur demande.
            var label = "prixSurDemande";
            
            switch( this.genreSelected ) {
                
                case "VENTE": case "PROMO":                
                   //Debug.trace2("- VENTE ou PROMO");
                    break;
                    
                case "LOC":
                    label = "loyerSurDemande";
                    break;
            
            }
            
            if(  $("#" + label + ":checked").length == 1 ) { //POSSIBLE DE METTRE EN CACHE???
                this.showPSD = true;
                //Debug.count("showPSD");
            } else {
                this.showPSD = false;
                //Debug.count("hidePSD");
            }
            
            //on recherche s'il ne faut afficher que les meublés
            /* SE FAIT AVEC APM A LA PLACE DE APP
            if( $("#showOnlyMeuble:checked").length == 1) {
                this.showOnlyMeuble = true;
            } else {
                this.showOnlyMeuble = false;
            }
            */
            
            //Récupération des limites de prix
            this.prixMin = $.fn.extractNumber( ce("#prixMin").val() ) ;
            this.prixMax = $.fn.extractNumber( ce("#prixMax").val() ) ;
            this.loyerMin = $.fn.extractNumber( ce("#loyerMin").val() );
            this.loyerMax = $.fn.extractNumber( ce("#loyerMax").val() );

            //Récupération des limites de surface et de pièces
            this.piecesMin = $.fn.extractNumber( ce("#piecesMin").val() ) ;
            this.piecesMax = $.fn.extractNumber( ce("#piecesMax").val() ) ;
            this.surfaceMin = $.fn.extractNumber( ce("#surfaceMin").val() );
            this.surfaceMax = $.fn.extractNumber( ce("#surfaceMax").val() );

           //Debug.trace2("- prixMin: " + this.prixMin);
           //Debug.trace2("- prixMax: " + this.prixMax);
           //Debug.trace2("- loyerMin: " + this.loyerMin);
           //Debug.trace2("- loyerMin: " + this.loyerMax);
           //Debug.trace2("- PSD: " + this.showPSD);            
           //Debug.trace2("- piecesMin: " + this.piecesMin);
           //Debug.trace2("- piecesMax: " + this.piecesMax);
           //Debug.trace2("- surfaceMin: " + this.surfaceMin);
           //Debug.trace2("- surfaceMax: " + this.surfaceMax);

            var me = this;
            
            //on met l'attribut selected aux biens qui correspondent aux critères
            if( this.genreSelected == "PROMO") {
                $(this.linesBKP).each( function() {
                    if( this.promo ) {
                        //bien en promo
                        this.selected = true;
                        //me.nbSelected++;
                    } else {
                        this.selected = false;
                    }
                });
            } else {
            
                $(this.linesBKP).each( function() {
                    if( (this.genre == me.genreSelected) || me.genreSelected == "ALL" ) {
                        //on a le bon genre
                        this.selected = true;
                        //me.nbSelected++;
                    } else {
                        this.selected = false;
                    }
                });
                
            }            
            //mémorisation de l'ancien genre INUTILE??
            this.oldGenreSelected = this.genreSelected;

            
            //On a plus que les biens du genre voulu, maintenant on filtre
            
            
            
            
            //si on n'affiche pas les pris sur demande:
            if( !this.showPSD ){
                //alert("masquer les prix sur demande");
                $(this.linesBKP).each(function() {
                    if (this.psd) {
                        this.selected = false;
                    }
                });
            }
            
            //si on n'affiche pas les non-meublés:
            /* SE FAIT AVEC APM A LA PLACE DE APP
            if( this.genreSelected == "LOC") { //a faire uniquement en mode location
                if( this.showOnlyMeuble ){
                    $(this.linesBKP).each(function() {
                        if (this.meuble == "non" ) {
                            this.selected = false;
                        }
                    });
                }
            }
            */
            
            
            
            //on vire ce qui n'est pas dans la gamme de prix
            
            $(this.linesBKP).each(function() {
                
                switch( this.genre ) {
                
                    case "LOC" : 
                        if( (this.selected) && (!this.psd) && ((this.loyer < me.loyerMin) || (this.loyer > me.loyerMax)) ) {
                           //Debug.trace3(me.prixMin + " " + this.prix + " " + me.prixMax);
                            this.selected = false;
                        }
                        break;
                        
                    case "VENTE" : case "ALL" : 
                        if( (this.selected) && (!this.psd) && ((this.prix < me.prixMin) || (this.prix > me.prixMax)) ) {
                           //Debug.trace3(me.prixMin + " " + this.prix + " " + me.prixMax);
                            this.selected = false;
                        }
                        break;
                
                }
                
            });    
            
            
            //on vire ce qui n'a pas le nombre de pièces correct
            $(this.linesBKP).each(function() {
                if( this.selected && ( (this.nb_pieces < me.piecesMin) || (this.nb_pieces > me.piecesMax) ) ) {
                    this.selected = false;
                //} else {
                   //Debug.trace2("CONSERVE: " + this.surface + " " + this.nb_pieces);
                }
            });            
            
            //surface
            //(this.surface < me.surfaceMin) || (this.surface > me.surfaceMax)
            $(this.linesBKP).each(function() {
                if( (this.surface < me.surfaceMin) || (this.surface > me.surfaceMax) ) {
                   //Debug.trace3("Surface incorrecte: " + this.surface);
                    this.selected = false;
                } else {
                   //Debug.trace3("Surface correcte: " + this.surface);
                }
            });
            
            

            //on filtre en fonction des petits boutons qui ne sont pas sélectionnées
            if( $("#limiter #checkbox-ALL:checked").length == 0 ) { //POSSIBLE DE METTRE EN CACHE??
               //Debug.trace2("********");
                ce("#limiter .checkbox").each(function() {
                   //Debug.trace2( $(this).attr("id") );
                   //Debug.trace2( $(this).val() );
                   //Debug.trace2( $( "#" + $(this).attr("id") + ":checked" ).length );
                    if( $( "#" + $(this).attr("id") + ":checked" ).length == 0 ) { //POSSIBLE DE METTRE CA EN CACHE??
                        var aVirer =  $(this).attr("value");
                       //Debug.trace2( "-remove: " + aVirer );
                            //on traverse la table pour virer tous les biens qui sont du sous-type sélectionné
                            $(App.goods.linesBKP).each(function() {
                                if( this.type == aVirer ){
                                    this.selected = false;
                                }
                            });
                        //alert( $(this).attr("class") ); 
                    }
                   
                });
            }

        }
        Debug.stopSpy("selectGoods");
        

        //Debug.stopSpy("selectGoods");
        //Debug.displaySpies();
        App.goodsSelected();
  
    },
    
    sortBy: function(key) {
       //Debug.trace2("Goods.sortBy" + key);
        //Tri des biens
        
        //Debug.startSpy("Sort Time");
        
        switch(key) {
        
            case "priority":
                this.linesBKP.sort(function(a, b) {
                    //return a.priority - b.priority;       
                    return b.priority - a.priority;       
                });
                break;
            
            case "dst":
                //On trie les bien en fonction de leur distance au centre de la carte
             
                
                //on commence par calculer l'indice iDist pour tous les biens
                //Debug.startSpy("IDIST"); //7 ms IE7

                $(this.linesBKP).each(function() {
                    
                    if( this.selected ) { //pas besoin de calculer si le bien n'est pas sélectionné
                        this.iDist();
                    }
                });
                
                //Debug.stopSpy("IDIST");
                
                //Tri des biens
                //Debug.startSpy("SortIDIST");
                this.linesBKP.sort(function(a, b) {
                    
                    //return a.dst - b.dst;
                    
                    /* prise en compte de la priorité */
                    if ( a.priority == b.priority ) {
                        //Debug.trace2("same priority " + a.priority);
                        
                        return a.dst - b.dst;
                        
                    } else {
                        //Debug.trace2("priority");
                        return a.priority - b.priority;    
                    }
  
                    
                });
                //Debug.stopSpy("SortIDIST");
                
                //Debug.displaySpies();
                
                this.sort = "dst";
                break;
                
            case "priceUp":
                //alert("tri priceUp");
                
                if(this.sort == "priceUp"){
                   //Debug.trace2("-Already sorted by " + key);
                    break;
                }
                
                this.linesBKP.sort(function(a, b) {
                    
                    //return a.montantNum - b.montantNum; //les prix sur demande arrivent en premier...
                    
                    /* Inutile
                    if( a.montantNum == b.montantNum) {
                        ////Debug.trace3(a.no + ":" + a.montantNum + " == " + b.no + ":" + b.montantNum);
                        return 0;

                    }
                    */
                    
                    if( a.psd ) { //prix sur demande...
                        ////Debug.trace3(a.no + ":" + a.montantNum + " <-D  " + b.no + ":" + b.montantNum);
                        return 1;

                    }
                    if( b.psd ) {
                        ////Debug.trace3(a.no + ":" + a.montantNum + " D->  " + b.no + ":" + b.montantNum);
                        return -1;

                    }
                    
                    return a.montantNum - b.montantNum;
                    
                    /* Plus rapide avec la methode de dessus...
                    if( a.montantNum < b.montantNum ) {
                        ////Debug.trace3(a.no + ":" + a.montantNum + " <  " + b.no + ":" + b.montantNum);
                        return -1;

                    }
                    
                    if( a.montantNum > b.montantNum ) {
                        ////Debug.trace3(a.no + ":" + a.montantNum + " >  " + b.no + ":" + b.montantNum);
                        return 1;

                    }
                    */
                    
                });
                
                this.sort = "priceUp";
                /*
                //DEBUG affichage du résultat...
               //Debug.trace2("***PriceUp Sort Result***");
                $(this.linesBKP).each(function() {
                   //Debug.trace2(this.no + ": " + this.montant + " " + this.montantNum + " " + this.genre);
                });
                */
                
                break;
                
            case "priceDown":
                //alert("tri priceUp");
                
                if(this.sort == "priceDown"){
                   //Debug.trace2("-Already sorted by " + key);
                    break;
                }
                
                this.linesBKP.sort(function(a, b) {
                    
                    //return a.montantNum - b.montantNum; //les prix sur demande arrivent en premier...
                    
                    /* Inutile
                    if( a.montantNum == b.montantNum) {
                        ////Debug.trace3(a.no + ":" + a.montantNum + " == " + b.no + ":" + b.montantNum);
                        return 0;

                    }
                    */
                    
                    if( a.psd ) { //prix sur demande...
                        ////Debug.trace3(a.no + ":" + a.montantNum + " <-D  " + b.no + ":" + b.montantNum);
                        return -1;

                    }
                    if( b.psd ) {
                        ////Debug.trace3(a.no + ":" + a.montantNum + " D->  " + b.no + ":" + b.montantNum);
                        return 1;

                    }
                    
                    return b.montantNum - a.montantNum;
                    
                    /* Plus rapide avec la methode de dessus...
                    if( a.montantNum < b.montantNum ) {
                        ////Debug.trace3(a.no + ":" + a.montantNum + " <  " + b.no + ":" + b.montantNum);
                        return -1;

                    }
                    
                    if( a.montantNum > b.montantNum ) {
                        ////Debug.trace3(a.no + ":" + a.montantNum + " >  " + b.no + ":" + b.montantNum);
                        return 1;

                    }
                    */
                    
                });
                
                this.sort = "priceDown";
                /*
                //DEBUG affichage du résultat...
               //Debug.trace2("***PriceUp Sort Result***");
                $(this.linesBKP).each(function() {
                   //Debug.trace2(this.no + ": " + this.montant + " " + this.montantNum + " " + this.genre);
                });
                */
                
                break;                
                
        }
        
        //Debug.stopSpy("Sort Time");
        //Debug.displaySpies();
        
    },
        
    onGoodsModified: function() {
       //Debug.trace2("Goods.onGoodsModified");
       //Debug.trace2("- dataCache.length: " + this.dataCache.length);
        
        this.goodsTreatment();
    },
          
    onGoodsLoaded: function(data) {
        //A faire quand les biens sont chargés
        
       //Debug.trace2("Goods.onGoodsLoaded started");
        
        //on mémorise les lignes
        this.linesBKP = data.lines.slice();
        

    
        //On génére le nuage de tags
        TagCloud.init();

        
        
        this.dataCache = data.lines;
        this.total = data.total;
        this.found = data.found;
        this.displayed = data.displayed;

        this.nbLoad += 1;
        
        this.goodsTreatment();

    },
    
    goodsTreatment: function() { //INUTILE
        
        alert("goodsTreatment utile...");
        //DEPRECIE
        
        alert("Goods.goodsTreatment: depreciated");
        
       //Debug.trace2("Goods.goodsTreatments");
        //Debug.startSpy("goodsTreatments");
        //Debug.displayMapInfo();
        
        this.active = null;
        
        if( App.hasBigMap ) {  
            App.bigMap.biens = [];
            //App.bigMap.bounds = null;
            App.bigMap.bounds = new GLatLngBounds();
            
        }
 
        //Création de tous les objets bien
        var me = this;
        
        $.each(this.dataCache, function(i, b) {
            b.no = i;
            b = $.extend(b, Good.prototype);
            Good.call(this);
            
            
            //Décalage des biens qui sont à la même place...
            
            //on recherche dans tous les biens qui suivent s'il y en a qui ont la même lat
           //Debug.trace3("- Detecte empliage");
            
            for (y = ( i + 1 ) ; y < me.dataCache.length ; y++) {
                if(me.dataCache[i].lat == me.dataCache[y].lat ) {
                   //Debug.trace3("-- Same lat");
                    //on vérifie si on a la même longitude
                    if(me.dataCache[i].lng == me.dataCache[y].lng ) {
                       //Debug.trace3("-- Same lng");
                       //Debug.trace3("*** déplacer le point ***");
                       //Debug.trace3(i + "=" + y + ": " + me.dataCache[y].lng );
                        var newLng = parseFloat(me.dataCache[y].lng) + 0.0005;
                        me.dataCache[y].lng = newLng.toString();
                       //Debug.trace3("-> " + me.dataCache[y].lng );
                    } else {
                       //Debug.trace3("-- Diffent lng -> abort");
                    }
                } else {
                   //Debug.trace2("- " + y + " ok");
                }
            }
            
            b.init();
            
            
            
        });
        //Debug.stopSpy("goodsTreatments");
        //Debug.displaySpies();
        if( App.hasSmallList ) {
            App.list.createTable();
        }
        


        App.goodsReady();
        
  
    },
               
    getTotal: function() {
        //retourne le nombre total de biens

       //Debug.trace2("Goods.getTotal started");
    
        return this.total;
    },
    
    initIcons: function() {
        //initialise les icônes
    
       //Debug.trace("Goods.initIcons started");
        me = this;
        
        
        //Version avec les images de Remo
        $.each(me.GENRES, function (ix, g) {
            me.icons[g] = {};
            $.each(me.TYPES, function (ix2, t) {
               
                //création de l'icône normale
                var i = new GIcon();
                i.image = "images/static/" + g + "-" + t + ".png";
                i.iconSize = new GSize(me.iconPref.w, me.iconPref.h);
                i.iconAnchor = new GPoint(me.iconPref.ax, me.iconPref.ay);            
                me.icons[g][t] = {};
                me.icons[g][t]['normal'] = i;
               
                //création de l'icône select
                var iSel = new GIcon();
                iSel.image = "images/static/" + g + "-" + t + "-select.png";
                iSel.iconSize = new GSize(me.iconPref.w, me.iconPref.h);
                iSel.iconAnchor = new GPoint(me.iconPref.ax, me.iconPref.ay); 
                me.icons[g][t]['select'] = iSel;
                
                //création de l'icône promo
                var iPromo = new GIcon();
                iPromo.image = "images/static/" + g + "-" + t + "-promo.png";
                iPromo.iconSize = new GSize(me.iconPref.w, me.iconPref.h);
                iPromo.iconAnchor = new GPoint(me.iconPref.ax, me.iconPref.ay); 
                me.icons[g][t]['promo'] = iPromo;
                
                //création de l'icône promo Select
                var iSelPromo = new GIcon();
                iSelPromo.image = "images/static/" + g + "-" + t + "-select-promo.png";
                iSelPromo.iconSize = new GSize(me.iconPref.w, me.iconPref.h);
                iSelPromo.iconAnchor = new GPoint(me.iconPref.ax, me.iconPref.ay); 
                me.icons[g][t]['selPromo'] = iSelPromo;
            
            });
        });
        
        
        
        var i = new GIcon();
        i.image = "images/static/LOC-neutre" + ".png";
        i.iconSize = new GSize(me.iconPref.w, me.iconPref.h);
        i.iconAnchor = new GPoint(me.iconPref.ax, me.iconPref.ay); 
        
        this.icons['default'] = i;
        
        
        
    },
    
    fillBigPopup: function(obj) {
        //remplis la grande popup
        
       //Debug.trace2("Goods.fillBigPopup: " + obj.no);
        //ATTENTION ID est probablement toujours égal à this.active
        //alert(this.active);
        //this.dataCache[ID].fillBigPopup();
        obj.fillBigPopup();
    }

};

function Good() {
    ////Debug.trace3("Good constructor called");
    //alert("Good constructor Called");
}
Good.prototype = {

    
    onTheMap: function() {
        //vérifie si le point est sur la map
        
       //Debug.trace3("Good.onTheMap");
        
        if ( (this.lat >= App.bigMap.s) && (this.lat <= App.bigMap.n) && (this.lng >= App.bigMap.w) && (this.lng <= App.bigMap.e) ) {
            //le point est sur la map
           //Debug.trace3("- true");
            //on mémorise...
            this.onTheMapCache = true;
            return true;
        } else {
            //à côté
           //Debug.trace3("- false");
            this.onTheMapCache = false;
            return false;
        }
        
        
        
    },
       
    createMapMarker3: function() {
        ////Debug.trace3("Good.createMapMarker3 " + this.no);
        
        //var mo = { title: this.title, icon: this.returnIcon() };    
        //mo.icon = this.returnIcon();
        /*
        var m = new GMarker(new GLatLng(this.lat, this.lng), { title: this.title, icon: this.icon });
        
        m.no = this.no;
        
        var me = this;
        //Avertit l'application lors d'un mouseover sur le pointeur
        GEvent.addListener(m, "mouseover", function() {
            //App.mapMouseOver(m.no);      
            App.mapMouseOver(me);      
        });
        
        this.marker = m; 
*/


        
        this.marker = new GMarker(new GLatLng(this.lat, this.lng), { title: this.title, icon: this.icon });
        
        //this.marker = new GMarker(new GLatLng(this.lat, this.lng), { title: this.title });
        
        
        this.marker.no = this.no;
        
        var me = this;
        //Avertit l'application lors d'un mouseover sur le pointeur
        GEvent.addListener(this.marker, "mouseover", function() {
            //App.mapMouseOver(m.no);      
            App.mapMouseOver(me);      
        });
        
        
        
        
        
    },
    
    returnIcon: function(select) {
        //renvoie l'icône du bien
        
           //return "test";
        ////Debug.trace3("Good.returnIcon started: " + this.no);
        
        
        if( typeof App.goods.icons[this.genre][this.type]  == 'undefined' ) {
            //Debug.stop("undefined");
            Debug.trace2("DEFAULT ICO: " + this.genre + " " + this.type );
            return App.goods.icons['default'];
            
            
        } else {
        
        //Debug.trace2( "normal: " + typeof(App.goods.icons[this.genre][this.type]) );
        
        
        
        //if( ( $.inArray(this.genre, App.goods.GENRES) != -1 ) && ( $.inArray(this.type, App.goods.TYPES) != -1 ) ) {
        //if( typeof(App.goods.GENRES[this.genre]) != undefined && typeof(App.goods.TYPES[this.type]) != undefined ) {
           
            
            
        
            if( this.promo ) {
            //promo
                if(select){
                    //on renvoie l'icône select
                    return App.goods.icons[this.genre][this.type]['selPromo']; //PREVOIR PROMO SELECT
                } else {
                    return App.goods.icons[this.genre][this.type]['promo'];
                }

            } else {
                 
                if(select){
                    //on renvoie l'icône select
                    return App.goods.icons[this.genre][this.type]['select'];
                } else {
                    //Debug.stop("TEST");
                    //Debug.trace2("ico: " + this.genre + " " + this.type );
                    
                    return App.goods.icons[this.genre][this.type]['normal'];
                }
                
            }
        //} else {
        
        //    //Debug.count("DefaultIconUsed");
        //    //Debug.displaySpies();
            //Debug.trace2("DEFAULT ICO: " + this.genre + " " + this.type );
            //return App.goods.icons['default'];
        }

    },
    
    returnSelectIcon: function() {
       //Debug.trace2("Good.returnSelectIcon");
        
        //var i = this.returnIcon(true);
        //alert(i.image); 
        
        return this.returnIcon(true);
    },
    
    getID: function() {
        //renvoie l'id d'un bien
    
       //Debug.trace3("Good.getID started: " + this.no);
        return this.id;
    },
    
    dist: function() {
        //Calcule la distance depuis le centre de la carte
        
        //distanceFrom(other,  radius?)
        
        
       //Debug.trace2("Good.dist");
        
        
        //Version la terre est ronde
        
        //d = R * (Pi/2 - ArcSin( sin(destLat) * sin(sourceLat) + cos(destLong - sourceLong) * cos(destLat) * cos(sourceLat)))
        
        
        var R = 6374892.5; //Rayon de la terre [m]
        var D = 40000000; //Diametre approximatif de la terre [m] 
        var a = Math.PI / 180; //tranformation en radians

        var lat1 = App.bigMap.centerLat;
        var lat2 = this.lat;
        var lng1 = App.bigMap.centerLng;
        var lng2 = this.lng;
        
        var d = R * ( Math.PI/2 - Math.asin( Math.sin(lat2*a)*Math.sin(lat1*a) + Math.cos(lng2*a-lng1*a) * Math.cos(lat2*a) * Math.cos(lat1*a) ) );
        
        //return d;
        
       //Debug.trace3("- distance1 : " + d);
        
        //Version la terre est plate
        
        //angle = sqrt ( (lat2-lat1)^2 + (lng2-lng1)^2 )
        
        //d environ= sin(angle) * rayon de la terre
        //d environ= angle * diametre de la terre / 360
        
        var angle = Math.sqrt( (lat2-lat1)*(lat2-lat1) + (lng2-lng1)*(lng2-lng1) );
       //Debug.trace2("- angle: " + angle);
        //var d2 = Math.sin(angle*a) * R;
        var d2 = angle * D / 360;
        
        
       //Debug.trace3("- distance2 : " + d2);
        
        //return 10;
        
        //uniquement l'angle permet de sélectionner les éléments
        //on peut calculer un indice de distance...
        var i = (lat2-lat1)*(lat2-lat1) + (lng2-lng1)*(lng2-lng1);
       //Debug.trace3("- indiceDistance : " + i);
        
    
    },
    
    iDist: function() {
        //calcule un indice de distance par rapport au centre de la carte et l'attribue à la propriete dst de l'objet
        
       //Debug.trace3("Good.iDist");
        
        this.dst = (this.lat - App.bigMap.centerLat)*(this.lat - App.bigMap.centerLat) + (this.lng - App.bigMap.centerLng)*(this.lng - App.bigMap.centerLng);

        //PRISE EN COMPTE DE LA PRIORITE
        //this.dst = (this.lat - App.bigMap.centerLat)*(this.lat - App.bigMap.centerLat) + (this.lng - App.bigMap.centerLng)*(this.lng - App.bigMap.centerLng);

 
       //Debug.trace3("- indiceDistance : " + this.dst);       
    
    },
    
    getRowID: function() {
        //renvoie le row ID d'un bien
        
        //var code = "tr-";
        
       //Debug.trace3("Good.getRowID started: " + code + this.no);

        return "tr-" + this.no ;
    },
    
    getMarkerID: function() {
        //retourne l'id du bouton marker
    
        var code = "marker-";
        
       //Debug.trace3("Good.getMarkerID: " + code + this.no);
        
        return code + this.no ;
    },
    
    getLi: function() {
        ////Debug.trace3("Good.getLi");
 
        //AVEC join() (370ms IE7 )
        var li = ['<li id="tr-' , this.no , '" class="row"><a href="#"><img height="66" width="88" src="' , this.img , '?w=88&h=66" alt="" class="miniThumb"/><img height="21" width="21" src="' , this.icon.image , '" alt="" class="listIcon"><strong>' , __(this.genre + '-' + this.type) , '</strong><br>' ];
        
        //li = li.join("");
        
                //affichage du nombre de pièces
        if( this.nb_pieces && ( this.nb_pieces != 0)) {
            if( this.nb_pieces > 1) {
                li.push( this.nb_pieces , " pièces" ) ; //INTERNATIONNALISER
                //li2 += '<li>' + this.nb_pieces + ' pièces</li>';
            } else {
                li.push( this.nb_pieces , " pièce" ) ; //INTERNATIONNALISER
                //li2 += '<li>' + this.nb_pieces + ' pièce</li>';
            }
        } else {
            //on renvoie la surface du terrain
            if( this.surface == 0) {
                //On renvoie le sous-type (pour les garages...)
                li.push(__(this.type + "-" + this.sous_type)); 
            } else {
                li.push( this.surface , " m<sup>2</sup>" ) ;
                //li2 += "<li>" + this.surface + " m<sup>2</sup></li>" ;
            }
        }
        
        if( this.genre == "LOC") {
            li.push( " " , this.quartier ) ;
        }
        
                //Affichage du montant
        li.push( '<br><span class="prix">' , this.montant , '</span></a></li>' ) ;
        
        
        
        return li.join("");
        
        
        
    },
    
    
    getBigLi: function() {
        //renvoie le li de du bien
        
        //FAIRE CA EN LI!!
        
       //Debug.trace2("Good.getLi");
        
        var li = '<li id="' + this.getRowID() + '" class="row';
        if( $.inArray( this.id, App.goods.idInt) != -1 ) {
            //alert("interest");
            li += ' marked'; 
        }
        li += ' "><a href="#">';
        
        
        //affichage de la petite photo
        var w = 132;
        var h = 99;
        li +='<img height="' + h + '" width="' + w + '" src="' + this.img + '?w=' + w + '&h=' + h + '" alt="" class="miniThumb"/>';
        
        
        //affichage de l'icône
        if( ( $.inArray(this.genre, App.goods.GENRES) != -1 ) && ( $.inArray(this.type, App.goods.TYPES) != -1 ) ) {
            li += '<img height="21" width="21" src="' + App.goods.icons[this.genre][this.type]['normal'].image + '" alt="' + this.type + "-" + this.type + '" class="listIcon">';
        } else {
            //li += "NC";
        }
        
        //version en liste
        //var li2 = li + '<ul>';
        
        //affichage du type de bien
        li += "<strong> " + __(this.genre + '-' + this.type) + "</strong>"; //+ " - " + __(this.type + '-' + this.sous_type) " ;
        
        //li2 += '<li class="titre">' + __(this.genre + '-' + this.type) + '</li>';
        
        
        //localité
        //li += "<br>" + __('Localité') + ": " + this.npa + ' ' + this.localite ;
        

        
        //affichage du nombre de pièces
        if( this.nb_pieces && ( this.nb_pieces != 0)) {
            if( this.nb_pieces > 1) {
                li += "<br>" + this.nb_pieces + " pièces" ; //INTERNATIONNALISER
                //li2 += '<li>' + this.nb_pieces + ' pièces</li>';
            } else {
                li += "<br>" + this.nb_pieces + " pièce"; //INTERNATIONNALISER
                //li2 += '<li>' + this.nb_pieces + ' pièce</li>';
            }
        } else {
            //on renvoie la surface du terrain
            if( this.surface == 0) {
                //rien
            } else {
                li += "<br>" + this.surface + " m<sup>2</sup>" ;
                //li2 += "<li>" + this.surface + " m<sup>2</sup></li>" ;
            }
        }
        
        //Affichage du montant
        li += '<br><span class="prix">' + this.montant + "</span> ";
        //li2 += '<li class="prix">' + this.montant + '</li>';
        
        
        
        //li += "<br>ligne en plus";
        
        li +='<span class="englobe"></span></a></li>';
        //li2 += '</ul></a></li>';
        
        return li;
    },
        
    getPiecesOrSurface: function() {
       //Debug.trace2("Good.getPiecesOrSurface");
        
        if( this.nb_pieces && ( this.nb_pieces != 0)) {
            if( this.nb_pieces > 1) {
                return this.nb_pieces + " pièces" ; //INTERNATIONNALISER
                //li2 += '<li>' + this.nb_pieces + ' pièces</li>';
            } else {
                return this.nb_pieces + " pièce"; //INTERNATIONNALISER
                //li2 += '<li>' + this.nb_pieces + ' pièce</li>';
            }
        } else {
            //on renvoie la surface du terrain
            if( !this.surface || ( this.surface == 0) ) {
                //Si on a rien, on renvoie le sous-type (pour les garages)
                return __(this.type + "-" + this.sous_type);
                
                
                //return false;
            } else {
                return this.surface + " m<sup>2</sup>" ;
                //li2 += "<li>" + this.surface + " m<sup>2</sup></li>" ;
            }
        }
        
        
        
    },
    
    getMontant: function() {
        //retourne le montant d'un bien en ajoutant loyer ou prix
        
       //Debug.trace3("Good.getMontant started: " + this.no);
        
        var code = '';
        if (this.genre == 'LOC') {
            if (this.prix == 'Prix sur demande') 
                code = __('loyer-sur-demande');
            else
                code = __('loyer') + ": " + this.montant;
        } else {
            if (this.prix == 'Prix sur demande') 
                code = __('prix-sur-demande');
            else
                //code = __('prix') + ": " + this.montant;
                code = this.montant;
        }
        return code;
    },
    
    addLiFunctions: function() {
       //Debug.trace3("Good.addLiFunctions: " + this.no + " " );
        
        var me = this;
        
        //var element = $('#' + this.getRowID()); //ON NE PEUT PAS UTILISER ce SUR IE?? pourquoi??

        //autre moyen pour mettre en cache...
        this.e = $('#' + this.getRowID());

        this.e.click(function() {
            
            App.rowClicked(me);
            
            return false;
        });
        
        //avertit l'application lors d'un hover sur une ligne et ajoute la classe hover
        this.e.mouseover(function() {
            //entrée du hover
            $(this).addClass("hover");
            App.rowHover(me);
        }); 

        this.e.mouseout( function() {
            $(this).removeClass("hover");
        });
        
    },
        
    activate: function() {
        //active le bien

       //Debug.trace2("Good.activate started: " + this.no);        
        
        
        //on met la classe selected a la ligne du bien
        if( App.hasSmallList && this.e ) {
            this.e.addClass("selected");
            //$('#' + this.getRowID()).addClass("selected"); //TROUVER UN MOYEN DE METTRE EN CACHE
        }

            
        //Remplissage du popup
        if( App.hasSmallPopup ) {
            this.fillPopup();
        }
        
        //on avertit l'application que le bien est activé
        App.goodActivated(this.no);
        
        
        
    },
    
    desactivate: function() {
        //désactive le bien
    
       //Debug.trace2("Good.desactivate started: " + this.no);        
        
                 
        //on enlève la classe selected à la ligne du bien
        if( App.hasSmallList && this.e ) {
            this.e.removeClass("selected");
            //$('#' + this.getRowID()).removeClass("selected"); //TROUVER UN MOYEN DE METTRE EN CACHE
        }

        

        
        
    },
    
    setMarkFunctionsXXX: function() { //INUTILE?
        alert("setMarkFunctions est utile...");
       //Debug.trace2("Good.setMarkFunctions");
        
        var me=this;
        
        //assignation de la fontion mark à la petite liste
        if(App.hasSmallList) {
        
            $("#" + this.getMarkerID() ).unbind();
            $("#" + this.getMarkerID() ).click(function() {
                App.markerClicked(me.no);
                //return false;
            });
            
            $("#" + this.getMarkerID() ).html("x");
        }
        
        
    },
    
    setUnMarkFunctionsXXX: function() { //INUTLIE?
        alert("setUnMarkFunctions est utile...");
       //Debug.trace2("Good.setUnMarkFunctions");
        
        var me = this;
        
        if(App.hasSmallList) {
            $("#" + this.getMarkerID() ).unbind();

            $("#" + this.getMarkerID() ).click(function() {
                App.unMarkerClicked(me.no);
                //return false;
            });

            $("#" + this.getMarkerID() ).html("v");
            
            
        }
        
    },
    
    markXXX: function() {
        //marque un bien
        
       //Debug.trace2("Good.mark: " + this.no + " id: " + this.id );
        
        //ajouter à la liste des biens marqués
       
        
        if( $.inArray( this.id, App.goods.idInt ) == -1 ) {
            //ajout à la liste des biens intéressants
            App.goods.idInt.push( this.id ); 
           
           //Debug.trace2("- Added to the list");
            
            //Ajout de la classe marked
            if( App.hasSmallList ) {
                this.row.addClass("marked");
                
                //reassignation de la fonction pour qu'elle démarque plutôt que ce qu'elle ne marque...
                this.setUnMarkFunctions();
                
            }
            
            App.goodMarked(this.no);
            
        } else {
           //Debug.trace2("- Already marked");
            App.goodAlreadyMarked(this.no);
        }
        
        //alert("mark");
    },
    
    unMarkXXX: function() {
       //Debug.trace2("good.unMark: " + this.no);
        
        //Suppression du bien de la liste des biens intéressants
        var position = $.inArray( this.id, App.goods.idInt);
        
       //Debug.trace2("- position: " + position);
        
        App.goods.idInt.splice( position );
        
        if(App.hasSmallList) {
            this.row.removeClass('marked');
            this.setMarkFunctions();
        }
        
        //Suppression de la classe marked
        
    },
          
    fillPopup: function() {
        //remplis le petit popup

       //Debug.trace2("Good.fillPopup started: " + this.no);    
        
        App.popup.setObj(this);
    
        App.popup.setImg(this.img);
        
        App.popup.setLine(1,__(this.genre + '-' + this.type));
        //App.popup.setLine(2,__(this.type + '-' + this.sous_type) + " / " + this.getPiecesOrSurface() );
        App.popup.setLine(2, this.getPiecesOrSurface() );
        //App.popup.setLine(3,__('Localité') + ": " + this.npa + ' ' + this.localite);
        App.popup.setLine(3, this.localite);
        App.popup.setLine(4,this.getMontant());
        
    },
    
    fillBigPopup: function() {
        //remplis le grand popup
        
       //Debug.trace2("Good.fillBigPopup started: " + this.no);
        
        //App.details.setNo(this.no);
        
        App.details.setObj(this);
        
        App.details.setImg(this.img);
        
        //Le titre h3
        App.details.setLine(0,__(this.genre + '-' + this.type) + " - " + this.localite );

/*        
        App.details.setLine(1,__(this.genre + '-' + this.type));
        App.details.setLine(10,__(this.type + '-' + this.sous_type));
        App.details.setLine(2,__('Localité') + ": " + this.npa + ' ' + this.localite);
        App.details.setLine(3,__('Année de rénovation') + ": " + "X");
        App.details.setLine(4,__('Etage') + ": " +"X");
        App.details.setLine(5,__('Ascenseur') + ": " + "X");
        App.details.setLine(6,__('Nombre de pièces') + ": " + this.nb_pieces);
        App.details.setLine(7,__('Surface habitable') + ": " + "X");
        App.details.setLine(8,__('id') + ": " + this.id);
        App.details.setLine(9,this.getMontant());
        
        //le complément
        App.details.setLine(100,"Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aliquam fermentum sagittis eros. Vivamus sagittis eleifend nunc. Proin quis justo id enim accumsan volutpat. Curabitur justo ante, posuere eu, dictum quis, interdum sit amet, turpis. Aenean nec tellus eu quam viverra tristique. Nulla at libero. Nunc faucibus, enim in auctor venenatis, sem justo hendrerit velit, ut porta pede turpis id magna. Sed ultrices varius neque. Etiam massa. Vivamus sit amet orci. In libero erat, viverra eu, mattis vitae, aliquam eget, metus. Aliquam eu mauris.");
*/        
        //avertit l'application que le grand popup est rempli
        App.bigPopupFilled();
    }
    
};

function List(place) {
    //constructeur List
    
   //Debug.trace("List Constructor Called");

    this.ready = false;
    this.place = place;
    this.nbRows = 0;
    this.nbRowsMax = 7;
    this.sort = "CENTER"; // trié par : "CENTER", "NO", "PRICE", "SIZE"
    this.mapOnly = true; // true: ne liste que les biens affichés sur la map, false: liste tous les biens
    this.distArray = [];
    this.selected = [];
    this.nbGoodsOnTheMap = null;
    /*
    this.table ='   <table id="listeDesBiens" summary="Liste des biens">\
                        <caption>Liste des biens affichés</caption>\
                        <thead>\
                        </thead>\
                        <tbody>\
                        </tbody>\
                    </table>'; //INUTILE on utilise que le mode liste
                                               
    this.thead ='           <tr>\
                                <!--<th scope="col">ID</th> -->\
                                <!-- <th scope="col">Title</th> -->\
                                <th scope="col">Localité</th>\
                                <th scope="col">Type</th>\
                                <th scope="col">Pièces</th>\
                                <th scope="col">Surface</th>\
                                <th scope="col">Montant</th>\
                                <th scope="col" title="Marquer">M</th>\
                            </tr>'; //INUTILE on utilise que le mode liste
    */
    
}
List.prototype = {
    
    init: function() {
        //Création des éléments de base de la table
        
       //Debug.trace2("List.init");
        
        this.initTable();

 
    },
    
    initTable: function() { //INUTILE
        //crée le squellette de la table (ou de la liste)
        
        /*
       //Debug.trace2("List.initTable");
        if(App.listMode == "table") { //INUTILE on n'utilise que le mode List
            $(this.place).html(this.table);
            $(this.place +" thead").html(this.thead);

        } else {
            
            //alert("List.initTable AFAIRE");
        */
        
            ce(this.place).html('<ul><li>' + __('loading') + '</li></ul>');
        /*}*/
    },
        
    erase: function() {
        //efface la liste
        
       //Debug.trace("List.erase started");
        
        ce(this.place).empty();
        this.nbRows = 0;
    },
    
    eraseContent: function() {
        //efface le body de la table
        
       //Debug.trace2("List.eraseTbody");
        

        
            //alert("List.eraseContent A faire");
            
        ce(this.place + " ul").empty(); //CA A l'AIR DE MARCHER...
     
        this.nbRows = 0;
    },
    
    addTableFunctions: function() {
        //ajoute les fonctions à la table
        
        //Suppression de l'action du click sur le lien a
        //on désactive le click sur le lien
        ce(this.place + " li a").click(function() { //BUG POTENTIEL
            //alert("click a");
            ce(this).parent().click(); //BUG POTENTIEL
            //return false;
        });
        
        
       //Debug.trace2("List.addTableFunctions started");
        //a la sortie de la table, virer tous les hover
        ce('#tableBiens').unbind();
        ce('#tableBiens').hover(function(){}, function() {
            ce("#tableBiens .row").removeClass("hover");
            App.outOfList();
        });    
    },
    
    addAlertRow: function() {
        //ajoute une ligne à la fin de la table signalant qu'elle n'est pas complète
        
       //Debug.trace2("List.addAlertRow");
        
        var msg = ""; //"Click";
        
        if(this.mapOnly) {
            
            var count = App.goods.nbGoodsOnTheMap - this.nbRowsMax;
            msg += __("list-all-good") ; //" to list all goods displayed on the 
            msg = msg.replace( /X/ , count );
            
            
        } else {
            msg += " to list all goods";
        }
        
        var html = '<li><a href="#" id="showAll">' + msg + '</a></li>';
        ce(this.place + " ul").append( html );
            
        var element = $("#showAll"); //mise en cache...   

        element.unbind();
        element.click( function() {
            App.listShowAllClicked();
            //alert("click");
            return false;
        });
        
    },
    
    notFull: function() {
        //retourne true si on a pas dépassé le nombre max de lignes
    
       //Debug.trace3("List.notFull");
        if( this.nbRows < this.nbRowsMax) {
           //Debug.trace3("- notFull" );
            return true
        } else {
           //Debug.trace3("- Full" );
            return false
        }
  
    },
    
    rowAdded: function() {
       //Debug.trace3("List.rowAdded");
        this.nbRows += 1;
    },
    
    createList: function() {
       //Debug.trace("List.createList");
        
        
        
        this.ready = false;
        
        //on efface la liste actuelle
        this.eraseContent();
        
        var me = this;
        
        //tri des biens
        Debug.startSpy("sort");
        App.goods.sortBy("dst");
        Debug.stopSpy("sort");
        
        //on liste tous les biens
        App.goods.nbGoodsOnTheMap = 0;
        App.goods.nbSelected = 0;
        
        //var codeToAppend = [];
        //var rowsIds = [];
        
        var maps = App.bigMap.s;
        var mapn = App.bigMap.n;
        var mapw = App.bigMap.w;
        var mape = App.bigMap.e;
        var sfl = App.showFullList;
        
        
        //var prioritaires = []; //liste des biens prioritaires
        //var secondaires = []; //liste des biens secondaires
        
        
        Debug.startSpy("createList");
        
        
        
        
        
        $(App.goods.linesBKP).each(function() {
        
        
        
        
        
            if(this.selected) {
            
                App.goods.nbSelected++ ;
              
                // version locale de onTheMap                
                this.onTheMapCache = (this.lat >= maps) && (this.lat <= mapn) && (this.lng >= mapw) && (this.lng <= mape);
                
                
                if ( this.onTheMapCache ) {
                //if ( this.onTheMap() ) {
                    App.goods.nbGoodsOnTheMap++ ; 
                }
                
                
                if( ( ( me.nbRows < me.nbRowsMax ) || sfl ) && ( !me.mapOnly || this.onTheMapCache ) ){
                    //this.createLine();
                                        
                    e[me.place + " ul"].append(this.li);    

                    this.addLiFunctions();
                        //rowsIds.push( this.getRowID() );

                    me.nbRows++; 
                    //me.rowAdded(); //avertit la liste qu'on lui a ajouté une ligne
  
                }
                
            }
 
        });
        

        
        
        
        Debug.stopSpy("createList");

        
        
        
        //si on affiche pas tous les biens, on met la ligne d'allerte
        
        //alert(App.goods.nbGoodsOnTheMap); 
        
        //alert("nbRows: " + this.nbRows + "\nMap: " + App.goods.nbGoodsOnTheMap);
        
        if( this.nbRows < App.goods.nbGoodsOnTheMap ) {
           //Debug.trace2("- !Not all goods listed");
            this.addAlertRow();
        } else {
           //Debug.trace2("- all goods listed");
        }

        this.addTableFunctions();
        
        this.ready = true;
        
        
        
        App.listTableCreated();
        
    },
               
    onMapChanged: function() {
        //Action à faire pour rafraichir les biens au changement de la map (les biens n'ont pas étés rechargés)
        
       //Debug.trace2("List.onMapChanged");
        this.createTable();
    }
      
};

function Carte(place) {

   //Debug.trace("Carte constructor called: " + place);
    
    this.ready = false;
    
    //this.defaultCenter = {lat: 46.20381, lng: 6.139959}; //Genève
    this.defaultCenter = {lat: 46.3, lng: 6.2}; //Un peu à droite et en haut de Genève
    this.prCenter = {lat: 46.203963, lng: 6.139699}; //position Pilet Renaud
    this.prMarker = null;

    this.map = null;
    //this.bounds = null;
    this.geocoder = null;
    
    this.mgr = null;
    this.mo = { borderPadding: 200, maxZoom: 20, trackMarkers: false };

    this.place = place;
    
    this.posX = null;
    this.posY = null;
    
    this.centerX = null;
    this.centerY = null;
    
    this.sw = null;
    this.ne = null;
    this.oldSw = null;
    this.oldNe = null;
    
    this.zoom = null;
    this.oldZoom = null;
    this.maxZoom = 11;
    this.maxZoomVente = 11; //zoom maximal quand il y a des objets en vente
    this.maxZoomAutre = 15; //zoom maximal dans les autres cas
    
    this.s = null;
    this.n = null;
    this.e = null;
    this.w = null;
    
    this.centerLat = null;
    this.centerLng = null;
    
    this.biens = [];
    this.bounds = null;
    
    


}
Carte.prototype = {
    
    initCarte: function() {
        //initialisation de la carte
        
       //Debug.trace2("Carte.initCarte started");
        
        this.posX = ce(this.place).offset().left;
        this.posY = ce(this.place).offset().top;
        
       //Debug.trace2("- position : " + this.posX + " " + this.posY);
        
        //attributions des title aux boutons de l'outil de déplacement
        ce("#gMapTools2 a").each( function() {
            var t = $(this).children().html();
            $(this).attr('title',t);
        });
        
        //mise en noir du fond des boutons au hover
        ce('#gMapTools2').hover(function() {
            ce('#gMapTools2').addClass("hover");
        }, function() {
            ce('#gMapTools2').removeClass("hover");
        });
        
        
        ce("#gMapTools2 a").click( function() {
            App.moveToolsUsed( $(this).attr("id") );
            //return false;%%%%%%%%%%%%
            //alert( $(this).attr("id") );    
        });
        
        
        
    },
    
    Init: function() {
    
        Debug.startSpy("bmInit1");
        //Lanceur de l'initialisation de la carte
    
       //Debug.trace2("Carte.init started");
        
        this.initCarte();
        
        Debug.stopSpy("bmInit1");
    },
    
    resetBiens: function() {
       //Debug.trace2("Carte.resetBiens");
        
        this.biens = [];
        this.bounds = new GLatLngBounds();   
    },
    
    onResize: function() {
        //Actions à faire au redimentionnement de la map
        
       //Debug.trace2("Carte.onResize started");

        this.map.checkResize();
        

        
    },
    
    calculateNeSw: function() {
        //Calcul des coordonnées sw ne
        
        //alert("calculate sw ne");
        
       //Debug.trace2("Carte.calculateNeSw started: " + this.place);
        
        this.s = this.map.getBounds().getSouthWest().lat();
        this.w = this.map.getBounds().getSouthWest().lng();
        this.n = this.map.getBounds().getNorthEast().lat();
        this.e = this.map.getBounds().getNorthEast().lng();
        
        this.sw = this.s + "," + this.w; 
        this.ne = this.n + "," + this.e;
        
        this.centerLat = ( this.s + this.n ) / 2;
        this.centerLng = ( this.e + this.w ) / 2;
        
        this.zoom = this.map.getZoom();
        
       //Debug.trace3("- sw: " + this.sw);
       //Debug.trace3("- ne: " + this.ne);
       //Debug.trace3("- center lat: " + this.centerLat);
       //Debug.trace3("- center lng: " + this.centerLng);

    },
        
    showLoader: function() {
       //Debug.trace2("Carte.showLoader");
        //Debug.count("MapLoader");
        //Debug.displaySpies();
        //Animation du loader
        
        ce("#gMapLoader").show();
 
    },
    
    removeLoader: function() {
       //Debug.trace2("Carte.removeLoader");
        ce("#gMapLoader").hide();

    },
    
    onGoods: function() {
        //Vérifie si la carte est incluse dans la zone des biens
        
       //Debug.trace2("Carte.onGoods");
        
        if ( this.w < App.goods.w ) {
            //trop à l'ouest
           //Debug.trace("- " + this.w + " < " + App.goods.w );
            return false;
        } else if ( this.e > App.goods.e ) {
            //trop à l'est
           //Debug.trace("- " + this.e + " > " + App.goods.e );
            return false;
        } else if ( this.n > App.goods.n ) {
            //trop au nord
           //Debug.trace("- " + this.n + " > " + App.goods.n );
            return false;
        } else if ( this.s < App.goods.s ) {
            //trop au sud
           //Debug.trace("- " + this.s + " < " + App.goods.s );
            return false;
        }
        
       //Debug.trace2("- Map on goods");
        return true;
        
        
    },
    
    updateMap: function() {
    
       //Debug.trace2("Carte.updateMap");
    
        this.showLoader();
        //alert("pause");
        
        //on charge tous les points dans le markerManager

        //On recharge le markerManager avec la liste des biens sélectionnés
        
        var me = this;
       
        /*       
        //VERSION1 : en utilistant dataCache 
        //On efface la liste des biens
        this.resetBiens();
        $(App.goods.dataCache).each(function() {
            //this.createMapMarker2();
            //this.putMapMarkerOnTheMap();
        
            me.bounds.extend(this.marker.getLatLng());
            me.biens.push(this.marker);
        });
        */
        
        //VERSION2 : en utilisant linesBkp...selected
        this.resetBiens();

        $(App.goods.linesBKP).each(function() {
            if(this.selected) {
                me.bounds.extend(this.marker.getLatLng());
                me.biens.push(this.marker);    
            }
        });

        //affichage des markers sur la map
        this.displayGoods();
        this.removeLoader();
    
    },
      
    centerOnObj: function(obj) {
       //Debug.trace2("Carte.centerOnObj");
        
        this.map.setCenter(new GLatLng(obj.lat, obj.lng) );
        
    },
    
    checkMaxZoom: function() {
        Debug.trace2("Carte.checkMaxZoom");
        
        //Vérifie que l'on aie pas dépassé le niveau de zoom maximal
    
        if( this.map.getZoom() > this.maxZoom ) {
            Debug.trace("Max Zoom dépassé");
            this.map.setZoom( this.maxZoom );
        }
    }
        
};

function BigCarte(place) {
    //constructor
    
   //Debug.trace2("BigCarte constructor called");

    Carte.call(this, place);
    this.default_zoom = 10; //9
    this.topMarker = null;
    

}
BigCarte.prototype = $.extend({}, Carte.prototype, {

    constructor: BigCarte,

    init: function() {
       //Debug.trace("BigCarte.init started: " + this.place);
        //alert("BigCarte.init start");
        
        
        
        this.initCarte();
        
        this.gLoad();
        
        

    },
    
    gLoad: function() {
        //Chargement de la googleMap
        //ATTENTION les données ne sont pas encore disponibles
    
       //Debug.trace2("BigCarte.gLoad started: " + this.place);
        Debug.startSpy("gLoad");
        
        
        
        
        if (GBrowserIsCompatible()) {
                        
            var g = new GLatLng(this.defaultCenter.lat, this.defaultCenter.lng);
            

            
            //ATTENTION trouver comment appeller this.place
            this.map = new GMap2(document.getElementById("gMap"), { backgroundColor: 'black' });
            
            
            this.map.addMapType(G_PHYSICAL_MAP);
            
            //this.map.setMapType(G_SATELLITE_MAP);
            //this.map.setMapType(G_NORMAL_MAP);
            this.map.setMapType(G_PHYSICAL_MAP);
            //this.map.setMapType(G_HYBRID_MAP);
            
            //this.map.setMapType(G_SATELLITE_3D_MAP);
             
            this.map.removeMapType(G_NORMAL_MAP);
            this.map.removeMapType(G_SATELLITE_MAP);
            this.map.removeMapType(G_HYBRID_MAP);
            
            
            
            
            //this.map.enableScrollWheelZoom();
            //this.map.enableGoogleBar();
            
            GEvent.addListener(this.map,"load", App.mapReady);            
            GEvent.addListener(this.map,"moveend", App.mapMoveEnd);            
            /*GEvent.addListener(this.map,"move", App.mapMoveStart);*/
            GEvent.addListener(this.map,"zoomend", App.mapZoomEnd);
            
            //détection des événements qui font passer en mode malin..
            //drag and drop de la map
            //GEvent.addListener(this.map,"dragend", App.advancedUser); 
            //double click gauche
            //double click droit
            
             
            Debug.startSpy("map.setCenter");
            this.map.setCenter(g, this.default_zoom);
            Debug.stopSpy("map.setCenter");
            //this.map.addControl(new GOverviewMapControl());
            Debug.stopSpy("gLoad1");
            //this.map.addControl(new GLargeMapControl());
            //this.map.addControl(new GMapTypeControl());
            //this.map.addControl(new GSmallMapControl());
           
            
            this.map.addControl(new GScaleControl());
            this.bounds = new GLatLngBounds();
            this.mgr = new MarkerManager(this.map, this.mo);
            this.geocoder = new GClientGeocoder();
            
            
            
            this.bounds = new GLatLngBounds();
            
            
            
            
            var ov = new GOverviewMapControl();
            this.map.addControl(ov);
            ov.hide(true); 
            
            //on crée le marker piletRenaud
            this.prMarker = new GMarker(new GLatLng(this.prCenter.lat, this.prCenter.lng));
            
            
            this.onResize();
            this.calculateNeSw();
            //on mémorise ces valeurs
            this.oldSw = this.sw;
            this.oldNe = this.ne;
            this.oldZoom = this.zoom;
            
        }

        Debug.stopSpy("gLoad");
        //Debug.displaySpies();

    },
    
    clear: function() {
        //efface les markers
        
       //Debug.trace("<strong>BigCarte.clear started</strong>");

        this.mgr.clearMarkers();
        
       //Debug.trace2("- BigCarte.clear End");        
    },
    
    displayGoods: function() {
        
        
       //Debug.trace("BigCarte.displayGoods started");
        //on force la carte a respecter les valeurs choisies
        this.setMapForGoods();
        
        //on efface le topMarker
        this.deleteTopMarker();
        
        //charge les markers sur la map
        
        

        this.clear();
       //Debug.trace("BigCarte.displayGoods 2");
        this.mgr.addMarkers(this.biens, 5, 20);
       //Debug.trace("BigCarte.displayGoods 3");
        this.mgr.refresh();
       //Debug.trace("BigCarte.displayGoods end");
        
        //prévient l'application que les biens sont chargés
        this.ready = true;
        App.mapGoodsDisplayed();
    },
    
    setMapForGoods: function() {
       //Debug.trace2("BigMap.setMapForGoods");
        
        Debug.startSpy("setMapForGoods");
        
        //si le zoom est trop fort, on le remet à maxZoom
        //alert(this.zoom);
        if( this.zoom > this.maxZoom ) {
            this.map.setZoom(this.maxZoom);
        }
        
        //on remet la carte topo
        this.map.setMapType(G_PHYSICAL_MAP);
        
        //on vire le marker pr
        this.map.removeOverlay(this.prMarker);
        
        Debug.stopSpy("setMapForGoods");
        
    },
    
    centerOnBounds: function() {
       //Debug.trace2("BigCarte.centerOnBounds");
        //alert("center on bounds");
        this.map.setCenter(this.bounds.getCenter(), this.map.getBoundsZoomLevel(this.bounds) ); // zoom + grand == plus pres
    },
    
    placeTopMarker: function(obj) {
       //Debug.trace2("BigCarte.placeTopMarker " + obj.no );
        
        //on vérifie si l'objet est sur la map
        if( !obj.onTheMap() ) {
            //Debug.stop("NOT ON THE MAP");
            //on centre la carte sur l'objet
            this.centerOnObj(obj);
        }
        
        
        //on vire le marker actuel
        this.deleteTopMarker();
        
        //on crée le marker
        
        var point = new GLatLng(obj.lat, obj.lng);
        var mo = {clickable: true, icon: null, zIndexProcess: function(){return 1;} };
        mo.icon = obj.returnSelectIcon();
        m = new GMarker(point, mo);
        //m.no = ID;
        
        //avertit l'application lors d'un click sur le pointeur
        GEvent.addListener(m, "click", function() {         
                //alert("click");
            App.click("mapMarker");
            App.mapMouseClick(obj);
        });
        
        //avertit l'application du mouse out
        GEvent.addListener(m, "mouseout", function() {            
            //alert("mouse Out");
            App.mapTopMarkerMouseOut();
        });
        
        //Avertit l'application lors d'un mouseover sur le pointeur
        GEvent.addListener(m, "mouseover", function() {
            //alert("mouseOver");
            App.mapTopMarkerMouseOver(obj);      
        });
        

        
        this.topMarker = m ;
        this.map.addOverlay(this.topMarker);
        
        
        
    },
    
    deleteTopMarker: function() {
       //Debug.trace2("BigCarte.deleteTopMarker");
        //alert("on vire le point bleu...");
        if( this.topMarker ) {
            this.map.removeOverlay(this.topMarker);
        } 
        
    },
    
    centerOnPR: function() {
       //Debug.trace2("Carte.centerOnPR");
        
        //alert("center on PR");
        
        //on vire les markers
        this.clear();
        
        //on modifie le type de carte en carte routière
        this.map.setMapType(G_NORMAL_MAP);
        
        //on centre sur PR
        
        this.map.setCenter(new GLatLng(this.prCenter.lat, this.prCenter.lng), 16);
        
        
        //on ajoute le marker PR
        this.map.removeOverlay(this.prMarker);
        this.map.addOverlay(this.prMarker);
        
        //on force l'onglet accueil
        
        
    }
    
    
        
});

function SmallCarte() {
    //constructor
    
   //Debug.trace("SmallCarte constructor called");
    
    Carte.call(this, place);
    this.default_zoom = 15;
}
SmallCarte.prototype = $.extend({}, Carte.prototype, {

    constructor: SmallCarte,

    init: function() {
        
       //Debug.trace("SmallCarte.init started");
        
        this.initCarte();
            
    }
});

function Popup(place) {
    //constructor
   //Debug.trace("Popup constructor called");
    
    this.place = place;

    this.x = null;
    this.y = null;
    this.height = null;
    this.width = null;
    this.blocked = false;
    this.no = null;
    this.genre = null;
    this.obj = null;
    
    this.imgLoaderTimer = null;
    this.imgLoaderDelay = 200; // [ms]
    this.imgLoaded = false;
}
Popup.prototype = {

    setNo: function(no) {
        //Mémorise le numéro du bien que l'on va afficher
        
       //Debug.trace2("Popup.setNo started: " + no);
    
        this.no = no;
    },
    
    setObj: function(obj) {
       //Debug.trace2("Popup.setObj: " + this.place);
        
        this.obj = obj;
        
    },
   
    block: function() {
        //bloque l'affichage du popup
        
       //Debug.trace("Popup.block started");

        this.blocked = true;
    },
    
    unBlock: function() {
        //Débloque l'affichage du popup
        
       //Debug.trace("Popup.unBlock started");

        this.blocked = false;
    },
    
    imgLoading: function() {
        //Affiche un loader au dessus de l'image du popup
        
       //Debug.trace2("Popup.imgLoading started: " + this.no);
        //Debug.startSpy("img loading");
        
        this.showLoader();
        
        //Prépare la suppression du loader une fois que l'image sera chargée
        var me = this;
        //BUG : Firefox ajoute milles fois ce truc à l'élement...
        ce(this.place + " .bienPopImg").unbind();
        ce(this.place + " .bienPopImg").load(function() {
            
            me.imgLoaded = true;
            
            clearTimeout(me.imgLoaderTimer);
            
            //Debug.stopSpy("img loading");
           //Debug.trace2("removing loader: " + me.no);
            //Debug.count("remove pop loader");
            //Debug.displaySpies();
            
            ce(me.place + " .popImgLoader").css( "visibility" , "hidden" );
        });
        
        //affichage du loader après un tout petit délais
        //var code = 'Popup.showLoader';
        //this.imgLoaderTimer = setTimeout( code, this.imgLoaderDelay);
        
        
        //$(this.place + " .popImgLoader").css( "visibility" , "visible" ); 
        
                    
    },
    
    showLoader: function() {
        //affichage du loader
        
        //Debug.count("Popup.showLoader");
        //Debug.displaySpies();
       //Debug.trace2("Popup.ShowLoader: " + this.no);
        
        //delay
        clearTimeout(this.imgLoaderTimer);
        
        me = this;
        code = 'me.showLoaderNow()';
        
        //Debug.count("SetTimer: PopupimgLoader");
        
        this.imgLoaderTimer = setTimeout( code, this.imgLoaderDelay);

        //this.showLoaderNow();
   
    },
    
    showLoaderNow: function() {
        //Debug.count("Popup.showLoaderNow");
        //Debug.displaySpies();
       //Debug.trace2("Popup.ShowLoaderNow: " + this.no)
        
        if( this.imgLoaded ) {
            //Debug.count("Popup.showLoaderNow: ABORT");
            //Debug.displaySpies();
           //Debug.trace2("Popup.showLoaderNow: ABORT");
        } else {
            //Debug.count("Popup.showLoaderNow: PROCEED");
            //Debug.displaySpies();
            ce(this.place + " .popImgLoader").css( "visibility" , "visible" ); 
        }
    
    },
        
    show: function() {
        //Affichage du popup
        
        //Debug.stop("showSmall: " + this.place);
        
       //Debug.trace2("!! Popup.show started: " + this.place);

        if(this.blocked) {
            alert("Popup blocked, please wait...");
        } else {
            ce(this.place).show();
        }
        
        App.popupShowed(this.no);
    },
    
    hide: function() {
        //Masquage du popup
        
        //Debug.stop("hideSmall");
        
       //Debug.trace2("!! Popup.hide started: " + this.place);
        ce(this.place).hide();
        
        //avertit l'application que le popup à été caché
        App.popupHidden(this.place);
    },
    
    setImg: function(img) {
        //remplace l'image du popup
    
       //Debug.trace2("Popup.setImg started: " + this.place);        
        
        var src = img + '?w=' + this.imgWidth + '&h=' + this.imgHeight;
        
        if( src == ce(this.place + ' .bienPopImg').attr("src") ) {
            
            this.imgLoaded = true;
            
           //Debug.trace2("- same src -> abort");
            //Debug.count("Popup.setImg : SAME SRC");
            
        } else {
        
            this.imgLoaded = false;
        
           //Debug.trace2("- new src: " + src);
        
            //affichage du loader sur l'image
            this.imgLoading();
            
            //changement de l'attribut src de la zone image   
            ce(this.place + ' .bienPopImg').attr("src", src ) ;
            
            //changement de l'attribut href du lien contenant l'image (si il existe)
            ce(this.place + ' .bienPopImgA').attr( "href" , img );
        
        }

    },
    
    setLine: function(line, code) {
        //remplis une ligne de popup
        
        if (code) {        
           //Debug.trace2("Popup.setLine started: " + line);
            //alert(line + " " + code);
            ce(".bienPopL" + line).html(code);
            ce(".bienPopL" + line).show();
        } else {
            ce(".bienPopL" + line).hide();
        }
    }
};

function SmallPopup(place) {
    //Constructeur Popup qui affiche un détail sommaire de biens
    
   //Debug.trace("SmallPopup constructor called");
    Popup.call(this, place);
    this.imgHeight = 150; //Dimentions de l'image du popup
    this.imgWidth = 200;
}
SmallPopup.prototype = $.extend({}, Popup.prototype, {

    constructor: Popup,
    
    setPosition: function() {
        //Recherche les coordonnées ou afficher le popup
        
       //Debug.trace2("SmallPopup.setPosition started: " + this.no);
    
        //alert("setPopupPosition");
        
        if( App.hasBigMap ) {
            this.setPositionOnMap();
        } else {
            this.setPosition2();
        }
        
        //avertit l'application que le popup est placé
        App.popupPlaced();
    },
    
    setPosition2: function() {
        //Position de la popup quand on a pas de map... A-FAIRE
    
       //Debug.trace("SmallPopup.setPosition2 started A-FAIRE");
        //on positionne le popup
        ce(this.place).css("left", 500 + "px" );
        ce(this.place).css("top", 200 + "px" );
    },
    
    setPositionOnMap: function() {
        //Recherche de la position du popup quand on a une map
        
       //Debug.trace2("SmallPopup.setPositionOnMap started: " + this.obj.no);        
    
        //positionnement du popup par défaut en bas à droite du point
        var corr = 10; //Eloignement du point central du bien en pixels //15
        var pad = 40; //Correction à cause du padding //10
        var bor = 0; //Correction à cause du border
        var class2 = ""; //class à mettre au popup pour les coins

        //calcule la position du centre de la carte
        App.bigMap.centerX = App.bigMap.map.getSize().width/2;
        //recherche de la coordonnée Y du point central. 
        App.bigMap.centerY = App.bigMap.map.getSize().height/2;
    
        //Après intégration des éléments, recalculer la hauteur du popup
        this.height = ce(this.place).height();
        this.width = ce(this.place).width();
        
        //recherche de la position actuelle du point
        //var posX = App.bigMap.map.fromLatLngToContainerPixel(App.bigMap.biens[this.no].getPoint()).x ;
        var posX = App.bigMap.map.fromLatLngToContainerPixel(this.obj.marker.getPoint()).x ;
        var posY = App.bigMap.map.fromLatLngToContainerPixel(this.obj.marker.getPoint()).y ;
        
        //si on est en dessous du point central, on corrige pour afficher le popup en dessus du point.
        if( posY > App.bigMap.centerY ) {
            class2 = "bottom";
            posY -= corr;
            posY -= this.height;
            posY -= pad;
            posY -= bor;
        } else {
            class2 = "top";
            posY += corr;
            posY -= bor;
            //posY -= pad;
        }
        
        //si on est à droite du point central, on corrige pour afficher le popup à gauche du point.
        if( posX > App.bigMap.centerX ) {
            class2 += "Right";
            posX -= corr;
            posX -= this.width;
            posX -= pad;
            posX -= bor;
        } else {
            class2 += "Left";
            posX += corr ;
            posX -= bor;
        }
        
        //on corrige avec la position de la map
        posX += App.bigMap.posX;
        posY += App.bigMap.posY;
        
        //on supprime toutes les ancienne classes
        ce(this.place).removeClass('topLeft');
        ce(this.place).removeClass('topRight');
        ce(this.place).removeClass('bottomLeft');
        ce(this.place).removeClass('bottomRight');
        //on ajoute la classe calculée
        ce(this.place).addClass(class2);
        
        //on positionne le popup
        ce(this.place).css("left", posX + "px" );
        ce(this.place).css("top", posY + "px" );
        
       //Debug.trace2("- PosX: " + posX + " PosY: " + posY + " height: " + this.height);
    },
    
    setPositionOnMapOLDXXX: function() {
        //Recherche de la position du popup quand on a une map
        
       //Debug.trace2("SmallPopup.setPositionOnMap started: " + this.no);        
    
        //positionnement du popup par défaut en bas à droite du point
        var corr = 10; //Eloignement du point central du bien en pixels //15
        var pad = 40; //Correction à cause du padding //10
        var bor = 0; //Correction à cause du border
        var class2 = ""; //class à mettre au popup pour les coins

        //calcule la position du centre de la carte
        App.bigMap.centerX = App.bigMap.map.getSize().width/2;
        //recherche de la coordonnée Y du point central. 
        App.bigMap.centerY = App.bigMap.map.getSize().height/2;
    
        //Après intégration des éléments, recalculer la hauteur du popup
        this.height = $(this.place).height();
        this.width = $(this.place).width();
        
        //recherche de la position actuelle du point
        var posX = App.bigMap.map.fromLatLngToContainerPixel(App.bigMap.biens[this.no].getPoint()).x ;
        var posY = App.bigMap.map.fromLatLngToContainerPixel(App.bigMap.biens[this.no].getPoint()).y ;
        
        //si on est en dessous du point central, on corrige pour afficher le popup en dessus du point.
        if( posY > App.bigMap.centerY ) {
            class2 = "bottom";
            posY -= corr;
            posY -= this.height;
            posY -= pad;
            posY -= bor;
        } else {
            class2 = "top";
            posY += corr;
            posY -= bor;
            //posY -= pad;
        }
        
        //si on est à droite du point central, on corrige pour afficher le popup à gauche du point.
        if( posX > App.bigMap.centerX ) {
            class2 += "Right";
            posX -= corr;
            posX -= this.width;
            posX -= pad;
            posX -= bor;
        } else {
            class2 += "Left";
            posX += corr ;
            posX -= bor;
        }
        
        //on corrige avec la position de la map
        posX += App.bigMap.posX;
        posY += App.bigMap.posY;
        
        //on supprime toutes les ancienne classes
        $(this.place).removeClass('topLeft');
        $(this.place).removeClass('topRight');
        $(this.place).removeClass('bottomLeft');
        $(this.place).removeClass('bottomRight');
        //on ajoute la classe calculée
        $(this.place).addClass(class2);
        
        //on positionne le popup
        $(this.place).css("left", posX + "px" );
        $(this.place).css("top", posY + "px" );
        
       //Debug.trace2("- PosX: " + posX + " PosY: " + posY + " height: " + this.height);
    },
    
    showLoader: function() {
        //Bypasse le delay pour l'affichage du loader sur les petites popup en remplacant la fonction showLoader de base qui est temporisée
        
       //Debug.trace2("SmallPopup.showLoader");
        
        this.showLoaderNow();
        
    }

});

function BigPopup(place) {
    //constructor
    
   //Debug.trace("BigPopup constructor called");
    
    Popup.call(this, place);
    this.imgHeight = 297; //Dimentions de l'image du popup
    this.imgWidth = 396;
    this.nbCarImg = 0;
    this.interesseOpen = false; //est-ce que le formulaire je suis interessé est affiché?
    
    me = this;
    
    //Fermeture du popup quand on clique à côté
    ce( this.place ).click( function() {
        App.detailsOutClick();
        App.click("BigPopup.main");
        return false; // BLOQUE LE CLICK MAIN!!!
    });
    
    //quand on clique dans la zone container (pour annuler le click out...)
    ce( this.place + " .container" ).click( function() {
        App.detailsContainerClick();
        App.click("BigPopup.container");
        return false; //BLOQUE LE CLICK MAIN!!!!
    });
    
    //Clique sur la zone déroulée de je suis intéressé
    ce( this.place + " #formInteresseContainer").click( function() {
        App.click("BigPopup.form");
        return false; //EMPECHE LA PROPAGATION DU CLICK     
    });
        
    //fonctionalités des boutons de bigPopup
    ce( this.place + " .btnHide" ).click( function() {
        App.detailsCloseClick();
        //return false;
    });
    
    //click sur le bouton imprimer
    ce(this.place + " .btnPrint a").click(function() {
        //alert(App.details.no);
        window.open("/fr/print?no=" + App.details.no);
        //return false;
    });
    
    //click sur le bouton je suis intéressé
    
    ce( this.place + " .btnInt a").click( function() {
        
        if( App.details.interesseOpen ) {
            //on le ferme
            App.details.hideInteresse();
            //me.forceHeight();
            
        } else {
            App.details.showInteresse();
            //me.forceHeight();
            App.click("BigPopup.btnInt");
            return false; //BLOQUE LA PROPAGATION DU CLICK
        }
        
        
    });
    
    //click sur la validation du formulaire je suis intéressé
    ce("#sendInteresse").click(function() {
        //alert("envoyer");
        Debug.trace("SENDMAIL int");
        $.ajax({
            type: 'POST' ,
            url: 'fr/ajax/sendmail' ,
            //data: 'no=' + App.goods.dataCache[this.no].id + '&source=' + App.goods.dataCache[this.no].source,
            data: 'source=' + App.details.genre + '&email=' + $("#email").val() + '&nom=' + $("#nom").val() + '&msg=' + $("#areaMessage").val() + '&no=' + App.details.no + '&nom2=' + $("#nom2").val() + '&tel=' + $("#tel").val(),
            dataType: 'text',
            success: App.sendMailResult,
            error: function() {}
        });
   
    });
        

    //Bouton Mark
    /*
    $( this.place + " .btnMark" ).click( function() {
        App.detailsMarkClick();
        return false;
    });
    */
    

    
    
     
}
BigPopup.prototype = $.extend({}, Popup.prototype, {

    constructor: Popup,
    
    show: function() {
        //Affiche le big popup
    
        //Debug.stop("showBig");
       //Debug.trace2("BigPopup.show started");
        
        this.hideInteresse();
        
        ce(this.place).css("left" , 0);
        ce(this.place).show();
        
    },
    
    hide: function() {
        //ferme la fenêtre
    
       //Debug.trace("BigPopup.hide started");

        ce(this.place).hide();
    },
    
    showInteresse: function() {
       //Debug.trace2("BigPopup.showInterresse");
        //$(this.place + " #bienBigPopTools3Middle").show();
        //$(this.place + " #bienBigPopTools3Bottom").show();
        ce(this.place + " #formInteresseContainer").slideDown();
        
        //DETECTER ICI S'IL FAUT AFFICHER LOC OU VENTE!!!! 
        
        
        this.interesseOpen = true;
    },
    
    hideInteresse: function() {
       //Debug.trace2("BigPopup.hideInterresse");
        //$(this.place + " #bienBigPopTools3Middle").hide();
        //$(this.place + " #bienBigPopTools3Bottom").hide();
        ce(this.place + " #formInteresseContainer").slideUp();
        this.interesseOpen = false;
        
    },
    
    hideForm: function() {
       //Debug.trace2("BigPopup.hideForm");
        
        ce(this.place + " #formInteresseContainer form").hide();  
        
    },
    
    resetForm: function() {
       //Debug.trace2("BigPopup.resetForm");
        
        ce('#result').html('');
        ce(this.place + " #formInteresseContainer form").show(); 
    },    
    
    loadFiche: function(obj) {
       //Debug.trace2("BigPopup.loadFiche");
        
        //alert(obj.id);
        //mémorisation de l'objet
        this.no = obj.id;
        //mémorisation du genre
        this.genre = obj.genre;
        
        
        //affichage - masquage de la partie du formulaire de contact adéquate
        //Debug.stop( obj.genre  );
        
        if( obj.genre == "LOC") {
            ce("#coordVente").hide();
            ce("#coordLoc").show();
        } else {
            ce("#coordLoc").hide();
            ce("#coordVente").show();        
        }
        
        $.ajax({
            type: 'POST' ,
            url: 'fr/ajax/getfiche' ,
            //data: 'no=' + App.goods.dataCache[this.no].id + '&source=' + App.goods.dataCache[this.no].source,
            data: 'no=' + obj.id + '&source=' + obj.source,
            dataType: 'text',
            success: App.detailFicheLoaded,
            error: function() {}
        });
        
        //alert(this.no);
        
    },
    
    updateFiche: function(data) {
       //Debug.trace2("BigPopup.updateFiche");
        //alert("updating..");
        ce(this.place + ' .data').html(data);
        this.resetForm();
        this.addBigPopupFunctions();
    },
    
    addBigPopupFunctions: function() {
       //Debug.trace2("BigPopup.addBigPopupFunctions");
        
        var me = this;

        //EFFACER l'ancien cache...
        e["#thumbsList a"] = false;
        e[me.place + " .bienPopImg"] = false;
        e[me.place + " .bienPopImgA"] = false;
        e[me.place + " .popImgLoader"] = false;
        
        //clique sur l'image principale
        ce( me.place + " .bienPopImgA").click( function() {
            //alert($( me.place + " .bienPopImgA").attr("href") );
            window.open( ce( me.place + " .bienPopImgA").attr("href") );
            //return false;
        });
        
        
        //hover sur le bouton je suis interressé
        //AFAIRE
        

        
        ce("#thumbsList a").each( function() {
    
            var href = this.href + "?w=" + me.imgWidth + "&h=" + me.imgHeight;
            var href2 = this.href;
            $(this).mouseover( function() {
            
               //Debug.trace2("BigPopup.addBigPopupFunctions: mouseover");
                
                //si l'image est déjà chargée, on ne fait rien
                if( ce(me.place + " .bienPopImg").attr("src") == href) {
                    //alert("image déjà chargée");
                    
                   //Debug.trace2("- Big image already loaded");
                   //Debug.trace2(href);
                    //Debug.count("Big image already loaded");
                    //Debug.displaySpies();
                    
                } else {
                    
                    //on supprime la class selected à tout le monde
                    ce("#thumbsList a").removeClass("selected");
                    //on l'ajoute au lien en cours
                    $(this).addClass("selected"); 
                   
                    
                    App.details.imgLoaded = false;
                
                    me.imgLoading();
                    
                   //Debug.trace2("- Loading Big Img");
                   //Debug.trace2(href);
                    
                    ce(me.place + " .bienPopImg").attr( "src" , href );
                    //alert(href);
                    //$(me.place + " .bienPopImg").src = href;
                    
                    
                    //modification de la propriété au click sur la grande image pour qu'elle s'ouvre dans une nouvelle fenêtre
                    
                    
                    
                    //$(me.place + " .bienPopImg").unbind();
                    //alert(href2);
                    ce(me.place + " .bienPopImgA").attr("href", href2);
                    
    
                    
                    //$(me.place + " .bienPopImg").css("cursor","pointer");
                    
                    
                }
                
                
            });
            
            //ouverture en grand au click
            $(this).click(function() {
                window.open(this.href);
            });
        });
   
    
    }
    
});

var SearchTools = {

    /* pour la recherche*/
    affiner: false,
    affinerPlus: false,
    blockNextReset: false,
    initialized: false,
    affinerPlusInitialized: false,

    initMode3: function() {
        
        //alert("SearchTools InitMode3");
        
        ce("#onglets li").hover(function() {
            //alert("hover");
            $(this).addClass("hover");
            
        }, function() {
            $(this).removeClass("hover");
            
        }); //78ms        

        
        
    },

    init: function() {
    
        //on essaye de gagner du temps au premier chargement en faisant l'init des searchTools uniquement quand on clique sur affiner
        
        
        
        
        //initialisation de la version en onglets
        
       //Debug.trace2("SearchTools.init");
        
        //ajout des fonctions aux boutons des onglets
        
        //au click, on deselectionne tous les autres
        
        ce("#onglets li").click(function() {
            ce("#onglets li").removeClass("selected");
            ce('#onglets li a').removeClass("selected");
            $(this).addClass("selected");
            $(this + " a").addClass("selected"); //MISE EN CACHE???
            //alert( $(this).children().attr("id") );
            App.ongletClicked( $(this).children().attr("id") );
            //return false;
        }); //62ms
       
        
        //on désactive le click sur le lien
        
        ce("onglets li").children("a").click(function() {
            $(this).parent().click();
            return false;
        }); //0ms
        
        
        //configuration du over
        
        
        ce("#onglets li").hover(function() {
            //alert("hover");
            $(this).addClass("hover");
            
        }, function() {
            $(this).removeClass("hover");
            
        }); //78ms
        
        
        //configuration de l'action du champs prix sur demande
        /*
        $("#surDemande").click(function() {
            //alert("psdClicked");
            App.searchToolUsed();
        });
        */
        

        if( !this.affiner) {
            this.masquerAffiner();
        } else {
            this.afficherAffiner();
        }

        
        if( !this.affinerPlus) {
            this.masquerAffinerPlus();
        } else {
            this.afficherAffinerPlus();
        }

        var me = this;
        
        ce("#affiner").click(function() {
            if( me.affiner ) {
                //affiner est déjà déployé... on le masque
                me.masquerAffiner();
                //$(this).removeClass("close");
                //$(this).addClass("open");
            } else {
                me.afficherAffiner();
                //$(this).removeClass("open");
                //$(this).addClass("close");
            }
            //return false;
        });

        //ajout des fonctions sur les zones de recherche
        

        //this.initAffiner();

        
        
    },
    
    
    initPetitsBoutons: function() { //INUTILE???
        alert("initPetitesBoutons utilisé!!!");
       //Debug.trace2("Goods.initPetitsBoutons");
        
        //Calcul des images pour les petits boutons
        
        //$(".selector").css( 'background-image', 'images/static/' + $(this).attr('id') + '.png' );
        $(".selector").each( function() {
            //alert($(this).attr('id'));
            $(this).parent().css('background-image', 'url("images/static/' + $(this).attr('id') + '-Double.png")');
            //transmission de la propriété selected au parent
            if ( $(this).hasClass("selected") ) {
                $(this).parent().addClass("selected");  
            } else {
                $(this).parent().removeClass("selected"); 
            }
        });
        
                //ajout des fonctions sur les petits selectors
        $(".selector").click(function(){
            
           //Debug.trace2( $(this).attr("id") + " toggled" );
            
            $(this).toggleClass("selected");
            
            //alert($(this).css('background-image'));
            
            //on vire les hover du parent
            $(this).parent().removeClass("hover");
            $(this).parent().removeClass('selectedHover');
            
            //transmission de la propriété selected au parent et modification de l'intitulé du lien
            if ( $(this).hasClass("selected") ) {
                $(this).parent().addClass("selected");
                $(this).parent().addClass('selectedHover');
                
                
                $(this).children().html(__('masquer'));
            } else {
                $(this).parent().removeClass("selected");
                $(this).parent().addClass('hover');
                 $(this).children().html(__('afficher'));
            }

            //App.searchToolUsed();
            //Bien.getData();
            //return false;
        });
        
        //action du hover sur les petits selectors
        $(".selector").hover(function() {
            //ajout de la classe hover au parent
            //$(this).parent().addClass("hover");
            //on déplace l'image de fond du parent
            //alert("hover");
            if($(this).hasClass('selected')){
                //on attribue la class selectedHover au parent (a cause d'IE 6 qui supporte pas les doubles classes)
                $(this).parent().addClass('selectedHover');
            } else {
                //hover non selectionne
                $(this).parent().addClass('hover');
                
            }
            
        }, function() {
            //on vire les hover du parent
            $(this).parent().removeClass("hover");
            $(this).parent().removeClass('selectedHover');
        });
        
        
        
        
    },

    masquerAffiner: function() {
       //Debug.trace2("serachTools.masquerAffiner");
        
        ce("#searchContainerMiddle").hide();
        ce("#searchContainerBottom").hide();
        //$("#affiner").html("[+] Critères de sélection");
        ce("#searchContainer").removeClass("open");
        this.affiner = false;
    },
    
    afficherAffiner: function() {
       //Debug.trace2("serachTools.afficherAffiner");
        
        //Vérifier si affiner à déjà été affiché!
        if( !this.affinerPlusInitialized ) {
            this.initAffiner();
            this.affinerPlusInitialized = true;
        }
        
        
        
        ce("#searchContainer").addClass("open");
        ce("#searchContainer").removeClass("hover");
        ce("#searchContainerBottom").show();
        ce("#searchContainerMiddle").show();
        //$("#affiner").html("[-] Critères de sélection");
        this.affiner = true;
    },
    
    masquerAffinerPlus: function() {
       //Debug.trace2("serachTools.masquerAffinerPlus");
        //alert("affinerPlus MASQUER");
        ce("#limiter .advanced").hide();
        //$("#affinerPlus").html("[+] Critères avancés");
        this.affinerPlus = false;
        ce("#searchContainer").removeClass("openPlus");
  
    },
    
    afficherAffinerPlus: function() {
       //Debug.trace2("serachTools.afficherAffinerPlus");
        //alert("affinerPlus AFFICHER");
        ce("#searchContainer").addClass("openPlus");
        //$("#affinerPlus").html("[-] Critères avancés");
        ce("#limiter .advanced").show();
        this.affinerPlus = true;
        
    },
    
    initAffiner: function() {
       //Debug.trace2("Goods.initAffiner");
        
        //alert(this.affiner);

        Debug.startSpy("SearchTools.initAffiner()");
        //configuration de l'action sur le click du bouton limiter
        ce("#limiterSubmit").click(function() {
            //alert("click");
            App.searchToolUsed();
            //return false;
        });
        
        ce("#limiterReset").click(function() {
            App.limiterResetClick();
            //return false;
        });

        //version petits boutons:
        //this.initPetitsBoutons();
        
        //version checkbox:
        
        ce(".checkbox").click(function() {
           //Debug.trace3("click: " + $(this).attr("value"));
            //si on a clické sur autre chose que indifférent, on déselectionne indifférent
            //alert($(this).attr("value"));
            App.blockNextClick = false;
            if( $(this).attr("value") == "ALL") {
                //Si on vient de sélectionner le checkbox
                if(this.checked) {
                    //on désélectionne tous les autres
                    ce(".checkbox").uncheck();
                    ce("#checkbox-ALL").check();
                }
            } else {
                //on désélectionne all
                ce("#checkbox-ALL").uncheck();
            }
            
            //s'il ne reste plus rien, on resélectionne all
            if( ce(".checkbox:checked").length == 0) {
                ce("#checkbox-ALL").check();
            }
            
            //App.searchToolUsed();
            //return false; //BLOQUE LA PROPAGATION DU CLICK            
            
            
        });
        
        
        //ajout de la même fonction  au click sur le label
        ce("#typesLimiter li label").click(function() {
           //Debug.trace3("-- click on label:" + $(this).parent('li').children('input').attr("value") );
            App.blockNextClick = false;
            //$( '#checkbox-' + $(this).parent('li').children('input').attr("value")).click();
            //return false; //BLOQUE LA PROPAGATION DU CLICK 
        });
        
        //autorisation de l'action sur les boutons SurDemande
        ce(".checkboxPrix").click(function() {
            App.blockNextClick = false;    
        });


    


        var me = this;
        

        
        ce("#masquer").click(function() { //INUTILE
            me.masquerAffiner();
            //return false;
        });
        
        ce("#affinerPlus").click(function() {
            if( me.affinerPlus ) {
                me.masquerAffinerPlus();
            } else {
                me.afficherAffinerPlus();
            }
            //return false;
        });

        //over sur la zone affiner
        ce("#searchContainer").hover(function() {
            if( !me.affiner ) {
                $("#searchContainer").addClass("hover");
            }
        }, function() {
            $("#searchContainer").removeClass("hover");
        });
        
        //Zones qui doivent se comporter comme au click sur affiner
        //$("#searchContainerTop , #searchContainerMarginBottom , #searchContainerBottom ").click( function() {
        //    $("#affiner").click();    
        //});
       
        //INPUT SELECT

        //masquage initial
        ce(".dropDown").hide();
        
      

        //Déroulage des options de select
        ce(".u .openSelect").click(function() {
            //alert("show");
            $(this).parent().children(".dropDown").show();
            //return false;
        });        
        
        //mise en bleu du selector open
        /*$(".u .openSelect").hover(function() {
            $(this).addClass("hover");
        }, function() {
            $(this).removeClass("hover");
        });*/

        ce(".dropDown li").hover(function() {
            $(this).addClass("hover");
        }, function() {
            $(this).removeClass("hover");
            //$(".dropDown").hide();
        });
        
        //fermeture du dropdown quand on le quitte
        ce(".dropDown").hover(function() {

        }, function() {

            ce(".dropDown").hide();
        });
        
        //replis au click sur la zone
        ce(".dropDown li").click(function() {
            //alert("hide");
            
            //on plante la valeur dans le champ
            //alert( $(this).html() );
            //alert( $(this).extractNumber() );
            $(this).parents(".main").children("input").val($(this).html());
            //alert( $.fn.extractNumber($(this).parents(".main").children("input").val()) );
            //$(this).extractNumber();
            //alert(this.numericVal);

            
            ce(".dropDown").hide();
            //return false;
        });

        //Annulation de l'ouverture de la liste au click dans le champ
        ce(".t input").click(function() {
            ce(".dropDown").hide();
            //alert("click sur le champ");
            //return false
        });
        
        //mise au premier plan de la zone en cas de hover pour que le dropdown passe devant le champs qui sont au dessous
        ce("li.u").hover(function() {
            //alert("hover");
            $(this).addClass("uHover");
        }, function() {
            //alert("plusHover");
            $(this).removeClass("uHover");
        });
        
        Debug.stopSpy("SearchTools.initAffiner()");       
       //Debug.displaySpies();
    },
    
    masqueH: function() {
        //masque tout ce qui à la classe h
        
       //Debug.trace2("SearchTools.masqueH");
        ce('.h').css("visibility","hidden");
        ce('.h').css("position","absolute");
        
    },
    
    showGenre: function() {
        //affiche les éléments qui correspondent au genre sélectionné
        
       //Debug.trace2("SearchTools.showGenre");

        //alert(App.goods.genreSelected);
        
        //$('.' + App.goods.genreSelected).css("background-color","red");
        ce('.' + App.goods.genreSelected).css("visibility","visible");
        ce('.' + App.goods.genreSelected).css("position","relative");
       
        
        
    },
    
    resetForm: function() {
       //Debug.trace2("SearchTools.resetForm");
        
        if( this.blockNextReset ) {
            this.blockNextReset = false;
        } else {
            //on coche indifférent
            this.resetTypes();
            this.resetSelect();
        }
    },
    
    uncheckAll: function() {
       //Debug.trace2("SearchTools.uncheckAll");
        ce(".checkbox").uncheck();
    },
    
    resetTypes: function() { //NON UTILISE??
       //Debug.trace2("SearchTools.resetTypes");
        
        //remet le type de biens à indifférent
        //on désélectionne tout
        this.uncheckAll();
        /*$(".checkbox").each(function() {
            $(this).uncheck();
        });*/
        //on sélectionne all
        ce("#checkbox-ALL").check();
    },
    
    resetSelect: function() {
       //Debug.trace2("SearchTools.resetPrices");
        
        ce("#prixMax").val(__("illimité"));
        ce("#prixMin").val(__("indifférent"));
        ce("#loyerMax").val(__("illimité"));
        ce("#loyerMin").val(__("indifférent"));
        
        ce("#surfaceMax").val(__("illimité"));
        ce("#surfaceMin").val(__("indifférent"));
        ce("#piecesMax").val(__("illimité"));
        ce("#piecesMin").val(__("indifférent"));
        
        ce("#prixSurDemande").check();
        ce("#loyerSurDemande").check();
        
    },
    
    hideUnusedTypes: function() {
       //Debug.trace2("SearchTools.hideUnusedTypes");
       //Debug.trace2("- " + App.goods.genreSelected);
        var arraySelected = null;
        switch( App.goods.genreSelected ){
            
            case "VENTE":
                arraySelected = App.goods.typesVente;
                break;
                
            case "LOC":
                arraySelected = App.goods.typesLoc;
                break;
                
            case "PROMO":
                arraySelected = App.goods.typesPromo;
                break;
        }
        
        if ( arraySelected ) {
            ce("input.checkbox").each(function() {
               //Debug.trace2( "-" + $(this).attr("value"));
                if( $.inArray( $(this).attr("value") , arraySelected ) != -1 ) {
                   //Debug.trace2("-- OK");
                    ce("#li-" + $(this).attr("value") ).show();
                    //$("#checkbox-" + $(this).attr("value") ).show();
                } else {
                   //Debug.trace2("-- REMOVE");
                    //$(this).hide();
                    ce("#li-" + $(this).attr("value") ).hide();
                    //$("#checkbox-" + $(this).attr("value") ).hide();
                }
            });
        }
        
        
        
        
    },
    
    placeElements: function() {
       //Debug.trace2("SearchTools.placeElements");
       //Debug.trace2("XXXXXXXXXXXXXXXXXXXXXXXXX");
        this.masqueH();
        
        this.showGenre();
        
        this.hideUnusedTypes();
        //this.resetTypes();
        
    }
    

    
};

var TagCloud = {
    
    tags : new Array() ,
    
    init: function() {
       //Debug.trace2("TagCloud.init");
        
        //configuration du click sur les lien
        ce("#tagCloud li a").click( function() {
            //alert("click");
            Debug.trace2("click on tagCloud: " + $(this).parent().attr("id"));
            App.tagCloudClick( $(this).parent().attr("id") );
            //return false;
        });
        
    }
    
};

var ModeSwitcher = {

    init: function() {
       //Debug.trace2("ModeSwitcher.init");
        
        //Attribution des fonctions aux boutons:
        
        
        
        ce("#gMapSelector").click(function() {
            //ModeSwitcher.setModeMap();
            //return false;
            App.blockNextClick = false;
        });
        
        ce("#listSelector").click(function() {
            //ModeSwitcher.setModeList();
            //return false;
            App.blockNextClick = false;
        });
        
        
        
    },
    
    setModeMap: function() {
       //Debug.trace2("ModeSwitcher.setModeMap");
        
        
        ce('#gMap').removeClass("small");
        ce('#gMap').addClass("big");
        
        ce('#tableBiens').removeClass("big");
        ce('#tableBiens').addClass("small");
        
        
        ce(".mainBox").css("margin-left","360px");

        
        ce(".leftBox").css("width","350px");
        
        
        App.placeElements();
        App.elementDetector();
    },
    
    setModeList: function() {
       //Debug.trace2("ModeSwitcher.setModeList");
        
        //alert("set List");
        ce('#gMap').removeClass("big");
        ce('#gMap').addClass("small");
        
        ce('#tableBiens').removeClass("small");
        ce('#tableBiens').addClass("big");
        
        //on bouge la marge de mainBox pour pousser la map
        ce(".mainBox").css("margin-left","710px");

        //on agrandit la partie de droite
        ce(".leftBox").css("width","700px");

        App.placeElements();
        App.elementDetector();
    }
    
};

var Menu = {
    
    timer: null,
    timerDelay: 200, // [ms]
    
    init: function() {
       //Debug.trace2("Menu.init");
        
        this.closeAll();
        
        //ajout des fonction sur le menu du haut
        ce(".menuPop").each( function() {
            var me = this;
            var id = $(this).attr('id');
            var blocked = false;
            
           //Debug.trace2("- " + id);
/*            $(this).hover(function() {
                //on kill le timer qui ferme le menu
                clearTimeout( Menu.timer);
                //on force la classe hidden à tous le monde
                Menu.closeAll();
                
                //alert( $(this).attr('id') );
                
                $( "#" + $(this).attr('id') + " .container div").slideDown("slow");
                //on l'enlève pour le menu en cours
                $(me).removeClass("hidden");
                //alert("hover " + id);
            }, function() {
                //alert("plus hover " + id);
                //$(me).addClass("hidden");
                //on lance le timer qui fermera le menu
                Menu.timer = setTimeout('Menu.timerEnd()' , Menu.timerDelay );
            });
*/            
            //fonctions du click
            $(this).click( function() {
                
                //if( blocked ) {
                    //le menu est déjà en train de bouger
                //} else {
                    //blocked = true;
                    //si le menu n'a pas la classe hidden, on le ferme
                    if( $(me).hasClass('hidden')) {
                        Menu.closeAll();
                        Menu.open(me);

                        
                    } else {
                        Menu.closeAll();
                    }
                //}
                
                App.click("Menu");
                if ( App.blockNextClick ) {
                    return false; //BLOQUE LA PROPAGATION DU CLICK
                }
            });
            
            //click dans la zone déroulée.
            $(this).children(".container").click(function() {
                App.click("Menu.container");
                if ( App.blockNextClick ) {
                    return false; //BLOQUE LA PROPAGATION DU CLICK
                }
            });
            
            //Gestion du hash!!!
           //Debug.trace3("GESTION HASH: MENU: " + $(this).attr("id") + " " + App.hash);
            if( App.hash == ( "m" + $(this).attr("id") ) ) {
                App.menuOpen(this);
                Menu.open(this);
            }
     
        }); 
        
        //click sur la validation du formulaire de contact
        ce("#sendCTC").click(function() {
            //alert("envoyer");
            Debug.trace("SENDMAIL");
            Debug.trace(ce("#emailCTC").val());
            $.ajax({
                type: 'POST' ,
                url: 'fr/ajax/sendmail' ,
                //data: 'no=' + App.goods.dataCache[this.no].id + '&source=' + App.goods.dataCache[this.no].source,
                data: 'source=CTC' + '&email=' + ce("#emailCTC").val() + '&nom=' + ce("#nomCTC").val() + '&msg=' + ce("#areaMessageCTC").val() + '&nom2=' + ce("#nom2CTC").val() + '&tel=' + ce("#telCTC").val(),
                dataType: 'text',
                success: App.sendMailResultCTC,
                error: function() {}
            });
       
        });
        
        
        
        
    },
    
    closeAll: function() {
       //Debug.trace2("Menu.closeAll");
        
        $(".menuPop").addClass("hidden");
        $(".menuPop .container div").slideUp(200);
    },
    
    open: function(m) {
       //Debug.trace2("Menu.open");
        
        Menu.showCTCForm(); //réaffiche le formulaire de contact
        $(m).removeClass("hidden");
        App.menuOpen(m);
        $( "#" + $(m).attr('id') + " .container div").slideDown(700, function() {
            //blocked = false;
        });
        
        
        
        
    },
    
    hideCTCForm: function() {
       //Debug.trace2("Menu.hideCTCForm");
        $("#formCTC").hide();
    },
    
    showCTCForm: function() {
       //Debug.trace2("Menu.showCTCForm");
        $("#formCTC").show();
    },
    
    timerEnd: function() {
       //Debug.trace2("Menu.timerEnd");
        
        Menu.closeAll();
    }
    
};

var Debug = {

    cache: [],
    spies: {},
    numbers: {},
    objTrace1: null,
    objTrace2: null,
    initialized: false,
    
    init: function() {
        //var DEBUG = DEBUG;
        //affichage de toutes les zones
        
        
/*
        Debug.cache["#trace2"] = $("#trace2");
        Debug.cache["#trace1"] = $("#trace1");
        Debug.cache["#spies"] = $("#spies");
        Debug.cache["#mapInfo"] = $("#mapInfo");
*/
        
         
            
        if(!App.ie6) {   
            this.cache["#trace2"].css("opacity",0.8);
            this.cache["#trace1"].css("opacity",0.8);
            this.cache["#spies"].css("opacity",0.8);
            this.cache["#mapInfo"].css("opacity",0.8);
        }
        //counters['d12'] = new Date();
        
        
        
        
        
        
        
        //counters['d2'] = new Date(); //
        
        //$("#chrono").show();
    
        //alert(DEBUG);
        
        //this.objTrace2 = document.getElementById("trace2");
        //this.objTrace1 = document.getElementById("trace1");
        
        if( DEBUG <= 2 ) {
            //si le mode debug est 0 ou 1 ou 2
            //this.cache["#trace2"].hide();
            
        } else {
            //on est en mode 3 ou suppérieur
            this.cache["#trace2"].show();
            this.addFunctions(this.cache["#trace2"]);
            
        }
        
        if( DEBUG <= 1) {
            //mode 0 ou 1
            //this.cache["#trace1"].hide();
            
        } else {
            //mode 2 ou suppérieur
            this.cache["#trace1"].show();
            this.addFunctions(this.cache["#trace1"]);
            
        }
        
        if( DEBUG <= 0 ) {
            //mode 0
            //this.cache["#spies"].hide();
        
        } else {
            //mode 1 ou suppérieur
            this.cache["#spies"].show();
            this.addFunctions2(this.cache["#spies"]);
        }
        
        if( DEBUG <= 1 ) {
            //this.cache["#mapInfo"].hide();
        } else {
            this.cache["#mapInfo"].show();
        }
        
        

        this.initialized = true;
        
        
        
        
    },
    
    addFunctions : function(obj) {
        
        obj.click( function() { 
            //Debug.count(place + " clear");
            //Debug.displaySpies();
            obj.empty();
        });        
    },
    
    addFunctions2 : function(obj) {
    
        obj.click( function() {
            Debug.displaySpies();
            Debug.displayCounters();
        });        
    },
        
    initSpy: function(key) {
        if( DEBUG > 0 ) { 
            this.spies[key] = {start: new Date(), stop: null, duration: 0, last: null, count: 1};
        }
    },
    
    startSpy: function(key) {
        if( DEBUG > 0 ) { 
            this.restartSpy(key);
        }
    },
    
    restartSpy: function(key) {
        if( DEBUG > 0 ) { 
            if( this.spies[key] ) {
                this.spies[key].count += 1;
                this.spies[key].start = new Date();
                this.spies[key].stop = null;
            } else {
                this.initSpy(key);
            }
        }
    },

    stopSpy: function(key) {
        if( DEBUG > 0 ) { 
            if( this.spies[key] ) {
                var s = this.spies[key];
                s.stop = new Date();
                s.duration += s.stop - s.start;
                s.last = s.stop - s.start;
            } else {
                //alert(key + " stopped but not started...");
                //Debug.count("error:" + key);
                //Debug.displaySpies();
            }
        }
    },
    
    count: function(key) {
    
        if( DEBUG > 0 ) { 
            if( this.numbers[key] ) {
                this.numbers[key] += 1;
            } else {
                this.numbers[key] = 1;
            }
        }
    },
     
    displaySpies: function() {
        
        if( DEBUG >= 1 ) {   

            var a = [ 'Spies: <br>' ];
            for (var k in Debug.spies) {
                a.push( "<strong>" , k , '</strong> ' , Debug.spies[k].duration , "ms<br>- " , Debug.spies[k].count , " calls. Last call: " , Debug.spies[k].last , "ms<br>" ) ;
            }
            //affichage des compteurs
            a.push( "Numbers: <br>" ) ;
            for (var k in Debug.numbers) {
                a.push( "<strong>" , k , '</strong> ' , Debug.numbers[k] , "<br>" ) ;
            }
            
            //alert(a);
            Debug.cache["#spies"].html(a.join(''));
            
            
        
        }
    },

    trace: function(text) {
        
        //this.count(text);
        var time = new Date() - counters['startTime'] ;
        text += " @" + time + "ms";
        this.trace2('<em>' + text + '</em>');
        
        if( DEBUG >= 2 ) {   
            this.cache["#trace1"].prepend(text + "<br>");

            /*
            if(this.initialized) {
                this.cache["#trace1"].scrollTop = this.cache["#trace1"].scrollHeight;
            }
            */
            
        }

    },
    
    trace2: function(text) {
        
        //this.count(text);
        
        if( DEBUG >= 3 ) {   
            this.cache["#trace2"].prepend(text + "<br>");
            
            /*
            if(this.initialized) {
                this.cache["#trace2"].scrollTop = this.cache["#trace2"].scrollHeight;
            }
            */
            
        }

    },
    
    trace3: function(text) {
    
        //this.count(text);
        
        if( DEBUG >= 4 ) {
            this.trace2(text);
        }
    },
    
    stop: function(text) {
        if( DEBUG > -10 ) {
            var time = new Date() - counters['startTime'] ;
            this.trace("<strong>STOP: </strong>" + text + " @" + time + " ms");
            alert("stop: " + text + " @" + time + " ms");
            
        }
    },
    
    displayMapInfo: function() {
        if( DEBUG > -1 ) {
            var s = App.bigMap.map.getBounds().getSouthWest().lat();
            var w = App.bigMap.map.getBounds().getSouthWest().lng();
            var n = App.bigMap.map.getBounds().getNorthEast().lat();
            var e = App.bigMap.map.getBounds().getNorthEast().lng();
        
            var html = "<table><tr><td>map</td><td>n:" + n + "</td><td>s:" + s + "</td><td>w:" + w + "</td><td>e:" + e + "</td><td>z:" + App.bigMap.zoom + "</td></tr>";
            html += "<tr><td>goods</td><td>n:" + App.goods.n + "</td><td>s:" + App.goods.s + "</td><td>w:" + App.goods.w + "</td><td>e:" + App.goods.e + "</td><td>nb: " + App.goods.nbLoad + "</td></tr></table>";
            this.cache["#mapInfo"].html(html);
        }
    },
    
    displayCounters: function() {
        
        
        
        if( DEBUG >= 1 ) {   
    
            var a = '';
            var t = 0;
            for (var k in counters) {
                t = counters[k] - counters['startTime'];    
                a = "<strong>" + k + " @ </strong>" + t + " ms<br>" + a;
            }
            

            this.trace(a);
        
        }
 
 
 
    
       

        

        
    },
    
    exit: function() {
        if( DEBUG > -99 ) {
            Debug.stop("exit");
            Debug.displaySpies();
            Debug.displayCounters();
            //va faire crasher javascript...
            //window.stop();
            //document.execCommand('Stop');
            ceciEstUneERREUR;
        }  
    }
    
};

var Chrono = {
    t: null,
    start: function() {
        this.t = new Date();
    },
    stop: function() {
        var s = new Date();
        var d = s - this.t;
        //$('#chrono').html("t: " + d + " ms");
        if( DEBUG >= -99 ) {
            alert("t: " + d + " ms");
        }
    }
};

var SpeedTest = {

    RunTest: function() {
        
       //Debug.trace("SpeedTest.RunTest");
    
        var timeArray, timeDate, timeError, timeMath, timeRegEx, timeString, timeDOM, timeAjax;
        timeArray = this.Test_Array();
        timeDate = this.Test_Date();
        timeError = this.Test_Error(); 
        timeMath = this.Test_Math();
        timeRegEx = this.Test_RegEx();
        timeString = this.Test_String();
        timeDOM = this.Test_DOM();
        //timeAjax = this.Test_Ajax();
        var timeTotal = timeArray + timeDate + timeError + timeMath + timeRegEx + timeString + timeDOM; // + timeAjax;
        
       //Debug.trace2("timeArray: " + timeArray);
       //Debug.trace2("timeDate: " + timeDate);
       //Debug.trace2("timeError: " + timeError);
       //Debug.trace2("timeMath: " + timeMath);
       //Debug.trace2("timeRegEx: " + timeRegEx);
       //Debug.trace2("timeString: " + timeString);
       //Debug.trace2("timeDom: " + timeDOM);
       //Debug.trace2("timeAjax: " + timeAjax);
       //Debug.trace("timeTotal: " + timeTotal);
        
        alert("SpeedTest Result: " + timeTotal + " ms");
    },
    
    Test_jQuery: function() {
        //on mesure le temps qu'il faut pour changer 1000 fois la couleur du menu langue
        
        var startTime = new Date() ;
        for( var i=0; i<=999; i++ ) {
            $("#lang li a").css("color","red");
            $("#lang li a").css("color","#ccc");
        }
        var result = (new Date() - startTime);
        
        //version optimisée:
        startTime = new Date() ;
        var e = $("#lang li a");
        for( var j=0; j<=999; j++ ) {
            e.css("color","red");
            e.css("color","#ccc");
        }       
        result += " " + (new Date() - startTime);
        return result;
       
       
       
    },
    

    Test_Array: function() {
        var startTime = new Date() ;
        var arr = new Array();
        for(var i=0; i<=94; i++)
            {	arr.push(i);}
        for(var i=0; i<=arr.length; i++)
        {
            arr.push( arr.pop());
            arr.reverse(arr.sort());
            arr.push(arr.splice(0,1));
        }
        arr = arr.join();
        return (new Date() - startTime);
    },
		
    Test_Date: function() {
        var startTime = new Date() ;
        var pharbor = new Date('December 7, 1941 07:48:00');
        for(var i=500;i<=2000;i++)
        {
            var dtDate = Date.parse('December 7, '+i+' 07:48:00');
            var diff = dtDate - pharbor;
        }
        return (new Date() - startTime);
    },

    Test_Error: function() {
        var startTime = new Date() ;
        for( var i = 0; i <= 50; i++ ) {
            try {
                throw new Error("Ungraceful Error");
            }
            catch (e) {
                try { 
                    throw new Error("Graceful Error"); 
                } 
                catch (e)  { 
                    this.Test_Error_isPrime(147457); //Do something CPU-intensive
                }
                finally	{
                    this.Test_Error_isPrime(147457); //Do something CPU-intensive
                }
            }
        }
        return (new Date() - startTime);
    },

    Test_Error_isPrime: function(PrimeTest) {
		for(i=2;i<=Math.sqrt(PrimeTest)+1;i++) {
			if (PrimeTest % i == 0) {
				return false;
			}
		}
		return true;
	},

    Test_Math: function() {
        var startTime = new Date() ;
        var a = 147457;
        for (i=0;i<10000;i++) {
            var angle = (Math.tan(Math.sin(Math.cos(Math.random()))));
            var x = (Math.sqrt(Math.abs(Math.log(Math.pow(angle,2)))));
        }
        return (new Date() - startTime);
    },

    Test_RegEx: function() {
        var startTime = new Date() ;
        var str = 'cdbbdbsbzcdbbdbsbzcdbbdbsbzcdbbdbsbzcdbbdbsbzcdbbdbsbzcdbbdbsbzcdbbdbsbzcdbbdbsbzcdbbdbsbzcdbbdbsbzcdbbdbsbzcdbbdbsbz';
        for (i=0;i<=20000;i++) {
            myRe = /d(b+)d/g; 
            myArray = myRe.exec(str);
        }
        return (new Date() - startTime);
    },

    Test_String: function() {
        var startTime = new Date() ;
        var str = "Do good? I? No! Evil anon I deliver. I maim nine more hero-men in Saginaw, sanitary sword a-tuck, Carol, I -- lo! -- rack, cut a drowsy rat in Aswan. I gas nine more hero-men in Miami. Reviled, I (Nona) live on. I do, O God!"; //http://www.rinkworks.com/words/palindromes.shtml
        for (i=0;i<=20;i++) {
            var strStrip = str;
            do {
                strStrip = strStrip.replace('?','');
                strStrip = strStrip.replace('!','');
                strStrip = strStrip.replace(',','');
                strStrip = strStrip.replace('.','');
                strStrip = strStrip.replace('(','');
                strStrip = strStrip.replace(')','');
                strStrip = strStrip.replace('-','');
                strStrip = strStrip.replace(' ','');
            } while (!(strStrip.indexOf('?') == -1 && strStrip.indexOf('!') == -1 && strStrip.indexOf(',') == -1 && strStrip.indexOf('.') == -1 && strStrip.indexOf('(') == -1 && strStrip.indexOf(')') == -1 && strStrip.indexOf('-') == -1 && strStrip.indexOf(' ') == -1))
            strStrip = strStrip.toLowerCase();
    
            for (c=0;c<=strStrip.length;c++) {
                strStrip = strStrip.substr(0,c) + strStrip.substr(c,strStrip.length);
            }
            
            strStripRev = strStrip.split();
            strStripRev = strStripRev.reverse();
            strStripRev= strStripRev.join();
            var isPalindrome = (strStrip == strStripRev);
        }
        return (new Date() - startTime);
    },

    Test_DOM: function() {
        var startTime = new Date() ;
        var elem = document.getElementById('chrono');
        for(i=0;i<=400;i++) {
            elem.style.top = i + 'px';
            elem.style.left = i + 'px';
            elem.innerHTML = elem.innerHTML + '..' + i;
        }
        elem.innerHTML = '';
        return (new Date() - startTime);
    },

    Test_Ajax: function() {
        var startTime = new Date() ;
        for( var i = 0; i <= 10000; i++ )
        {
            var ao_featured = new AjaxObject101();
        }
        return (new Date() - startTime);
    }
};

function AjaxObject() {

	this.createRequestObject = function() {

		var ro;

		var browser = navigator.appName;

		if ( browser == "Microsoft Internet Explorer") {

			try {

				ro = new ActiveXObject("Microsoft.XMLHTTP");

			}

			catch (e) {

				ro = new XMLHttpRequest();

			}

		}

		else {

			ro = new XMLHttpRequest();

		}

		return ro;

	}

	this.sndReq = function(action, url) {

		this.http.open(action,url);

		this.http.onreadystatechange = this.handleResponse;

		this.http.send(null);

	}

	this.handleResponse = function() {

		if ( me.http.readyState == 4) {

			var rawdata = me.http.responseText.split("|");

			for ( var i = 0; i < rawdata.length; i++ ) {

				var item = (rawdata[i]).split("=>");

				if (item[0] != "") {

					document.getElementById(item[0]).innerHTML = item[1];

				}

			}

		}

	}	

	var me = this;

	this.http = this.createRequestObject();

}

function AjaxObject101() {
	this.createRequestObject = function() {

		if (XMLHttpRequest) {
			var ro = new XMLHttpRequest();
		}
		else {
			var ro = new ActiveXObject("Microsoft.XMLHTTP");
		}


		return ro;
	}
	this.sndReq = function(action, url, data) {
		if (action.toUpperCase() == "POST") {
			this.http.open(action,url,true);
			this.http.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
			this.http.onreadystatechange = this.handleResponse;
			this.http.send(data);
		}
		else {
			this.http.open(action,url + '?' + data,true);
			this.http.onreadystatechange = this.handleResponse;
			this.http.send(null);
		}
	}
	this.handleResponse = function() {
		if ( me.http.readyState == 4) {
			if (typeof me.funcDone == 'function') { me.funcDone();}
			var rawdata = me.http.responseText.split("|");
			for ( var i = 0; i < rawdata.length; i++ ) {
				var item = (rawdata[i]).split("=>");
				if (item[0] != "") {
					if (item[1].substr(0,3) == "%V%" ) {
						document.getElementById(item[0]).value = item[1].substring(3);
					}
					else {
						document.getElementById(item[0]).innerHTML = item[1];
					}
				}
			}
		}
		if ((me.http.readyState == 1) && (typeof me.funcWait == 'function')) { me.funcWait(); }
	}
	var me = this;
	this.http = this.createRequestObject();
	
	var funcWait = null;
	var funcDone = null;
}


     
////////////////////////////////////////////////////////////////////////////////
// INIT
////////////////////////////////////////////////////////////////////////////////
//$(document).ready( function() { alert("block"); } );


//for( var i = 0 ; i < 100 ; i++ ) {
        Debug.cache["#trace2"] = $("#trace2");
        Debug.cache["#trace1"] = $("#trace1");
        Debug.cache["#spies"] = $("#spies");
        Debug.cache["#mapInfo"] = $("#mapInfo");
//§}

/* mauvaise idée...
var mem1 = $("#content");
for( var i = 0 ; i < 100 ; i++ ) {

        
        Debug.cache["#trace2"] = mem1.children("#trace2");
        Debug.cache["#trace1"] = mem1.children("#trace1");
        Debug.cache["#spies"] = mem1.children("#spies");
        Debug.cache["#mapInfo"] = mem1.children("#mapInfo");
}


counters['c'] = new Date();
*/

e['document'] = $(document);
e['document'].ready( function() { App.init(); } );
//$(window).unload( function () { App.unLoad(); } );
//window.onunload = App.unLoad;
window.onload = App.windowOnload;
