var map = null;
var clickOverlay = null;
var clickLatLng = null;
var countrySearchAttempted = false;
var MAP_HOLDER = 'locationMap';
var hotelsPlottedPoints = new Array();
var HOME_LATITUDE = 0;  // DEFAULT LATITUDE
var HOME_LONGITUDE = 0; // DEFAULT LONGITUDE
var DEFAULT_ZOOM = 1;
var SINGLE_HOTEL_DEFAULT_ZOOM = 1;

function GM_InitializeMap() {														//INITIALIZE GOOGLE MAP
    if(GBrowserIsCompatible()) {
        map = new GMap2(getElement(MAP_HOLDER));
        if(enableMapControls) {
            map.addControl(new GMapTypeControl()); 								//CHOOSE Map Satellite Hybrid MAP TYPE
        }
        if(enableMapZoom) {
            map.addControl(new GSmallZoomControl()); 							//SMALL PLUS/MINUS ZOOM CONTROL
        }
        map.enableScrollWheelZoom();
        map.disableDoubleClickZoom();
    }
    if (map) {
        if (CURRENT_LOCATION && hotelsArray && CURRENT_LOCATION.length > 0 && hotelsArray.length > 0) {
            try {
                GM_Begin();
            } catch (e) {
                GM_HideMapHolder();
            }
        } else if (LATITUDE != 999 && LONGITUDE != 999 && ZOOM_LEVEL != 0) {
            map.setCenter(new GLatLng(LATITUDE, LONGITUDE), ZOOM_LEVEL);
        } else if (CURRENT_LOCATION && CURRENT_LOCATION.length > 0) {
            if (CURRENT_COUNTRY && CURRENT_COUNTRY.length > 0) {
                GM_GetCurrentLocationFromBedsLocationAndCountryName(CURRENT_LOCATION + ', ' + CURRENT_COUNTRY);
            } else {
                GM_GetCurrentLocationFromBedsLocationAndCountryName(CURRENT_LOCATION);
            }
        } else {
            //BROWSER NOT COMPATIBLE SO HIDE MAP
            GM_HideMapHolder();
        }
    }
}

