
$(document).ready(function() {

    if (jQuery.url.param("map") == 'open')
        showMap("fast");
    else
        hideMap("fast");

    showHideObject('facMore', 'fast');

    $('#txtSearch').focus(function() {
        $('#Search_EjDestination').val('Airport');
    });

    $('a[href*=#]').click(function() {
        if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '')
		 && location.hostname == this.hostname) {
            var $target = $(this.hash);
            $target = $target.length && $target || $('[name=' + this.hash.slice(1) + ']');
            if ($target.length) {
                var targetOffset = $target.offset().top;
                $('html,body').animate({ scrollTop: targetOffset }, 1000);
                return false;
            }
        }
    });

    $(".showCC").each(function() {
        $($(this)).bind('click', function(e) {
            $("#ccTimes").dialog({
                bgiframe: true,
                minHeight: 10,
                modal: true,
                overlay: {
                    backgroundColor: '#000',
                    opacity: 0.5
                }
            });

            $("#ccTimes").dialog('open');
        });
    });

    $(".hideCC").each(function() {
        $($(this)).bind('click', function(e) {
            $("#ccTimes").dialog('close');
        });
    });

});

var MarkersArray = [];

function setupMap() {
    // Set up map
    var googleMap = new google.maps.Map2(document.getElementById("GoogleMap"));
    $("#GoogleMap").data("googleMap", googleMap);

    GEvent.addListener(googleMap, "moveend", function() {
        geoCentricFilter();
    });

    // Centre map
    centreMap(mapCentre);

    // Set up map options
    googleMap.enableDoubleClickZoom();
    googleMap.enableContinuousZoom();

    googleMap.addControl(new google.maps.LargeMapControl(G_ANCHOR_TOP_LEFT));

    // thumbnail map
    var Tsize = new GSize(150, 150);
    googleMap.addControl(new GOverviewMapControl(Tsize));
    
    addEjDestinations(ejMarkers);

    $("#GoogleMap").data("loaded", true);
}

function drawMapMarkers() {
    // Add markers for each hotel    
    addHotels(markers);
}

function addHotels(hotels) {
    var hotelCount = hotels.length, busy = false;
    var maxPins = 50;

    // start with a clean slate
    removeMarkers();

    if (hotelCount == 0) return;

    var googleMap = $("#GoogleMap").data("googleMap");

    var itemIndex = 0;
    for (var hotelIndex = 0; hotelIndex < hotelCount && hotelIndex < maxPins; hotelIndex++) {
        var hotel = hotels[hotelIndex];

        //if (LatLongWithinMapBounds(googleMap, hotel.Latitude, hotel.Longitude)) {
        var marker = createMarkerLabel(hotel, itemIndex);
        MarkersArray[itemIndex] = marker;
        itemIndex++;

        googleMap.addOverlay(marker);
        //}
    }
}

function addEjDestinations(destinations) {
    if (destinations.length == 0) return;

    var googleMap = $("#GoogleMap").data("googleMap");

    var itemIndex = 0;
    for (var markerIndex = 0; markerIndex < destinations.length; markerIndex++) {
        var destination = destinations[markerIndex];
        var marker = createEjMarker(destination);
        googleMap.addOverlay(marker);
    }
}

function createEjMarker(destination) {
    var icon = new GIcon();
    icon.image = "/Partners/5655/airportmarker.png";
    icon.iconSize = new GSize(19, 33);
    icon.iconAnchor = new GPoint(9, 33);
    icon.infoWindowAnchor = new GPoint(10, 8);

    var markerOptions = {
        "title": destination.Name,
        "icon": icon,
        "clickable": false
    };

    var latlng = new GLatLng(destination.Latitude, destination.Longitude);
    var marker = new LabeledMarker(latlng, markerOptions);
    //var marker = new GMarker(latlng, markerOptions);    

    //google.maps.Event.addListener(marker, "click", openBalloonClosure(pin));

    return marker;
}

function showMap(speed, callback) {
    if ($("#GoogleMap").data("loaded") != true) {
        $("#GoogleMap").show(speed, function() {

            setupMap();
            if (callback != null) callback();

        });
    } else {
        $("#GoogleMap").show(speed, callback);
    }
    $('#toggleMap span').text(com.laterooms.microsites.HideMapText);
    $("div.indicate").css("display", "block");
}

function hideMap(speed) {
    $('#toggleMap span').text(com.laterooms.microsites.ShowMapText);
    $("#GoogleMap").hide(speed);
    $("div.indicate").css("display", "none");
}

