var h = 0;
var w = 760;
var initialized = false;
var map = null;
var zoom = 15;
var actual_nh = 0;
var actual_resto = null;
var marker = new Array;
var idrIcon = new GIcon();
var idrIcon_sm = new GIcon();
var pdjIcon = new GIcon();
var pdjIcon_sm = new GIcon();
var allowedBounds = null;
var geocoder = new GClientGeocoder();
var prev_pin = null;


function loadIcons(){
    idrIcon.image = '/'+idr_public_folder+'/images/markers/grey/image.png';
    idrIcon.printImage = '/'+idr_public_folder+'/images/markers/grey/printImage.gif';
    idrIcon.mozPrintImage = '/'+idr_public_folder+'/images/markers/grey/mozPrintImage.gif';
    idrIcon.iconSize = new GSize(26,26);
    idrIcon.shadow = '/'+idr_public_folder+'/images/markers/grey/shadow.png';
    idrIcon.transparent = '/'+idr_public_folder+'/images/markers/greytransparent.png';
    idrIcon.shadowSize = new GSize(39,26);
    idrIcon.printShadow = '/'+idr_public_folder+'/images/markers/grey/printShadow.gif';
    idrIcon.iconAnchor = new GPoint(13,26);
    idrIcon.infoWindowAnchor = new GPoint(10,0);
    idrIcon.imageMap = [17,1,19,2,20,3,21,4,22,5,23,6,23,7,24,8,24,9,24,10,24,11,24,12,24,13,24,14,24,15,24,16,24,17,23,18,23,19,22,20,21,21,20,22,19,23,17,24,8,24,6,23,5,22,4,21,3,20,2,19,2,18,1,17,1,16,1,15,1,14,1,13,1,12,1,11,1,10,1,9,1,8,2,7,2,6,3,5,4,4,5,3,6,2,8,1];

    idrIcon_sm.image = '/'+idr_public_folder+'/images/markers/grey_sm/image.png';
    idrIcon_sm.printImage = '/'+idr_public_folder+'/images/markers/grey_sm/printImage.gif';
    idrIcon_sm.mozPrintImage = '/'+idr_public_folder+'/images/markers/grey_sm/mozPrintImage.gif';
    idrIcon_sm.iconSize = new GSize(13,13);
    idrIcon_sm.shadow = '/'+idr_public_folder+'/images/markers/grey_sm/shadow.png';
    idrIcon_sm.transparent = '/'+idr_public_folder+'/images/markers/grey_sm/transparent.png';
    idrIcon_sm.shadowSize = new GSize(20,13);
    idrIcon_sm.printShadow = '/'+idr_public_folder+'/images/markers/grey_sm/printShadow.gif';
    idrIcon_sm.iconAnchor = new GPoint(7,13);
    idrIcon_sm.infoWindowAnchor = new GPoint(5,0);
    idrIcon_sm.imageMap = [9,1,10,2,11,3,11,4,11,5,11,6,11,7,11,8,11,9,10,10,9,11,3,11,2,10,1,9,1,8,1,7,1,6,1,5,1,4,1,3,2,2,3,1];

    pdjIcon.image = '/'+idr_public_folder+'/images/markers/'+idr_host+'/image.png';
    pdjIcon.printImage = '/'+idr_public_folder+'/images/markers/'+idr_host+'/printImage.gif';
    pdjIcon.mozPrintImage = '/'+idr_public_folder+'/images/markers/'+idr_host+'/mozPrintImage.gif';
    pdjIcon.iconSize = new GSize(26,26);
    pdjIcon.shadow = '/'+idr_public_folder+'/images/markers/'+idr_host+'/shadow.png';
    pdjIcon.transparent = '/'+idr_public_folder+'/images/markers/'+idr_host+'/transparent.png';
    pdjIcon.shadowSize = new GSize(39,26);
    pdjIcon.printShadow = '/'+idr_public_folder+'/images/markers/'+idr_host+'/printShadow.gif';
    pdjIcon.iconAnchor = new GPoint(13,26);
    pdjIcon.infoWindowAnchor = new GPoint(10,0);
    pdjIcon.imageMap = [17,1,19,2,20,3,21,4,22,5,23,6,23,7,24,8,24,9,24,10,24,11,24,12,24,13,24,14,24,15,24,16,24,17,23,18,23,19,22,20,21,21,20,22,19,23,17,24,8,24,6,23,5,22,4,21,3,20,2,19,2,18,1,17,1,16,1,15,1,14,1,13,1,12,1,11,1,10,1,9,1,8,2,7,2,6,3,5,4,4,5,3,6,2,8,1];

    pdjIcon_sm.image = '/'+idr_public_folder+'/images/markers/'+idr_host+'_sm/image.png';
    pdjIcon_sm.printImage = '/'+idr_public_folder+'/images/markers/'+idr_host+'_sm/printImage.gif';
    pdjIcon_sm.mozPrintImage = '/'+idr_public_folder+'/images/markers/'+idr_host+'_sm/mozPrintImage.gif';
    pdjIcon_sm.iconSize = new GSize(13,13);
    pdjIcon_sm.shadow = '/'+idr_public_folder+'/images/markers/'+idr_host+'_sm/shadow.png';
    pdjIcon_sm.transparent = '/'+idr_public_folder+'/images/markers/'+idr_host+'_sm/transparent.png';
    pdjIcon_sm.shadowSize = new GSize(20,13);
    pdjIcon_sm.printShadow = '/'+idr_public_folder+'/images/markers/'+idr_host+'_sm/printShadow.gif';
    pdjIcon_sm.iconAnchor = new GPoint(7,13);
    pdjIcon_sm.infoWindowAnchor = new GPoint(5,0);
    pdjIcon_sm.imageMap = [9,0,10,1,11,2,12,3,12,4,12,5,12,6,12,7,12,8,12,9,11,10,10,11,9,12,3,12,2,11,1,10,0,9,0,8,0,7,0,6,0,5,0,4,0,3,1,2,2,1,3,0];
}


