﻿

var googleMap;
var features = '';
var estabTypeControl;
var bounds;
var serviceReturned = false;
var lastMarker;
var lastSpid;
var lastWasAvailable;
var restoreWindow = false;
var restoreWindow = false;
var infoWindowOpen = false;
var currentMapType = null;
var swlat;
var swlng;
var nelat;
var nelng;
var firstLoad = true;

var arriveDate;
var numNights;
var numGuests;


function loaded() {
    setTimeout('document.getElementById(mapDivId).style.backgroundImage = "";', 1000);
    createMap();
    setupOnUnload();
}

function loadedWithAvailability() {
    setTimeout('document.getElementById(mapDivId).style.backgroundImage = "";', 1000);
    createMapWithAvailability();
    setupOnUnload();
}

function setupOnUnload() {
    var attrs = document.body.attributes;
    var unload = document.createAttribute('onunload');
    unload.nodeValue = 'GUnload()';
    attrs.setNamedItem(unload);
    isLoaded = true;
}



function activateMap(callback) {
    initSearch();
    var script = document.createElement("script");
    var src = "http://maps.google.com/maps?file=api&v=2&key=" + mapsKey + "&async=2&callback=" + callback;
    script.setAttribute("src", src);
    script.setAttribute("type", "text/javascript");
    document.documentElement.firstChild.appendChild(script);
}

function createMap() {
    if (GBrowserIsCompatible()) {
        setupMap();
        getMarkersUsingQueryString();
        qs = '';
    }
}

function createMapWithAvailability() {
    if (GBrowserIsCompatible()) {
        setupMap();
        getAvailableMarkersUsingQueryString();
    }
}

function setupMap() {
    bounds = new GLatLngBounds();
    setMapSize();
    googleMap = new GMap2(document.getElementById(mapDivId));
    googleMap.addControl(new GSmallMapControl());
    googleMap.addControl(new GMapTypeControl());
    googleMap.addControl(new GOverviewMapControl());
    googleMap.addControl(new GScaleControl()); 
    GEvent.addListener(googleMap, "moveend", function() {  getAllMarkers(); });
}

function getAvailableMarkersUsingQueryString() {
    getAvailabilityData();
    SearchService.FindEstablishmentsByMapBounds(0, 0, 0, 0, arriveDate, numNights, numGuests, qs, SucceededCallback, FailedCallBack);
}



function getAllMarkers() {
        getMarkersUsingBounds();
}


function setMapSize() {
    var mapdiv = document.getElementById(mapDivId);
    mapdiv.style.width = (100) + '%';
}


function getMarkersUsingLocationId() {
    if (serviceReturned == true) { return; }
    initSearch();
    getOtherFilters();
    getAvailabilityData();
    SearchService.FindEstablishmentsByLocationId(lastLocation,arriveDate, numNights, numGuests, SucceededCallback, FailedCallBack);    
}


function getMarkersUsingQueryString() {
    initSearch();
    getOtherFilters();
    SearchService.FindEstablishmentsByQueryString(qs, SucceededCallback, FailedCallBack);
}

function toProperCase(s) {
    return s.toLowerCase().replace(/^(.)|\s(.)/g,
          function($1) { return $1.toUpperCase(); });
}

function getAvailability() {
    //use last location, or bounds whichever is defined
    //also use filter constraints TODO:!
    
    if (!isLoaded) {
        activateMap('loadedWithAvailability');
    }
    else {
        getAllMarkers();
    }
}


function getAvailabilityData() {
    arriveDate = $get(arrivalDateControl).value;
    numGuests = $get(guestsTextBox).value;
    numNights = $get(nightsTextBox).value;

}


function resetLocation() {
    lastLocation = '';
}

function getMarkersUsingBounds() {
    if (serviceReturned == true) { return; } //prevents recursive gets of the same data
    resetLocation();

    // prevents re-gets when the screen auto-pans to accommodate an infowindow
    var currentInfoWindow = googleMap.getInfoWindow();
    if (!currentInfoWindow.isHidden()) { return; };

    initSearch();
    getCurrentBounds();
    getOtherFilters();
    getAvailabilityData();
    SearchService.FindEstablishmentsByMapBounds(swlat, swlng, nelat, nelng, arriveDate, numNights, numGuests, qs, SucceededCallbackBounds, FailedCallBack);
}


function getOtherFilters() {
    getPlaceTypeFilters();
}

function getCurrentBounds() {
    swlat = googleMap.getBounds().getSouthWest().lat();
    swlng = googleMap.getBounds().getSouthWest().lng();
    nelat = googleMap.getBounds().getNorthEast().lat();
    nelng = googleMap.getBounds().getNorthEast().lng();
}

function killMarkerGeoData() {
    SearchService.KillMarkerGeoData(lastSpid);
}