function GM_Begin() {
    if (hotelsArray.length > 0) {
        if (hotelsArray.length === 1) {
            //IF THERE IS ONLY ONE HOTEL WE DO NOT WANT TO SetMapView AS THIS WILL RESET THE ZOOM LEVEL WHICH IS INVARIABLY INCORRECT
            if (parseFloat(hotelsArray[0].split(',')[4]) > 0) {
                var zoomLevel = parseFloat(hotelsArray[0].split(',')[4]);
            } else {
                var zoomLevel = SINGLE_HOTEL_DEFAULT_ZOOM;            
            }
            map.setCenter(new GLatLng(parseFloat(hotelsArray[0].split(',')[1]), parseFloat(hotelsArray[0].split(',')[2])), zoomLevel);
            GM_PlotHotels(); 														//PLOT THE HOTELS
        } else {
            map.setCenter(new GLatLng(parseFloat(hotelsArray[0].split(',')[1]), parseFloat(hotelsArray[0].split(',')[2])), DEFAULT_ZOOM);
            GM_PlotHotels(); 														//PLOT THE HOTELS
            GM_SetMapView(hotelsPlottedPoints); 									//ZOOM BASED ON ARRAY OF POINTS
        }        
    } else {
        //DEFAULT TO CURRENT COUNTRY BASED ON BEDS COUNTRY SET IN PAGE
        if (CURRENT_COUNTRY && CURRENT_COUNTRY.length > 0) {
            GM_GetCurrentLocationFromBedsLocationAndCountryName(CURRENT_LOCATION + ', ' + CURRENT_COUNTRY);
        } else {
            GM_GetCurrentLocationFromBedsLocationAndCountryName(CURRENT_LOCATION);
        } 
    }
}
function GM_PlotHotels() {
    if(hotelsArray.length > 0) {
        hotelsPlottedPoints = new Array(hotelsArray.length); 					//ADD THE POINT GM_AddHotelIcon TO AN ARRAY TO USE WITH GM_SetMapView
        for(i = 0; i < hotelsArray.length; i++) {
            hotelsPlottedPoints[i] = GM_AddHotelIcon(
														parseFloat(hotelsArray[i].split(',')[0]),
														parseFloat(hotelsArray[i].split(',')[1]),
														parseFloat(hotelsArray[i].split(',')[2])
												    );
        }
    }
}
function GM_AddHotelIcon(globalPropertyNodeId, latitude, longitude) {
    var point = new GLatLng(latitude, longitude);
    map.addOverlay(marker = new GMarker(point));
    GEvent.addListener(marker, 'mouseover', function() { GM_GetHotelGlobalPropertyInfo(this, globalPropertyNodeId) });
    GEvent.addListener(marker, 'mouseout', function() { hideWindow(globalPropertyNodeId) });
    return point;
}
function GM_GetCurrentLocationFromBedsLocationAndCountryName(location) {
    geocoder = new GClientGeocoder();
    if(geocoder) {
        geocoder.getLatLng(location, GM_onFoundResults_getCurrentLocationFromBedsLocationAndCountryName)
    }
}
function GM_onFoundResults_getCurrentLocationFromBedsLocationAndCountryName(point) {
    if (map) { 
        if(point) {																		//SET LOCATION TO CURRENT LOCATION/COUNTRY
            if(countrySearchAttempted) {
                map.setCenter(point, 4);
            } else {
                map.setCenter(point, 9);
            }
        } else if(CURRENT_COUNTRY.length > 0 && !countrySearchAttempted) {
            GM_GetCurrentLocationFromBedsLocationAndCountryName(CURRENT_COUNTRY); 	//ATTEMPT TO SEARCH FOR JUST COUNTRY
            countrySearchAttempted = true;
        } else {
            map.setCenter(new GLatLng(HOME_LATITUDE, HOME_LONGITUDE), 1); 			//REVERT BACK TO HOME LOCATION
        }
    }
}
function addCenterMarker(point) {
    map.addOverlay(marker = new GMarker(point));
}
/* AJAX CALLS START */
function GM_GetHotelGlobalPropertyInfo(marker, globalPropertyNodeId) {
    hotelClicked = marker;
    if(globalPropertyNodeId > 0) {
        ajaxObject = initAjaxObject();
        ajaxObject.onreadystatechange = processAjaxReadyState_GM_GetHotelGlobalPropertyInfo;
        ajaxObject.open('GET', '/ski/utility/hoteldescriptionxml.aspx?globalpropertynodeid=' + globalPropertyNodeId + '&ms=' + new Date().getTime(), true);
        ajaxObject.send('');
    }
}
function processAjaxReadyState_GM_GetHotelGlobalPropertyInfo() {
    if(ajaxObject.readyState == 4) {
        if(ajaxObject.status == '200') {
            hotelAddress = '';
            hotelDesc = '';
            starRating = '';
            if(ajaxObject.responseXML.getElementsByTagName('GlobalPropertyInfo')) {
                if(ajaxObject.responseXML.getElementsByTagName('GlobalPropertyInfo')[0]) {
                    globalPropertyNodeId = ajaxObject.responseXML.firstChild.getAttribute('GlobalPropertyNodeId');
                    hotelInfo = ajaxObject.responseXML.getElementsByTagName('GlobalPropertyInfo')[0];
                    if(hotelInfo.getElementsByTagName('HotelName')[0].childNodes[0].nodeValue) {
                        if(hotelInfo.getElementsByTagName('StarRating')[0].childNodes[0]) {
                            starRating = hotelInfo.getElementsByTagName('StarRating')[0].childNodes[0].nodeValue
                        }
                        customInfoWindow(hotelClicked, hotelInfo.getElementsByTagName('HotelName')[0].childNodes[0].nodeValue, starRating);
                        highlightHotel(globalPropertyNodeId);
                    }
                }
            }
            //DO NOT SET ajaxObject = null HERE AS IT CAUSES ERRORS IF 
            //WE HAVE MULIPLE CALLS TO THIS FUNCTION RUNNING AT THE SAME TIME
            //IT IS SET TO NULL ON window.onunload
        }
    }
}
/* AJAX CALLS END */
/* HELPER FUNCTIONS */
function GM_SetMapView(points) {														//ZOOMS MAP TO CORRECT ZOOM LEVEL BASED ON AN ARRAY OF HOTELS PLOTTED
    var bounds = new GLatLngBounds();
    for(var i = 0; i < points.length; i++) {
        bounds.extend(points[i]);
    }
    map.setZoom(map.getBoundsZoomLevel(bounds));
    map.setCenter(bounds.getCenter());
}
function getElement(elementId) {														//CROSS BROWSER document.getElementById
    if(document.getElementById) {
        return document.getElementById(elementId);
    } else {
        return document.all[elementId];
    }
}
function GM_HideMapHolder() {
    getElement(MAP_HOLDER).style.display = 'none';
}
if(window.addEventListener) {														//EXECUTED ON WINDOW LOAD/UNLOAD EVENT. ATTEMPTS FF/MOZ ETC THEN IE THEN OVERIDES window.onload/unload EVENTS
    window.addEventListener('load', function() { GM_InitializeMap(); }, false);
    window.addEventListener('unload', function() { CustomGUnload(); }, false);
} else if(window.attachEvent) {
    window.attachEvent('onload', GM_InitializeMap);
    window.attachEvent('onunload', CustomGUnload);
} else {
    window.onload = function() { GM_InitializeMap(); };
    window.onunload = function() { CustomGUnload(); };
}