/**
 * Initialise l'affichage de la carte
 */
function initialize() {
    if (GBrowserIsCompatible()) {
        map = new GMap2(document.getElementById("gmap_map"));
        map.enableScrollWheelZoom();

        // Configuration des marqueurs personnalisés
        loadIcons();

        // Restriction des zooms
        var mt = map.getMapTypes();
        for (var i=0; i<mt.length; i++) {
            mt[i].getMinimumResolution = function() {
                return 12;
            }
            mt[i].getMaximumResolution = function() {
                return 19;
            }
        }

        // Restriction de l'affichage de la carte au canton de Genève
        GEvent.addListener(map, "move", function() {
            checkBounds();
        });

        // Tout le canton de Genève
        allowedBounds = new GLatLngBounds(new GLatLng(46.127627,5.955534), new GLatLng(46.37,6.3));
        // Juste la ville de Genève
        //allowedBounds = new GLatLngBounds(new GLatLng(46.127627,5.955534), new GLatLng(46.37,6.3));

        // Centre la carte sur Genève
        map.setCenter(new GLatLng(46.2038099,6.1399589), 16);
        // Supprime la vue Satellite non-mixte
        map.removeMapType(G_SATELLITE_MAP);
        var opts2 = {
            zoomInBtnTitle : "Zoom in",
            zoomOutBtnTitle : "Zoom out",
            moveNorthBtnTitle : "Nord",
            moveSouthBtnTitle : "Sud",
            moveEastBtnTitle : "Est",
            moveWestBtnTitle : "Ouest",
            homeBtnTitle : "Dernier résultat"
        };

        // Joute les controles personnaliséss de zoom
        map.addControl(new ExtLargeMapControl(opts2));
        map.addControl(new GMapTypeControl());

        initialized = true;
    }
}

/**
 * Renvoie la hauteur de la fenêtre
 */
function getWindowHeight() {
    if (window.self && self.innerHeight) {
        return self.innerHeight;
    }
    if (document.documentElement && document.documentElement.clientHeight) {
        return document.documentElement.clientHeight;
    }
    return 0;
}

/**
 * Recalcule la taille de la fenêtre
 */
