/* 
 * This is used by the main map page
 */

/*************** new code *********/
// filter tab initiating values and user values during the period of usage
var filterRef = {
    //this is the price filrer reference values we use to initiate the price filter
        //the lower and upper limits of the price slider
    lowerPriceLimit : 0,
    upperPriceLimit : 300,
        //what are the starting values of the filter
    startLowFilterPrice : 0,
    startHighFilterPrice : 300,

    //the states of the star filtering
    star_states : [0,0,0,0,0],

    getUpperPriceFilterValue : function(upperPriceVal){
    //strip out the plus sign out of the upper price and chk if we are at the upper range,
        //if we are then we need to make sure we need to set the upper limit to include ALL the hotels
        if(upperPriceVal.replace('+','') == filterRef.upperPriceLimit){
            return 100000000;
        }
        else{ //convert the value to a float
            return parseFloat(upperPriceVal);
        }
    }
}


var hotelsNrMap = {
/****
 *  This obj literal contains propoerties and functions relating to the map and hotel data
 */
    //constants
    city : 'London',
    defaultZoom : 16,
    defaultCenter : new GLatLng(51.51277733333332, -0.1364444444444445),
    lastRefreshLatLng : null,
    ajaxUrl : "/search/hotels_search.php",
    mapMinZoom : 13,
    mapMaxZoom : 17,
    baseCountry : 'UK',
    autoMapUpdate : true,

    zoomDistance :{
        //zoom : distance(meters)
        '18' : 180,
        '17' : 400,
        '16' : 600,
        '15' : 800,
        '14' : 900,
        '13' : 1050,
        '12' : 1250
        },

    AddHotelFloatingWindow : function(hotelInfo){
        var marker = new GMarker(hotelInfo.latitude, hotelInfo.longitude);
        var ajaxUrl = hotelsNrMap.ajaxUrl + "?format=json&a=getHotelInfo&hotelId="+hotelInfo.HotelID;
        $.ajax({
                type: "GET",
                url: ajaxUrl,
                async: false
            })
    },

    initMap : function(mapDom){
        //initialise the map - add events amnd listeners

        GEvent.addListener(mapDom,'dragend',function() {
        /****
        *  refresh map when user has dragged map a certain distance
        *  ref: cfg.zoomDistance
        */
            // Clear the overlays first, to lessen the chance of users triggering the info window while dragging
            // which leads to a bug where the map hangs.
            mapDom.clearOverlays();

            hotelsNrMap.doAutomapRefresh(mapDom);
            attInfo.getAttractionpanelInfo(mapDom.getCenter(), mapDom.getZoom());
        });

        GEvent.addListener(mapDom,'zoomend',function() {
            getNearbyHotels(null,false,true);
        });

        GEvent.addListener(mapDom,'extinfowindowopen',function() {
            hotelsNrMap.autoMapUpdate = false;
        });

        GEvent.addListener(mapDom,'extinfowindowopen',function() {
            hotelsNrMap.autoMapUpdate = true;
        });
       
        /** floating window updates **/
/*
        GEvent.addListener(mapDom, 'extinfowindowupdate', function(){
            //attInfo.getAttractionpanelInfo(mapDom.getCenter(), mapDom.getZoom());
            getNearbyHotels(null,false);  //asynch callgetNearbyHotels(null,false);  //asynch call
            //hotelsNrMap.doAutomapRefresh(mapDom);
        });
        GEvent.addListener(mapDom, 'extinfowindowbeforeclose', function(){
            getNearbyHotels(null,false,true); //synch call
            //attInfo.getAttractionpanelInfo(mapDom.getCenter(), mapDom.getZoom());
        })
*/
    },

    doAutomapRefresh : function(mapDom,newLatLng){
        //works out if we need to automatically update the map

        if(typeof(newLatLng) =="undefined"){
            newLatLng = false;
        }

        var ctrLatLng = '';
        if(newLatLng){ //if new lat lng provided
            ctrLatLng = newLatLng;
        }
        else{//assume the center point of current map obj
            ctrLatLng = mapDom.getCenter();
        }

        /*
        //whoot we got the distance from last refresh
        var distFromLastRefresh = ctrLatLng.distanceFrom(hotelsNrMap.lastRefreshLatLng);
        var zoom = mapDom.getZoom()
        var distanceForRefresh = hotelsNrMap.zoomDistance[zoom];

        //test of we have dragged far enough to force a refresh of map and we havent got a floating window open
        if(distFromLastRefresh > distanceForRefresh && hotelsNrMap.autoMapUpdate){
            //whoot, we've moved the map enough to warrent a map page refresh
        */
            getNearbyHotels(null);
            //hotelsNrMap.getNearestHotels(ctrLatLng);
            hotelsNrMap.filterNearestHotelsTab(filterRef.star_states,
                                    parseFloat($('#lowerPrice').html()),
                                    filterRef.getUpperPriceFilterValue($('#upperPrice').html()),
                                    hotelsNrMap.getMapLongitude(map),
                                    hotelsNrMap.getMapLatitude(map)
                                );
        /*
        }
        */
    },

    createAjaxBoundsCallStrg : function(map){
        //creates an ajax ready string used to get attractions and hotels by bounds of map
        var currBnd = map.getBounds();
        var sw = currBnd.getSouthWest();
        var ne = currBnd.getNorthEast();
        var dataSend = '';
        dataSend = dataSend + 'North='+ ne.lng();
        dataSend = dataSend + '&East='+ ne.lat();
        dataSend = dataSend + '&South='+ sw.lng();
        dataSend = dataSend + '&West='+ sw.lat();
        dataSend = dataSend + '&a=mapGet';
        return dataSend;

    },

    showHotelFromSidebar :function(hotelInfo){
        //gets the hotel info from a single Id
        var htlLatLng = new GLatLng(hotelInfo.latitude,hotelInfo.longitude);
        map.setCenter(htlLatLng);
        getNearbyHotels(null,hotelInfo);
        //alert(hotelInfo.HotelID);        
    },

    ucwords : function (str) {
    // Uppercase the first character of every word in a string
    //
    // version: 1003.2411
    // discuss at: http://phpjs.org/functions/ucwords    // +   original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   improved by: Waldo Malqui Silva
    // +   bugfixed by: Onno Marsman
    // +   improved by: Robin
    // *     example 1: ucwords('kevin van zonneveld');    // *     returns 1: 'Kevin Van Zonneveld'
    // *     example 2: ucwords('HELLO WORLD');
    // *     returns 2: 'HELLO WORLD'
    return (str + '').replace(/^(.)|\s(.)/g, function ($1) {
        return $1.toUpperCase();});
    },

    mapLocationSearch : function(searchTerm){
        //add the search term to the H1 tag
        var h1tag = searchTerm.replace(/[+|-]/g, ' '); // replace all occurences of + or - with spaces
        $('.homePageTitle').html("Hotels Near To "+hotelsNrMap.ucwords(h1tag));

        //update further info tab
        populateInfoTab(searchTerm);
        
        //does the seardch to google using google map
        var addr = searchTerm + ","+ hotelsNrMap.city + "," + hotelsNrMap.baseCountry;
        geocoder.getLatLng(
            addr,
                function(point) {
                    if (!point) {
                        alert(searchTerm + " not found");
                    }
                    else {
                        map.setCenter(point);
                        getNearbyHotels(null,false,true);
                        // Set the sidebar too
                        hotelsNrMap.getNearestHotels(point);
                        attInfo.getAttractionpanelInfo(point, map.getZoom());
                    }
                }
        );
        htlGen.logLocSearch("location", $('#searchTxt').val(), 0,'location search');
        
    },

    getNearestHotels : function(GlatLng){
        //displays the hotels nearest to the central point on the left hand side
        var ajxurl = ajxFetch.ajaxUrl + '?a=getNearestHotels&lat=' + GlatLng.lat()
            + '&lng=' + GlatLng.lng();
        //clear existing contents
        
        $.ajax({
            url: ajxurl,
            cache : false,
            async : false,
            success : function(data){
                $('#nearest').html('');
                hotelsNrMap._displayNearestHotels(data);
            }
        });
    },

    openHotelFloatingWindow : function(hotelId){
        //creates a hotel floating external window
        var url = this.ajaxUrl + '?a=getHotelInfo&hotelId=' + hotelId
        $.ajax({
            url : url,
            dataType: 'json',
            success : function(data){
                //perform a map update before we show the marker to ensure we
                //  have map info in the background
                getNearbyHotels('',false,true);
                
                var point = new GLatLng(data.Latitude,data.Longitude);
                map.setCenter(point);

                //set up icon defaults
                var baseIcon = new GIcon(G_DEFAULT_ICON);
                baseIcon.iconSize = new GSize(25, 30);
                baseIcon.iconAnchor = new GPoint(9, 2);
                baseIcon.infoWindowAnchor = new GPoint(9, 2);
                var numIcon = new GIcon(baseIcon);

                numIcon.image = "/images/hotel.png";
                markerOptions = {icon:numIcon};

                var marker = new GMarker(point, markerOptions);
                marker.openExtInfoWindow(
                    map,
                    "locCardContainer",
                    customWindow(0,data),
                    {}
                );
                map.addOverlay(marker);

               //hide loading image
               $('#loadImg').css('visibility', 'hidden');

            }
        })
        //addRecent(hotelId);
        return false;
    },

    _displayNearestHotels : function(hotelsList){
        //renders the left hand list of nearest hotels

        var htl = eval(hotelsList);

            //the hotel string template we will do to find
        var hotelsTpl = '<li>';
        hotelsTpl += '<img src="[[htlPic]]">';
        hotelsTpl += '<div class="sideText">';
        hotelsTpl += '<h3><a href="#" onClick="hotelsNrMap.openHotelFloatingWindow([[htlId]])">[[htlName]]</a></h3>';
        hotelsTpl += '  <div id="starBox">';
        hotelsTpl += '      [[htlStar]]';
        hotelsTpl += '  </div>';
        hotelsTpl += '<p><sup>from</sup> <span>&pound;[[htlPrice]]</span> <sub>per night</sub></p>';
        hotelsTpl += '<a href="/hotels/[[nameURL]]/[[ID]]/" class="textLink">Find Out More</a>';
        hotelsTpl += '</div>';
        hotelsTpl += '</li>';
        
        var tmp = '';
       
        for(var i = 0; i <htl.length; i++){//we should only loop 5 times
            //if first top hotel
            if(i == 0){ //nearest hotel and therefore featured at the top
                var ft = '<li id="featured">';
                ft += '<img id="featuredImage" src="[[htlPic]]"/>';
                ft += '<div class="sideTextFeat">';
                ft += '<h3><a id="featuredTitle" href="#" onClick="hotelsNrMap.openHotelFloatingWindow([[htlId]])">[[htlName]]</a></h3>';
                ft += '  <div id="starBoxFeatured">';
                ft += '      [[htlStar]]';
                ft += '  </div>';
                ft += ' <p id="featuredp"><sup id="featuredsup">from</sup> <span id="featuredspan">&pound;[[htlPrice]]</span><span id="featuredsub"> per night</span></p>';
                ft += ' <a style="float: right;" class="orangeBtnSide" href="/hotels/[[nameURL]]/[[ID]]/">Find Out More</a>';
                ft += '</div>';
                ft += ' </li>';

                ft = ft.replace('[[ID]]',htl[i].id);
                ft = ft.replace("[[nameURL]]",htl[i].name.toLowerCase().replace(/\s/g, '-').replace(/---/g, '-').replace(/[(|)|\/|.|,|&|']/g, ''));
                ft = ft.replace('[[htlPic]]',htl[i].thumbnail);
                ft = ft.replace('[[htlLink]]', htl[i].productUrl);
                ft = ft.replace('[[htlName]]', htl[i].name);
                ft = ft.replace('[[htlPrice]]', htl[i].price);
                //if there is no rating e.g. rating = 0
                if( htl[i].Hotel_Rating == 0 )
                    ft = ft.replace('[[htlStar]]', '<p class="noRating">No Rating Available</p>');
                else
                    ft = ft.replace('[[htlStar]]', '<img alt="hotels rating" src="/images/'+htl[i].Hotel_Rating+'stars.png" class="starRating" />');
                ft = ft.replace('[[htlId]]', htl[i].HotelID);
                ft = ft.replace('[[htlLng]]', htl[i].Longitude);
                ft = ft.replace('[[htlLat]]', htl[i].Latitude);

                $('#nearest').append(ft);
            }
            else{//we assume the other hotels
                tmp = hotelsTpl.replace('[[htlPic]]',htl[i].thumbnail);
                tmp = tmp.replace('[[htlLink]]', htl[i].productUrl);
                tmp = tmp.replace('[[htlName]]', htl[i].name);
                tmp = tmp.replace('[[htlPrice]]', htl[i].price);
                //if there is no rating e.g. rating = 0
                if( htl[i].Hotel_Rating == 0 )
                    tmp = tmp.replace('[[htlStar]]', '<p class="noRating">No Rating Available</p>');
                else
                    tmp = tmp.replace('[[htlStar]]', '<img alt="hotels rating" src="/images/'+htl[i].Hotel_Rating+'stars.png" class="starRating" />');
                tmp = tmp.replace('[[htlId]]', htl[i].HotelID);
                tmp = tmp.replace('[[ID]]', htl[i].id);
                tmp = tmp.replace("[[nameURL]]",htl[i].name.toLowerCase().replace(/\s/g, '-').replace(/---/g, '-').replace(/[(|)|\/|.|,|&|']/g, ''));
                tmp = tmp.replace('[[htlLng]]', htl[i].Longitude);
                tmp = tmp.replace('[[htlLat]]', htl[i].Latitude);

                //[[htlLat]],[[htlLng]],[[htlId]]
                $('#nearest').append(tmp);
            }
        }
    },

    showInfoPanel : function(panelId){
        //shows one panel and hides the other panel. Affects nearest and recentlt seen panels only
        if(panelId == 'recent'){
            $('#recent').css('display','block');
            $('#recentBtn').removeClass('infoboxBtn').addClass('infoboxBtnSelected');
            $('#nearest').css('display','none').removeClass('infoboxBtnSelected').addClass('infoboxBtn');
            $('#nearestBtn').removeClass('infoboxBtnSelected').addClass('infoboxBtn');
        }
        else if(panelId == 'nearest'){
            $('#recent').css('display','none').removeClass('infoboxBtnSelected').addClass('infoboxBtn');
            $('#recentBtn').removeClass('infoboxBtnSelected').addClass('infoboxBtn');
            $('#nearest').css('display','block').removeClass('infoboxBtn').addClass('infoboxBtnSelected');
            $('#nearestBtn').removeClass('infoboxBtn').addClass('infoboxBtnSelected');
        }
    },

    getMapLongitude : function(mapObj){
        //returns the map center Longitude
        var tmp = mapObj.getCenter();
        return tmp.lng();
    },

    getMapLatitude :function(mapObj){
        //returns the map center latitude
        var tmp = mapObj.getCenter();
        return tmp.lat();
    },

    filterNearestHotelsTab : function(hotelRating,minPrice,maxprice,lng,lat){
        /*
        * @desc updates the nearest tab based on filtering
        * @author JL 'Apr 10
        * @param array hotelRating - an array of the hotel ratings , whether they are on or off should be filterRef.star_states
        * @param real minPrice - the lowest filter price user has selected
        * @param real maxprice - the highest filter price user has selected
        * @param real lng - longitude
        * @param real lat - latitude
        **/
       var keyRating = 'r1=' + hotelRating[0] + '&r2=' + hotelRating[1] + '&r3=' + hotelRating[2]
            + '&r4=' + hotelRating[3] + '&r5=' + hotelRating[4];
       var ajxUrl = hotelsNrMap.ajaxUrl + '?a=getNearestFiltered&' + keyRating;
       //change hotel rating to an assocative array

       var filterOptions = {
                "minPrice" : minPrice,
                "maxPrice" : maxprice,
                "lng" : lng,
                "lat" : lat
            };       

       $.ajax({
           url : ajxUrl,
           dataType: 'json',
           data : filterOptions,
           async : false,
           success : function(data){
               $('#nearest').html('');
               hotelsNrMap._displayNearestHotels(data);
               
           },
           error : function(data){
                console.log('problem with ajax call');
           }
       })

    }
}

var attInfo = {
//obj that holds all the attractions panel interactions functions

    showAttraction : function(attId){
        //shows the attraction on the map
        var url = hotelsNrMap.ajaxUrl + '?a=getAttrInfo&id=' + attId
        $.ajax({
            url : url,
            dataType: 'json',
            success : function(data){
                //perform a map update before we show the marker to ensure we
                //  have map info in the background
                getNearbyHotels('',false,true);

                var point = new GLatLng(data.latitude,data.longitude);
                map.setCenter(point);
                //set up icon defaults
                var baseIcon = new GIcon(G_DEFAULT_ICON);
                baseIcon.iconSize = new GSize(25, 30);
                baseIcon.iconAnchor = new GPoint(9, 2);
                baseIcon.infoWindowAnchor = new GPoint(9, 2);
                
                var numIcon = new GIcon(baseIcon);
                numIcon.image = data.icon;
                markerOptions = {icon:numIcon};
                //hides the loading animation
                $('#loadImg').css('visibility', 'hidden');

                var marker = new GMarker(point, markerOptions);
                marker.openExtInfoWindow(
                    map,
                    "locCardContainer",
                    attractionWindow(0,data),
                    {}
                );
                map.addOverlay(marker);
            }
        })
        
//        /return false;
    },
    
    getAttractionpanelInfo : function(googLatLng, mapZoom){
    /***
     *  Description : retrieves and displays the attraction
     *  @param GlatLng googLatLng = obj thats holds the latLng of the map center
     *  @param int mapZoom = zoom level of map
    */
        if(typeof(mapZoom) == "undefined"){
            mapZoom = hotelsNrMap.defaultZoom;
        }
        //alert(googLatLng.lat() +',' + googLatLng.lng());
        var ajxurl = ajxFetch.ajaxUrl + '?a=getAttractions&lat=' + googLatLng.lat() 
            + '&lng=' + googLatLng.lng() + '&zoom=' + mapZoom;        
        $.ajax({
            url: ajxurl,
            cache : false,
            success : function(data){
                attInfo._displayAttractionPanelInfo(data);
            }
        })
    },

    hideHotelMarkers : function(){
    /***
     *  Description : Hides hotel markers
     */
        for( var i = 0; i < hotels.length; i++ )
        {
            if( showHotels == false )
                hotel_markers[hotels[i].id].show();
            else
                hotel_markers[hotels[i].id].hide();
        }
    },

    _displayAttractionPanelInfo : function(attInfo){
    /***
     *  Description : displays the info
     *  @param GlatLng googLatLng = obj thats holds the latLng of the map center
     *  @param int mapZoom = zoom level of map
    */
        var att = eval(attInfo);
        attrTpl = '<li>';
        attrTpl += '    <img src="[[attPicUrl]]" width="105" height="84" />';
        attrTpl += '    <h3>[[attName]] - [[attDist]] miles away</h3>';
        attrTpl += '    <p>[[attDescription]]</p>';
        //attrTpl += '    <a onclick="show_attraction_thickbox([[attId]]); return false;" class="orangeBtnSide">Find Out More</a>';
        attrTpl += '    <a href="#mainMap" onclick="attInfo.showAttraction([[attId]]);" class="orangeBtnSide">Show on map</a>';
        attrTpl += '</li>';

        var tmp = '';//tmp string for the tpl to add to add
        var tmpP=''; //tmp holding parameters
        //clear list
        $('#attrLeft').html('');
        $('#attrRight').html('');

        for(var i = 0; i < att.length; i++){
            tmp =attrTpl.replace("[[attPicUrl]]",att[i]["thumbnail"]);
            tmp =tmp.replace("[[attName]]",att[i]["name"]);

            //check if we have a long description
            if(att[i]["description"] == null){
                att[i]["description"] = '';
            }
            else{
                if(att[i]["description"].length > att[i]["shortDes"].length){
                    tmp =tmp.replace("[[attDescription]]","[[attDescription]]...");
                }
            }
            tmp =tmp.replace("[[attId]]",att[i]["id"]);
            tmp =tmp.replace("[[attId]]",att[i]["id"]);
            tmp =tmp.replace("[[attDescription]]",att[i]["shortDes"]);
            tmp =tmp.replace("[[attDist]]",att[i]["distance"]);

            //work out if we need to add to right or left column
            if((i + 1) % 2 == 1){//if odd number then add to left column
                $('#attrLeft').append(tmp);
            }
            else{//we add to the right hand column
                $('#attrRight').append(tmp);
            }
        }
    }
}

function GetParameterFromURL(name){
    /*-------------------------------------
    Description:
    Extracts a parameter from the url. eg xyz.com/test.php?msg=hello
    GetParameterFromURL('msg') will get 'hello'
    Author: http://www.netlobo.com/url_query_string_javascript.html
    Dependencies:
    Updates:
    @Parameters: name = name of the parameter to extract
    -------------------------------------*/
      name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
      var regexS = "[\\?&]"+name+"=([^&#]*)";
      var regex = new RegExp( regexS );
      var results = regex.exec( window.location.href );
      if( results == null )
        return "";
      else
        return results[1];
    }

/**
 *  TEMP FUNCTION for phase 1 for friendly URLs. Modified function above (GetParameterFromURL)to find
 *  the searchFor query string parameter after the url has been rewritten via mod rewrite.
 *
 *  Author: CD
 */
function getSearchFromURL(name){
      name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
      var regexS = name+"([^&#]+)/?";
      var regex = new RegExp( regexS );
      var results = regex.exec( window.location.href );
      if( results == null )
        return "";
      else
        return results[1].replace(/[\/|?][/?a-zA-Z0-9=_~*$:{}%\/|]+/g,'');
}

/**
 *  Populates the Further Information tab using data retrieved through ajax request.
 *  @parameter string searchTerm The value from the searchFor key in the query string.
 */
 function populateInfoTab(searchTerm)
 {
     if(searchTerm)
     {
         $.getJSON('/search/hotels_search.php', {a: 'getCityInfo', city: searchTerm}, function(data){
             var content = '';
             if(data)
             {
                 content += '<img src="'+data[0].image+'" alt="'+data[0].name+'" />';
                 content += '<h2>'+data[0].name+'</h2>';
                 content += '<p>'+data[0].description+'...</p>';
                 $('#further_info').html(content);
             }
             else{
                 $.getJSON('/search/hotels_search.php', {a: 'getAttrInfoForTab', attr: searchTerm}, function(data){
                     if(data)
                     {
                         content += '<img src="'+data.thumbnail+'" alt="'+data.name+'" />';
                         content += '<h2>'+data.name+'</h2>';
                         content += '<p>'+data.description.substr(0,400)+'...</p>';
                         $('#further_info').html(content);
                     }
                     else{
                         content += '<img src="/images/city/city-of-london.jpg" alt="City of London" />';
                         content += '<h2>City of London</h2>';
                         content += "<p>The City of London is the historic core of London, whose boundaries have hardly changed since the Middle Ages. Its buildings come in a wide variety of architectural styles from the city's long and colourful history, and it's now a global financial and business centre equivalent to New York City. </p>";
                         $('#further_info').html(content);
                     }
                 });
             }
         });
     }
 }

/*
 * updates the pop up attraction lightbox thingy using the attraction id passed in.
 * @Parameters int attrId
 */
function cdWriteAttrCard(attrId)
{
    $.getJSON('/search/hotels_search.php', {a: 'getAttrInfo', id: attrId}, function(data){

        $('#aName').html(data.name);
        $('#aLoc').html(data.city+', '+data.postcode);
        $('#aDesc').html(data.description);
        $('#aImage').html('<div class="imgBox" style="background: #000000 url('+data.image+') center no-repeat"</div><p class="attrImgCaption">'+data.name+'</p>')

        //remove the previous overlay
        attrmap.removeOverlay(attrMarker);

        //change attraction marker on map and pan to the attraction
        var point = new GLatLng(data.latitude, data.longitude);
        attrMarker.setLatLng(point);
        attrmap.addOverlay(attrMarker);
        attrmap.panTo(point);
    });
}

/*********************************/
var map =''; //google map obj
var panel_active_tab = document.getElementById('nearest_hotels')
var last_used_hotel_id = 0;
var clickState = 0; //no hotel has been clicked yet
var hotels = new Array;
var viewed = new Array;
var hotel = new Object;
var sortedHotels = new Array();
var geocoder = new GClientGeocoder();
geocoder.setBaseCountryCode(hotelsNrMap.baseCountry);

//Global variable which will store the state (true or false) of the displaying of hotels
var showHotels = true;

//Global array which will store the state (show or hidden) of the attraction categories
var categoryArray = new Array();
    categoryArray['theatre'] = 'show';
    categoryArray['venue'] = 'show';
    categoryArray['museum'] = 'show';
    categoryArray['tourist'] = 'show';
    categoryArray['landmark'] = 'show';

//declare global variables for the attractions popup map
var attrmap;
var attrMarker;

$(document).ready(function(){
    hotel = new Object;
    hotel.visible = true ;

    //google map initiation code
    map = new GMap2(document.getElementById("map_canvas"));
    map.setCenter(hotelsNrMap.defaultCenter,hotelsNrMap.defaultZoom);
    hotelsNrMap.initMap(map);
    init_hotels_arr(map);

    //ordering of ajax calls is important!
        //after getting the nearest hotels from initial map render, then get the correct
        //nearest hotels info from the new location
    if(GetParameterFromURL('searchFor'))
    {
        map.setZoom(15);
        hotelsNrMap.mapLocationSearch(GetParameterFromURL('searchFor'));
    }
    //For rewritten friendly URL
    else if(getSearchFromURL('hotels-near'))
        hotelsNrMap.mapLocationSearch(getSearchFromURL('/hotels-near-'));
    
    //add events
    $('#recentBtn').click(function(){
        hotelsNrMap.showInfoPanel('recent');
        return false;
    });

    $('#nearestBtn').click(function(){
        hotelsNrMap.showInfoPanel('nearest');
        return false;
    })

    $('#searchTxt').keyup(function(event){
        if (event.keyCode == '13') {
            hotelsNrMap.mapLocationSearch($(this).val())
            map.setZoom(15);
        }
    })

    // Create attractions popup map
    var point = new GLatLng(51.51277733333332, 0.1364444444444445);
    var baseIcon = new GIcon(G_DEFAULT_ICON);
    baseIcon.iconSize = new GSize(25, 30);
    var attrIcon = new GIcon(baseIcon);
    attrIcon.image = "/images/landmark.png";

    attrMarkerOptions = {icon:attrIcon};
    attrMarker = new GMarker(point, attrMarkerOptions);

    attrmap = new GMap2(document.getElementById("attrMap"));
    attrmap.setCenter( point, 13);
    attrmap.setUIToDefault();
    attrmap.addOverlay(new GMarker(point, attrMarkerOptions));
    attrmap.disableScrollWheelZoom();
    
    //add colorbox popup to links with hpAttrLink class
    $('.hpAttrLink').live('click', function(){
        $.fn.colorbox({
            width: '820px',
            height: '520px',
            inline: true,
            href: '#lightBoxWrap',
            opacity: 0.8
        })
    });

    if(GetParameterFromURL('A8ID')){
        // if A8ID is set in the URL set value into cookie
        $.cookie('A8ID',GetParameterFromURL("A8ID"),{path: '/', expires: 120});
    }

    //initiate the price filter labels
    $("#lowerPrice").html(filterRef.startLowFilterPrice);
    $('#upperPrice').html(filterRef.startHighFilterPrice);
    
    $('#slider').slider({
            range: true,
            values: [filterRef.startLowFilterPrice, filterRef.startHighFilterPrice],
            min: filterRef.lowerPriceLimit,
            max: filterRef.upperPriceLimit,
            step:5,
            slide : function(event,ui){
                $("#lowerPrice").html(ui.values[0]);
                //chk if we have reached the allowed upper limit of filter and add extra "+" chracter
                if(ui.values[1] == filterRef.upperPriceLimit){
                    $('#upperPrice').html(filterRef.upperPriceLimit + "+");
                }
                else{
                    $('#upperPrice').html(ui.values[1]);
                }
            },
            stop: function(event, ui) {
                do_filter();
            }
    })

    if(GetParameterFromURL('zoom')){
        // if zoom is set in the URL set zoom
        map.setZoom( parseInt(GetParameterFromURL('zoom')) );
        hotelsNrMap.doAutomapRefresh(map, map.getCenter())
    }

});