function CustomGUnload() {
    ajaxObject = null;
    GUnload();
}

function highlightHotel(globalPropertyNodeId) {
    if(getElement('prop_' + globalPropertyNodeId)) {
        getElement('prop_' + globalPropertyNodeId).style.backgroundColor = '#ffebd6';
        getElement('prop_' + globalPropertyNodeId).style.border = 'solid 1px #ffb261';
    }
}
function unHighlightHotel(globalPropertyNodeId) {
    if(getElement('prop_' + globalPropertyNodeId)) {
        getElement('prop_' + globalPropertyNodeId).style.backgroundColor = 'transparent';
        getElement('prop_' + globalPropertyNodeId).style.border = 'solid 1px #fff';
    }
}

var customInfoDiv = document.createElement('div');
customInfoDiv.style.visibility = 'visible';
customInfoDiv.style.background = '#ffffff';
customInfoDiv.style.border = '1px solid #000000';
customInfoDiv.style.padding = '5px 10px';

function customInfoWindow(hotelClicked, hotelName, hotelStarRating) {
    if(hotelStarRating.length > 0) {
        customInfoDiv.innerHTML = hotelName + ' (' + hotelStarRating + '*)';
    } else {
        customInfoDiv.innerHTML = hotelName;
    }
    map.getContainer().appendChild(customInfoDiv);

    var x = 30;
    var y = 7;
    if(x > map.getSize().width - 120) {
        x = map.getSize().width - 120
    }
    if(y > map.getSize().height - 100) {
        y = map.getSize().height - 100
    }
    var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(x, y));
    pos.apply(customInfoDiv);
    customInfoDiv.style.visibility = 'visible';
}

function hideWindow(globalPropertyNodeId) {
    var allHotels = getElementsByClassName(document, 'h3', 'hotelname');
    for(var i = 0; i < allHotels.length; i++) {
        allHotels[i].style.backgroundColor = 'transparent';
        allHotels[i].style.border = 'solid 1px #fff';
    }
    unHighlightHotel(globalPropertyNodeId);
    customInfoDiv.innerHTML = '';
    customInfoDiv.style.visibility = 'hidden';
}

function getElementsByClassName(oElm, strTagName, strClassName) {
    var arrElements = (strTagName == '*' && oElm.all) ? oElm.all : oElm.getElementsByTagName(strTagName);
    var arrReturnElements = new Array();
    strClassName = strClassName.replace(/\-/g, '\\-');
    var oRegExp = new RegExp('(^|\\s)' + strClassName + '(\\s|$)');
    var oElement;
    for(var i = 0; i < arrElements.length; i++) {
        oElement = arrElements[i];
        if(oRegExp.test(oElement.className)) {
            arrReturnElements.push(oElement);
        }
    }
    return (arrReturnElements)
}

function initAjaxObject() {
    if(window.XMLHttpRequest) {
        // W3C METHOD
        return new XMLHttpRequest();
    } else if(window.ActiveXObject) {
        // IE METHOD
        return new ActiveXObject('Microsoft.XMLHTTP');
    } else {
        return;
    }
}

/* HELPER FUNCTIONS END */