function resize_content() {
    if (typeof( min_map_height ) != 'undefined') min_height = min_map_height;
    else min_height = 455;

    var gmapBorderWidth = 17;
    var marginlandr = 2*gmapBorderWidth;
    var hauteur = getWindowHeight()-190;
    if (hauteur < min_height) hauteur = min_height;
    if (typeof( max_map_height ) != 'undefined' ) {
        if (max_map_height != null) hauteur = max_map_height;
    }
    $('#gmap').css("height",(hauteur)+"px");

    $('#gmap_left').css("height",(hauteur-marginlandr)+"px");
    $('#gmap_right').css("height",(hauteur-marginlandr)+"px");
    $('#gmap_map').css("height",(hauteur-marginlandr)+"px");
    $('#ds_v_1').css("height",(hauteur-marginlandr)+"px");
    $('#ds_v_2').css("height",(hauteur-marginlandr)+"px");
    $('#ds_v_3').css("height",(hauteur-marginlandr)+"px");
    $('#ds_v_4').css("height",(hauteur-marginlandr)+"px");
    $('#ds_v_5').css("height",(hauteur-marginlandr)+"px");
    $('#ds_v2_1').css("height",(hauteur-marginlandr)+"px");
    $('#ds_v2_2').css("height",(hauteur-marginlandr)+"px");
    $('#ds_v2_3').css("height",(hauteur-marginlandr)+"px");
    $('#ds_v2_4').css("height",(hauteur-marginlandr)+"px");
    $('#ds_v2_5').css("height",(hauteur-marginlandr)+"px");

    h = (hauteur-marginlandr);

    $('#ds_h2_1').css("top",(hauteur+102)+"px");
    $('#ds_h2_2').css("top",(hauteur+102)+"px");
    $('#ds_h2_3').css("top",(hauteur+102)+"px");
    $('#ds_h2_4').css("top",(hauteur+102)+"px");
    $('#ds_h2_5').css("top",(hauteur+102)+"px");

    $('options_column').css("height",(hauteur)+"px");

    if ($('#liste_restos_ul')) {
        $('#liste_restos').css("height",(hauteur)+"px");
        $('#liste_restos_ul').css("height",(hauteur-100)+"px");
    }
    if (map != null)
    map.checkResize();
}

/**
 * Change l'onglet de la fiche de détail d'un restaurant
 */
function change_tab(tab,resto_uid) {
    $('#resto_tab_'+resto_uid+'_pdj').removeClass('selected');
    $('#resto_tab_'+resto_uid+'_infosprat').removeClass('selected');
    $('#resto_tab_'+resto_uid+'_menupdf').removeClass('selected');
    $('#resto_tab_'+resto_uid+'_photos').removeClass('selected');

    $('#resto_'+resto_uid+'_pdj').hide();
    $('#resto_'+resto_uid+'_infosprat').hide();
    $('#resto_'+resto_uid+'_menupdf').hide();
    $('#resto_'+resto_uid+'_photos').hide();

    $('#resto_tab_'+resto_uid+'_'+tab).addClass('selected');
    $('#resto_'+resto_uid+'_'+tab).show();

    if (tab == 'photos') {
        $(function() {
            $('#uid_photos a').lightBox({
                imageLoading: '/'+idr_public_folder+'/images/loading.gif',
                imageBtnClose: '/'+idr_public_folder+'/images/closelabel.gif',
                imageBtnPrev: '/'+idr_public_folder+'/images/prevlabel.gif',
                imageBtnNext: '/'+idr_public_folder+'/images/nextlabel.gif',
                txtImage: 'Images',
                txtOf: 'sur',
                imageArray : [],
                activeImage : 0

            });
        });
    }
}


function RestoTabs() {
    $("#ficheRestoTabs").tabs();
    $('#ficheRestoTabs .tab_photos a').lightBox({
                imageLoading: '/'+idr_public_folder+'/images/loading.gif',
                imageBtnClose: '/'+idr_public_folder+'/images/closelabel.gif',
                imageBtnPrev: '/'+idr_public_folder+'/images/prevlabel.gif',
                imageBtnNext: '/'+idr_public_folder+'/images/nextlabel.gif',
                txtImage: 'Images',
                txtOf: 'sur',
                imageArray : [],
                activeImage : 0

            });
}


/**
 * Change l'onglet du plat du jour
 */