function initSearch() {    
    $get(progressIndicator).style.display = 'block';           
}

//assigns features global from currently selected features
function checkChanged() {
    features = '';
    var frm = document.forms[0];
    for (i = 0; i < frm.elements.length; i++) {
        if (frm.elements[i].type == "checkbox") {
            if (frm.elements[i].checked) {
                features += '|' + frm.elements[i].parentNode.attributes['id'].nodeValue;
            }
        }
    }

    if (features != '') { features = features.slice(1) }; //trim leading |
    qs = "fid=" + features;
    getMarkersUsingBounds();
}

function FailedCallBack() {
    serviceReturned = false;
    $get(progressIndicator).style.display = 'none';
}
function synchMarkerState() {
    var currentInfoWindow = googleMap.getInfoWindow();
    if (!currentInfoWindow.isHidden()) { restoreWindow = true };
}

function addMarkers(result) {

    synchMarkerState();
    googleMap.clearOverlays();
    var points = result;
    if (points.length > 0) {
        var tokens = points.split('|');
        for (index = 0; index < tokens.length; index++) {

            //wrap in try and pray to ganesh
            try {
                var item = tokens[index];
                if (item.split(',').length == 6) {
                    var latitude = item.split(',')[0].replace('!', '');
                    var longitude = item.split(',')[1];
                    var title = item.split(',')[2];
                    var url = item.split(',')[3];
                    var spid = item.split(',')[4]
                    var availability = item.split(',')[5];

                    html = '<div class="earthSearchSmallInfoWindow"><a href="#" onclick="javascript:populateDiv(); return false;"><b>' + title + '<br/></b><img src="http://www.safarinow.com/db/id/' + spid + '/' + spid + 't.jpg" height="150px" width="200px" /></a><a href="javascript:killMarkerGeoData();">.</a><br clear="all"/></div>';
                    var marker = new GMarker(new GLatLng(latitude, longitude));
                    if (availability == 'True') { marker = new GMarker(new GLatLng(latitude, longitude), { icon: availableIcon() }); }

                }
                else {
                    //its a place
                    var latitude = tokens[index].split(',')[0].replace('!', '');
                    var longitude = tokens[index].split(',')[1];
                    var title = tokens[index].split(',')[2];
                    var url = tokens[index].split(',')[3];
                    var type = tokens[index].split(',')[4];
                    html = '<div class="earthSearchSmallInfoWindow"><a href="' + url + '"><b>' + title + '<br/></b> <br clear="all"/></div>';
                    var marker = new GMarker(new GLatLng(latitude, longitude), { icon: placeIcon(type) });
                }
                if (index == 0 && firstLoad) { googleMap.setCenter(new GLatLng(latitude, longitude, 13, G_HYBRID_MAP)); }
                updateMarker(marker, html, spid, availability);
                googleMap.addOverlay(marker);
            }
            catch (Error) {
                continue;
            }

        }
        googleMap.setMapType(G_HYBRID_MAP);
    }
    setSwitchToListingsViewUrl();
}



function availableIcon() {
    var icon = new GIcon();
    icon.image = "http://www.safarinow.com/search/images/marker_green.png";
    icon.shadow = "http://www.google.com/mapfiles/shadow50.png";
    icon.iconSize = new GSize(20, 34);
    icon.shadowSize = new GSize(37, 34);
    icon.iconAnchor = new GPoint(9, 34);
    icon.infoWindowAnchor = new GPoint(9, 2);
    icon.infoShadowAnchor = new GPoint(18, 25);
    icon.printImage = "http://www.google.com/mapfiles/markerie.gif";
    icon.mozPrintImage = "http://www.google.com/mapfiles/markerff.gif";
    icon.printShadow = "http://www.google.com/mapfiles/dithshadow.gif";
    icon.transparent = "http://www.google.com/mapfiles/markerTransparent.png";
    icon.imageMap = [9, 0, 6, 1, 4, 2, 2, 4, 0, 8, 0, 12, 1, 14, 2, 16, 5, 19, 7, 23, 8, 26, 9, 30, 9, 34, 11, 34, 11, 30, 12, 26, 13, 24, 14, 21, 16, 18, 18, 16, 20, 12, 20, 8, 18, 4, 16, 2, 15, 1, 13, 0];
    return icon;
}