function showHideMap(speed) {
    if ($("#GoogleMap").css("display") == "none") {
        showMap(speed);
    }
    else {
        hideMap(speed);
    }
}

function indicators() {
    if ($("#GoogleMap").css("display") == "none") {
        $("div.indicate").css("display", "none");
    }
    else {
        $("div.indicate").css("display", "block");
    }
}

function centreMap(geoCode) {
    var googleMap = $("#GoogleMap").data("googleMap");
    var zoom = $("#noSearchResults").val() == "false" ? 5 : 11;
    googleMap.setCenter(new google.maps.LatLng(geoCode.Latitude, geoCode.Longitude), zoom);
}

function geoCentricFilter() {
    var map = $("#GoogleMap").data("googleMap");
    var bounds = map.getBounds();

    var lat = (bounds.getNorthEast().lat() + bounds.getSouthWest().lat()) / 2;
    var lng = (bounds.getNorthEast().lng() + bounds.getSouthWest().lng()) / 2;

    //alert(lat + ", " + lng);

    filterHotelsByGeoCode(lat, lng);
}

function removeMarkers() {
    var googleMap = $("#GoogleMap").data("googleMap");

    for (var i = 0; i < MarkersArray.length; i++) {
        googleMap.removeOverlay(MarkersArray[i]);
    }

    // reset marker tracking
    MarkersArray = [];
}

function createMarkerLabel(pin, index) {
    var icon = new GIcon();
    icon.image = "/Partners/5655/hotelmarker.png";
    icon.iconSize = new GSize(19, 33);
    icon.iconAnchor = new GPoint(9, 33);
    icon.infoWindowAnchor = new GPoint(10, 8);

    var markerOptions = {
        "title": pin.Name,
        "icon": icon,
        "clickable": true,
        "labelText": index + 1,
        "labelOffset": new GSize(-15, -31)
    };

    var latlng = new GLatLng(pin.Latitude, pin.Longitude);
    var marker = new LabeledMarker(latlng, markerOptions);
    //var marker = new GMarker(latlng, markerOptions);    

    google.maps.Event.addListener(marker, "click", openBalloonClosure(pin));

    return marker;
}

function LatLongWithinMapBounds(map, lat, lon) {
    var bounds = map.getBounds();
    var minlatitude = bounds.getSouthWest().lat();
    var minlongitude = bounds.getSouthWest().lng();
    var maxlatitude = bounds.getNorthEast().lat();
    var maxlongitude = bounds.getNorthEast().lng();

    return !(lat < minlatitude || lat > maxlatitude || lon < minlongitude || lon > maxlongitude);
}

//function GetVisibleMapCentre(map) {
//    var bounds = map.getBounds();
//    var minlatitude = bounds.getSouthWest().lat();
//    var minlongitude = bounds.getSouthWest().lng();
//    var maxlatitude = bounds.getNorthEast().lat();
//    var maxlongitude = bounds.getNorthEast().lng();        

//    return !(lat < minlatitude || lat > maxlatitude || lon < minlongitude || lon > maxlongitude);
//}

function openBalloonClosure(pin) {
    function closure() {
        primeOpenBalloon(pin);
    }

    return closure;
}

function primeOpenBalloon(pin) {
    showMap('slow', function() {
        $.ajax({
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            url: '/' + basePath + 'Models/Services/Service.asmx/GetHotel',
            data: '{hotelRef: "' + pin.Ref + '"}',
            dataType: 'json',
            success: openHotelBalloon
        });
    });
}

function openHotelBalloon(response) {
    var hotel = response.d;

    var markerContent = getBalloonHtml(hotel.HotelId, hotel.Image, hotel.Name, hotel.StarNumber, hotel.StarImage, hotel.City, hotel.Dates, hotel.Rates);

    var googleMap = $("#GoogleMap").data("googleMap");

    googleMap.openInfoWindow(new GLatLng(hotel.Latitude, hotel.Longitude), markerContent, { pixelOffset: new GSize(0, -32) });
}

function showObject(speed, object) {
    $("#" + object).show(speed);
}

function hideObject(speed, object) {
    $("#" + object).hide(speed);
}

function showHideObject(object, speed) {
    if ($("#" + object).css("display") == "none") {
        showObject(speed, object);
    }
    else {
        hideObject(speed, object);
    }
}

function showHideObjectWithText(object, speed, anchor) {
    if ($("#" + object).css("display") == "none") {
        showObject(speed, object);
        $("#" + anchor).text(com.laterooms.microsites.less);
    }
    else {
        hideObject(speed, object);
        $("#" + anchor).text(com.laterooms.microsites.more);
    }
}