function change_pdjday(day,resto_uid) {
    $('#pdjday_link_lun').removeClass('selected');
    $('#pdjday_link_mar').removeClass('selected');
    $('#pdjday_link_mer').removeClass('selected');
    $('#pdjday_link_jeu').removeClass('selected');
    $('#pdjday_link_ven').removeClass('selected');

    $('#pdj_'+resto_uid+'_lun').hide();
    $('#pdj_'+resto_uid+'_mar').hide();
    $('#pdj_'+resto_uid+'_mer').hide();
    $('#pdj_'+resto_uid+'_jeu').hide();
    $('#pdj_'+resto_uid+'_ven').hide();

    $('#pdjday_link_'+day).addClass('selected');
    $('#pdj_'+resto_uid+'_'+day).show();
}

/**
 * Recentre la carte sur le quartier choisir
 * Initialise la carte, si ce n'est déjà fait
 */
function showNeighborhood(nh_id,from) {

    if (actual_resto != null) marker[actual_resto].closeExtInfoWindow(map);

    idr_initMap();
    razForm('searchPdj');
    $('#neighborhood_sel').val(nh_id);
    actual_nh = nh_id;
    map.setCenter(new GLatLng(nh[nh_id][0], nh[nh_id][1]), nh[nh_id][2]);

    if (actual_resto != null) marker[actual_resto].closeExtInfoWindow(map);

    if (from != 'ajax') {
        clearMap();


	// On va chercher la liste des marqueurs à afficher.
	    var serial = '';
	    var names = '';
	
	    $('#searchPdj input[type=checkbox]').each(
	        function(){
	            names = names + '&'+this.name+'='+this.value;
	            if($(this).is(':checked')) serial = serial + '&'+this.name+'=1';
	        }
	
	    );
	    $("#debug_ie").html(serial);


        $.ajax({
            type: "GET",
            data: serial+$('#searchPdj').formSerialize()+"&searchPdj=1&from="+from+"&neighborhoods=1&w="+w+"&h="+h,
            url: "/ajax/markers/",
            dataType: "script",

            complete: function(html){
                $('#loading_box').hide();
            }

        });

    }
}


/**
 *  Vide le champ de recherche si "Restaurant, Rue" y est indiqué
 */
function clearSearchForm() {
    // si il n'y a aucun texte dans le champ de recherche, on met une valeur par défaut
    if($('#idr_searchForm').val() == '') {
        $('#idr_searchForm').val('Restaurant, Rue');
        $('#idr_searchForm_close').hide();
    }
    // Si c'est la valeur par défaut, on vide le champ de recherche
    else if($('#idr_searchForm').val() == 'Restaurant, Rue') {
        $('#idr_searchForm').val('');
    }
}


/**
 * Remise à zéro d'un groupe d'options avec popup
 */
function razOpt(set) {
    // Décoche les case dans le popup
    $(".set_checkboxes input[type=checkbox]").each(
        function() {
            $('#'+this.id).removeAttr("checked");
        }
    );
    // On décoche les checkbox dans la colonne de droite
    $("#"+set+"_div input").each(
        function() {
            $('#'+this.id).removeAttr("checked");
        }
    );
    // Cache les cases à cocher dans la colonne de droite
    $("#"+set+"_div .set_tr_opt").each(
        function() {
            this.style.display = 'none';
        }
    );
    // On affiche les intulés par défaut pour les liens ouvrant les popup
    $("#"+set+"_btn span.opt").text('Choisir ...');
    $("#"+set+"_btn span.def").text('Changer ...');
}


/**
 * Remise à zéro d'un groupe d'options avec popup
 */
function razSpe(set,opt) {
    // Décoche les case dans le popup
    $(".set_checkboxes input[type=checkbox]").each(
        function() {
            if (this.id != set+'_'+opt+'_dialog'){
                $('#'+this.id).removeAttr("checked");
            }
        }
    );
    // On décoche les checkbox des spécialités dans la colonne de droite
    $("#spe_div input").each(
        function() {
            $('#'+this.id).removeAttr("checked");
        }
    );
    // On décoche les checkbox des types de cuisine dans la colonne de droite
    $("#typ_div input").each(
        function() {
            $('#'+this.id).removeAttr("checked");
        }
    );
    // Cache les cases à cocher des spécialités dans la colonne de droite
    $("#spe_div .set_tr_opt").each(
        function() {
            this.style.display = 'none';
        }
    );
    // Cache les cases à cocher des types de cuisine dans la colonne de droite
    $("#typ_div .set_tr_opt").each(
        function() {
            this.style.display = 'none';
        }
    );
    // On affiche les intulés par défaut pour les liens ouvrant les popup
    $("#typ_btn span.opt").text('Choisir ...');
    $("#typ_btn span.def").text('Changer ...');
}