function placeIcon(type) {
    var icon = new GIcon();
    icon.image = "http://www.safarinow.com/search/images/places/" + type + ".png";
    icon.shadow = "http://www.google.com/mapfiles/shadow50.png";
    icon.iconSize = new GSize(20, 34);
    icon.shadowSize = new GSize(37, 34);
    icon.iconAnchor = new GPoint(9, 34);
    icon.infoWindowAnchor = new GPoint(9, 2);
    icon.infoShadowAnchor = new GPoint(18, 25);
    icon.printImage = "http://www.google.com/mapfiles/markerie.gif";
    icon.mozPrintImage = "http://www.google.com/mapfiles/markerff.gif";
    icon.printShadow = "http://www.google.com/mapfiles/dithshadow.gif";
    icon.transparent = "http://www.google.com/mapfiles/markerTransparent.png";
    icon.imageMap = [9, 0, 6, 1, 4, 2, 2, 4, 0, 8, 0, 12, 1, 14, 2, 16, 5, 19, 7, 23, 8, 26, 9, 30, 9, 34, 11, 34, 11, 30, 12, 26, 13, 24, 14, 21, 16, 18, 18, 16, 20, 12, 20, 8, 18, 4, 16, 2, 15, 1, 13, 0];
    return icon;
}


function updateMarker(marker, html, spid, available) {
    GEvent.addListener(marker, "click", function() {
        marker.openInfoWindowHtml(html); lastMarker = marker; lastSpid = spid; lastWasAvailable = available
    });
    bounds.extend(marker.getPoint());
}

function populateDiv() {
    $get(progressIndicator).style.display = 'block';
    SearchService.GetEstablishmentHTML(lastSpid, lastWasAvailable, SucceededCallbackEstablishmentHtml, FailedCallBack);
}


function SucceededCallbackEstablishmentHtml(result) {
    result = '<div class="earthSearchInfoWindow">' + result + '<br clear="all" /></div>';
    lastMarker.openInfoWindowHtml(result);
    $get(progressIndicator).style.display = 'none';
}


function SucceededCallbackBounds(result) {
    serviceReturned = true;
    if (result != '') {
        addMarkers(result);
    }
    serviceReturned = false;
    endSearch();
}


function SucceededCallback(result) {
    serviceReturned = true;
    if (result != '') {
        addMarkers(result);
        googleMap.setZoom(googleMap.getBoundsZoomLevel(bounds));
        googleMap.setCenter(bounds.getCenter());
    }
    endSearch();
    serviceReturned = false;
}

function endSearch() {
    $get(progressIndicator).style.display = 'none';
}

function addPlaceMarkers(result) {
    synchMarkerState();
    var points = result;
    if (points.length > 0) {
        var tokens = points.split('|');
        var LatLongs = new Array(tokens.length - 1);

        for (index = 0; index < tokens.length; index++) {

            var latitude = tokens[index].split(',')[0].replace('!', '');
            var longitude = tokens[index].split(',')[1];
            var title = tokens[index].split(',')[2];
            var url = tokens[index].split(',')[3];
            var type = tokens[index].split(',')[4];
            html = '<div class="earthSearchSmallInfoWindow"><a href="' + title + '"><b>' + title + '<br/></b> <br clear="all"/></div>';
            var marker = new GMarker(new GLatLng(latitude, longitude), { icon: placeIcon(type) });
            if (index == 1 && firstLoad) { googleMap.setCenter(new GLatLng(latitude, longitude, 13, G_HYBRID_MAP)); }
            updateMarker(marker, html, 0, 'false');
            googleMap.addOverlay(marker);
        }
    }
    setSwitchToListingsViewUrl();
}

function checkPlaceTypeChanged() {
    if (!isLoaded) {
        activateMap('loaded');
    }
    else {
        getAllMarkers();
    }
}

function getPlaceTypeFilters() {
    placeTypes = '';
    var frm = document.forms[0];
    for (i = 0; i < frm.elements.length; i++) {
        if (frm.elements[i].type == "checkbox") {
            if (frm.elements[i].checked) {
                placeTypes += '|' + frm.elements[i].parentNode.attributes['id'].nodeValue;
            }
        }
    }

    if (placeTypes != '') { placeTypes = placeTypes.slice(1) }; //trim leading |
    qs += "&places=" + placeTypes;
}

function getPlaceMarkersUsingBounds() {
    initSearch();
    getCurrentBounds();
    SearchService.FindPlaceByMapBounds(swlat, swlng, nelat, nelng, qs, SucceededCallbackPlacesBounds, FailedCallBack);
}

function SucceededCallbackPlacesBounds(result) {
    serviceReturned = true;
    if (result != '') {
        addPlaceMarkers(result);
    }
    serviceReturned = false;
    endSearch();
}

function setSwitchToListingsViewUrl() {
    if (!firstLoad) {
        var locationString = '';
        var url;
        //combination of either location, or bounds + feature constraints
        if (lastLocation != '' && lastLocation != undefined && lastLocation != null) {
            var locationString = lastLocation;
            url = qs + '&location=' + locationString;

        }
        else {
            getCurrentBounds()
            url = qs + '&swlat=' + swlat + '&swlng=' + swlng + '&nelat=' + nelat + '&nelng=' + nelng;
        }

        url = '/search.aspx?' + url;
    }
    else {
        firstLoad = false;
    }
}




