var map = null;

function initialize() {
    if ($('#map').length > 0) {
        map = new google.maps.Map2(document.getElementById("map"));
        map.enableScrollWheelZoom();

        map.setCenter(new google.maps.LatLng(46.997114,-71.06369), 10);

        map.addControl(new GLargeMapControl3D());
        map.addControl(new GMapTypeControl());

        var msaIcon = new GIcon();
        msaIcon.image = "/++resource++velirium.hebergement.images/icone-msa.png";
        msaIcon.iconSize = new GSize(70, 45);
        msaIcon.iconAnchor = new GPoint(35, 22);
        msaIcon.infoWindowAnchor = new GPoint(0, 0);
        msaOptions = {icon: msaIcon};
        msaMarker = new GMarker(new GLatLng(47.074798, -70.906856), msaOptions);
        map.addOverlay(msaMarker);


        var i = 0;
        var h = null;
        for (i = 0; i < listeHebergeurs.length; i++) {
            h = listeHebergeurs[i];
            var point = new GLatLng(h['lat'],
                                    h['lon']);
            createMarker(point, h, h['cat']);
        }

        ResizeHotelResults(map);
    }
}

markers = [];

function createMarker(point, h, cat) {
    // Create our "tiny" marker icon
    var tinyIcon = new GIcon();
    tinyIcon.image = "/++resource++velirium.hebergement.images/mm_20_results-" + cat + ".png";
    tinyIcon.shadow = "/++resource++velirium.hebergement.images/mm_20_shadow.png";
    tinyIcon.iconSize = new GSize(12, 20);
    tinyIcon.shadowSize = new GSize(22, 20);
    tinyIcon.iconAnchor = new GPoint(6, 20);
    tinyIcon.infoWindowAnchor = new GPoint(5, 1);

    var markerOptions = { icon:tinyIcon };

    var marker = new GMarker(point, markerOptions);
    markers.push(marker);

    map.addOverlay(marker);
    var myHtml = $('#popup-h-' + h['id']).html();
    var myPoint = point;
    GEvent.addListener(marker, "click", function() {
        map.openInfoWindowHtml(myPoint, myHtml, {maxWidth:360});
    });
    $('#listing-h-' + h['id'] + ' h2 a').click(function() {
        map.panTo(myPoint);
        map.openInfoWindowHtml(myPoint, myHtml, {maxWidth:360});
        return false;
    });
}

google.setOnLoadCallback(initialize);

jQuery(window).unload(function() {
    GUnload();
});

function centrerCarte(lat, lon, zoom) {
    map.setZoom(zoom);
    map.panTo(new GLatLng(lat, lon));
}

function ClearHotelResults(){

    //clear visible results
    $('.hotelCol .line').remove();

    //clear hidden bottom divs
    $('#hidden_hebergeurs').children().remove()

    //clear google map
    $(markers).each( function(i,marker){
        map.removeOverlay(marker);
    });

}

function UpdateHotelResults(p){

    $('.firstCol');


    //build get params
    var params = [];

    params.push('&ajax=1');

    var proximites = $("input:checkbox.chkProximite:checked");
    for(var i=0; i<proximites.length; i++)
        params.push( '&proximites=' + $(proximites[i]).val() );


    var categories = $("input:checkbox.chkCategories:checked");
    for(var i=0; i<categories.length; i++)
        params.push( '&categories=' + $(categories[i]).val() );

    if( !p ) p = 1;

    params.push( '&p=' + p );


    //array 'params' becomes a string
    if(params)
        params = params.join('').replace( new RegExp('^&'), '?');
    else
        params = '';


    $('.hotelCol').html( '<img id="hotel_loading_spinner" src="/++resource++velirium.hebergement.images/spinner.gif" alt="" />' );


    $.ajax({
        url: 'hebergement_ajaxfilter_view' + params,
        //data: query,
        type: 'GET',
        dataType: 'json',
        success: function(results){

            ClearHotelResults();
            $('.hotelCol').html(results.visible_hebergeurs_div);
            $('#hidden_hebergeurs').html(results.hidden_hebergeurs_div);

            if( results.nb_pages > 1 )
                $('.rightFooter').html( results.paging );
            else
                $('.rightFooter').html('');



            $(results.hebergeurs).each( function(i, h){
                var point = new GLatLng(h['lat'], h['lon']);
                createMarker(point, h, h['cat']);
            });

        }
    });
}

function ResizeHotelResults(map){
    if ($('#map').length > 0) {

        // agrandir la map en fonction de la taille de la fenetre
        var w_height = $(window).height();
        var map_height = w_height - $('#header').height() - $('.leftFooter').height() - 11;
        $('#map').css('height', map_height + 'px');
        map.checkResize();

        //resultats de recherche: ajuster la hauteur de la div avec la Google Map.
        var leftcol_bottom = $('.leftCol').offset().top + $('.leftCol').height();
        var hoteldiv_min_height = leftcol_bottom - $('.hotelCol').offset().top;
        $('.hotelCol').css('min-height', Math.floor(hoteldiv_min_height)-11);
        $('.hotelCol').css('max-height', Math.floor(hoteldiv_min_height)-11);

        //that one's for IE6
        $('.hotelCol').css('height', Math.floor(hoteldiv_min_height)-11);
    }
}

var pageIsLoaded = false;

$( function(){

    $('#lien-qc').click(function() {
        centrerCarte('46.817037', '-71.214066', 13);
    });
    $('#lien-msa').click(function() {
        centrerCarte('47.067316', '-70.933228', 11);
    });

    $('a#btn-reserver').click(function() {
        var $checkbox = $('#checkbox-accept');
        if ( ! $checkbox.attr('checked') ) {
            $('#avertissement-accept').show();
            return false;
        }
        else {
            // le lien poursuit son cours normal
            $('#avertissement-accept').hide();
        }
    });


    $('.firstCol input').click( function(){
        UpdateHotelResults();
    });

    $('.twoCol input').click( function(){
        UpdateHotelResults();
    });


    //lien "fermer" dans la page de détail d'un hébergeur
    $('#btnCloseHebergeur').click( function(){
        window.close();
    });

    $(window).resize(function() {
        if(map)
            ResizeHotelResults(map);
    });



});