/**
 * Remise à zéro de l'ensemble des options de la colonne de droite
 */
function raz(){

    // On enlève l'éventuel class select des autres options
    $('.set_checkboxes li').each(
        function() {
            $('#'+this.id).removeClass('selected');
        }
    );
    // On ferme tous les menus de droite
    razRightMenus();
    // Remise à zéro des champs
    razForm('searchResto');
    // Réaffichage de l'ensemble des restaurants
    updateMarkers('searchPdj');
    // On cache le bouton de remise à zéro
    $('#raz_btn').hide();
}



/**
 * Remet à zéro les formulaires de droite
 */
function razForm(form) {
    if (form == 'searchPdj') {
        $('#idr_searchForm').val('Restaurant, Rue');
        $('#idr_searchForm_close').hide();
    }
    else if (form == 'searchResto') {

        // Remet à zéro les menus déroulants
        $('#searchPdj select option').each(
            function(){
                $(this).removeAttr("selected");
            }
        );
        // On décoche toutes les cases coches
        $('#searchPdj input[type=checkbox]').each(
            function(){
                $(this).removeAttr("checked");
            }
        );

        // Seule l'option prix max d'un plat du jour doit sélectionner l'ultime option
        $('#pdj_max').val(0);
    }
}


/**
 * Remet la spécialité à zéro si un type de cuisine est choisi... et vice versa.
 */
function razCuisine(selEl) {
    if (selEl == 'spe') {
        // Remet à zéro les types de cuisines
        $('#searchPdj select[name=typ] option').each(
            function(){
                $(this).removeAttr("selected");
            }
        );
    }
    else if (selEl == 'typ') {
        // Remet à zéro les spécialités
        $('#searchPdj select[name=spe] option').each(
            function(){
                $(this).removeAttr("selected");
            }
        );
    }
}


/**
 * On ferme les menus ouverts
 */
function razRightMenus() {
    $('#options_column .formSection').each(
        function() {
            $(this).removeClass('selected');
            $(this).removeClass('opened');

        }
    );
    $('#options_column .formSection .head').each(
        function() {
            $(this).children().addClass("ui-icon-triangle-1-e");
            $(this).children().removeClass("ui-icon-triangle-1-s");
            $(this).next().hide();

        }
    );
}

/**
 * Affuche le bouton de remise à zéro
 */
function showRazBtn() {
    $('#raz_btn').show();
    //$("#raz_btn").effect('highlight',{color:'#'+idr_hosts_colors},1000);
    //$("#raz_btn").effect('highlight',{color:'#'+idr_hosts_colors},500);

}


/**
 *
 */
function setUpdate(browser,set,opt) {
    if (set == 'spe' ||set == 'typ') razSpe(set,opt);

    // On enlève l'éventuel class select des autres options
    $('.set_checkboxes li').each(
        function() {
            $('#'+this.id).removeClass('selected');
        }
    );


// IE ne se comporte pas comme les autres.. Ceci est une astuce pour qu'il se comporte comme il se doit
    if (browser == 'ie'){
        // On cache l'option décochée cochée dans la colonne de droite
        if ($('#'+set+'_'+opt+'_dialog').attr("checked")) {
             $('#'+set+'_'+opt+'_tr').hide();
            $('#'+set+'_'+opt+'_id').removeAttr("checked");
        }
        // et on l'affiche si elle est cochée
        else {
            $('#'+set+'_'+opt+'_tr').show();
            $('#'+set+'_'+opt+'_id').attr("checked", "checked");
            $('#'+set+'_'+opt+'_dialog_li').addClass('selected');
        }
    }
    else {
        // On affiche l'option cochée dans la colonne de droite
        if ($('#'+set+'_'+opt+'_dialog').attr("checked")) {
            $('#'+set+'_'+opt+'_tr').show();
            $('#'+set+'_'+opt+'_id').attr("checked", "checked");
            $('#'+set+'_'+opt+'_dialog_li').addClass('selected');
        }
        // et on la cache si elle est décochée
        else {
             $('#'+set+'_'+opt+'_tr').hide();
            $('#'+set+'_'+opt+'_id').removeAttr("checked");
        }
    }

    // On change les labels des boutons de la colonne de droite
    if($(".set_checkboxes input:checked").length > 0) {
        $("#"+set+"_btn span").text('Changer ...');
        showRazBtn();
    }
    else {
        $("#"+set+"_btn span").text('Choisir ...');
    }

}

/**
 * Ouvre un des sites idresto
 */
 function openSite(host){
     var url = '';
     if (host == 'pdj') url = 'http://www.platdujour.'+idr_mode+'/';
     if (host == 'dim') url = 'http://www.dimancheresto.'+idr_mode+'/';
     if (host == 'lun') url = 'http://www.lundiresto.'+idr_mode+'/';
     if (host == 'gen') url = 'http://www.restogeneve.'+idr_mode+'/';
     if (host == 'pre') url = 'http://www.restorapido.'+idr_mode+'/';

     window.location = url;
 }


function getAddressPosition(address){
        address = address+', Genève, Suisse';

        if (address != ''){
            geocoder.getLatLng(address,function(point){
                if (point != null){
                    map.setCenter(new GLatLng(point.lat(), point.lng()), 16);

	    			$("#debug_ie").html(point.lat()+' , '+point.lng());
	    			
	    			if (point.lat() == '46.2038099' && point.lng() == '6.1399589')
                    alert("Aucun restaurant ne correspond à votre recherche. Essayez à nouveau.");
	    			
	    			
                    if (prev_pin) {
                        map.removeOverlay(prev_pin);
                        prev_pin = null;
                    }
                    pin = new GMarker(point);
                    map.addOverlay(pin);
                    prev_pin = pin;

                }
                else{
                    alert("Aucun restaurant ne correspond à votre recherche. Essayez à nouveau.");
                }
            })
        }
        else{
            alert("Aucun restaurant ne correspond à votre recherche. Essayez à nouveau.");
        }
    }

function checkOpt(name) {
    if (!$('input[name='+name+']').attr('checked')) $('input[name='+name+']').attr('checked', false);
    else $('input[name='+name+']').attr('checked', true);
    return true;
}



/**
 * Met à jour les marqueurs sur le plan
 */
function updateMarkers(form) {

    // recherche par nom
    if (form == 'searchResto') {
        if ($('#idr_searchForm').val() == 'Restaurant, Rue') {
            // Si la valeur recherchée est la valeur par défaut, on ne fait rien
            return false;
        }
        else {
            // Sinon, on affiche le bouton de raz du formulaire de recherche
            $('#idr_searchForm_close').show();
            // On ferme tous les menus de droite
            razRightMenus();
            // On cache l'éventuel bouton de remise à zéro
            $('#raz_btn').hide();
        }
    }

    if (form == 'searchPdj') {
        showRazBtn();
    }

    // Remise à zéro du formulaire
    razForm(form);
    // Initialisation de l'affichage du plan (si ne n'est déjà fait)
    idr_initMap();
    // Si un restaurant est déjà affiché, on ferme sa bulle
    if (actual_resto != null) marker[actual_resto].closeExtInfoWindow(map);

    // Définition de l'ensemble des cases cochées à envoyer via le get
    var gp_data = '';

// ?? Toujours utile ?
    var names = '';

    $('#'+form+' input[type=checkbox]').each(
        function(){
// ?? Toujours utile ?
            names = names + '&'+this.name+'='+this.value;
            // Liste des valeurs à passer dans le get
            if($(this).is(':checked')) {
                gp_data = gp_data + '&'+this.name+'=1';
            }
        }
    );

    // Remet à zéro les menus déroulants
    $('#'+form+' select').each(
        function(){
            gp_data = gp_data + '&'+this.name+'='+this.value;
        }
    );

    // Message de debug pour Internet Explorer
//    $("#debug_ie").html(gp_data);

    // On va chercher la liste des marqueurs à afficher.
    $.ajax({
        type: "GET",
        data: gp_data+$('#'+form).formSerialize()+'&'+form+"=1&w="+w+"&h="+h,
        url: "/ajax/markers/",
        dataType: "script",

        complete: function(html){
            $('#loading_box').hide();
        }
    });
    return true;
}

