//import url("\styles\common.css");
//higher zoomlevel = closer to ground, max 18

var defaultZoomLevel = 10;
var boxes = new Array();
var previous_box = '';
//var map = ''; //global for gmap
function showAddress(address) {
  geocoder.getLatLng(
    address + ", uk",
    function(point) {
    if (!point) {
      alert(address + " not found");
    } else {
      sendAttRequest("/search/hotels_search.php?format=json&a=att&lng="+point.lng()+"&lat="+point.lat(),"text",
        function(jSonResponse)
        {
            eval("("+jSonResponse+")");
            var zoom = map.getZoom();
            initialize();
            filter();
            sortHotelsByDistance();
            showAttraction_data(attractions);
            map.setCenter(new GLatLng(point.lat(),point.lng()),zoom);
            displacement=0;
        }
      );
    }
    }
  );
}

function infowindow(number, hotel){      
    var text = "<div style='width: 350px;'>"
    text = text + "<div style='position: relative; '>"
    text = text + "<table><tr><td rowspan='6'><img class='description_image' src='" + hotel.imageUrl + "' style='width: 80px; height: 80px;'></td></tr>"
    text = text + "<tr><td><a href='" + hotel.name + "'><b>" + hotel.name + "</b></a></td></tr>"
    text = text + "<tr><td><label>" + hotel.Hotel_Rating + " star</label></td></tr>"
    text = text + "<tr><td><label>" + display_currency("USD") + " " + convert_currency(hotel["price"], "GBP", "USD") + "</label></td></tr></table>" 
    text = text + "</div>"
    text = text + "</div>"    
    return text;
}

function customWindow(number, hotel){
/*
    var text='<div id="map_info_window" style="position: relative; background: #FFFFFF; padding: 0; width:350; border:2px solid #CCCCCC">';
    text +='  <table style=" margin: 5px;">';
    text +='  <col width=102px;>';
    text +='  <col width=230px;>';
    text +='  <tr style="background: #E0EBF1">';
    text +='  <td colspan=3 style="padding-left: 5px"><strong>'+hotel["name"]+'</strong></td>';
    text +='  </tr>';
    text +='  <tr>';
    text +='    <td style="vertical-align: top; padding-left:0; padding-top: 5px; padding-bottom: 0"><img style="width: 110px; height: 110px; border: 1px solid #000" src="'+ hotel["URL"]+'" /></td>';
    text +='    <td colspan=2 >';
    text +='    <table>';
    text +='      <tr><td style="vertical-align: top; padding-top: 0">'+hotel["Address1"]+', '+hotel["city"].toUpperCase()+' '+hotel["Postal_Code"].toUpperCase()+'</td></tr>';
    text +='      <tr><td style="vertical-align: top; padding-top: 0">'+showStar(hotel["Hotel_Rating"]);
    text +='        </td>';
    text +='      </tr>';
    text +='      <tr><td colspan=2 class="highlight">';
    text +='        <strong id="curr_holder">From '+display_currency("GBP")+'</strong> <strong id="price_holder">'+convert_currency(hotel["price"], "GBP", "USD")+' /Night</strong><br><br>';
    text +="        <a class='alignRight sideHotelName' href=\""+hotel['productUrl']+"\" target=\"_blank\"'><img src=\"images/book_now.png\"></a> \t";
    //text +="        <a class='alignRight sideHotelName' onclick='show_hotel_thickbox(\""+hotel.id+'","'+hotel.name+"\"); return false;'><img src=\"images/find_out.png\"></a> \t";
    text +=' 		  </td></tr>';
    text +='    </table>';
    text +='    </td>';
    text +=' </tr>';
*/

    var text ='    <a href="/hotels/[[nameURL]]/[[id]]/"><img class="locCardImg" src="[[hotelPic]]"></a>';
    text += '      <div class="locText">';
    text +=    '       <a href="/hotels/[[nameURL]]/[[id]]/"><h3>[[hotelName]]</h3></a>';

    //dislpay no rating message if no rating
    if( hotel["Hotel_Rating"] == 0 )
        text +='             <p class="noRating">No Rating Available</p>';
    else
        text +='             <img class="locCardStars" src="/images/'+hotel["Hotel_Rating"]+'stars.png" />';

    text +='            <p><sup>from</sup> <span>£[[hotelPrice]]</span> per night</p>';
    text +='            <a class="orangeBtnSide" href="/hotels/[[nameURL]]/[[id]]/">More Information</a>';
    text +='            </div>';

    text = text.replace(/\[\[id\]\]/g,hotel["id"]);
    text = text.replace("[[hotelName]]",hotel["name"]);
    text = text.replace(/\[\[nameURL\]\]/g,hotel["name"].toLowerCase().replace(/\s/g, '-').replace(/---/g, '-').replace(/[(|)|\/|.|,|&|']/g, ''));
    text = text.replace("[[hotelPic]]",hotel["ThumbnailURL"]);
    text = text.replace("[[hotelPrice]]",hotel["price"]);
    text = text.replace("[[hotelLink]]",hotel["productUrl"]);


    //replace the string with the
     
    return text;
}
function convert(amount)
{
    var currency = document.getElementById("curr_holder");
    if(currency.innerHTML.charCodeAt(0)==163)
    {
      var usd_pice = convert_currency(amount, "GBP", "USD");
      currency.innerHTML = display_currency("USD");
      document.getElementById("price_holder").innerHTML = usd_pice;
      document.getElementById("convert_to").innerHTML = " [Convert to "+display_currency("GBP")+"]";
    }
    else
    {
      amount=document.getElementById("price_holder").innerHTML;
      var gbp_pice = convert_currency(amount, "USD", "GBP");
      currency.innerHTML = display_currency("GBP");
      document.getElementById("price_holder").innerHTML = gbp_pice;
      document.getElementById("convert_to").innerHTML = " [Convert to "+display_currency("USD")+"]";
    }
}

function convert_currency(amount, fromCurrency, toCurrency,ex_rates){
/*-------------------------------------
Description:
Converts the currency

Author: AM

updates:
   july09 - removed the calc, will return the original value

todo: apply back in
-------------------------------------*/
    
    return amount;
    //return Math.round(100*(amount*ex_rates[toCurrency])/ex_rates[fromCurrency], 2)/100;
}


function init_price_menu() //DEPRECATED???
{
/*-------------------------------------
Description:
Initialises the menu to USD after intially showing GBP

Author: AM
-------------------------------------*/
    var txtPriceFrom = document.getElementById("txtPriceFrom");
    var menu ="<option value='-1'></option>";
    for(var i=0; i<=5;  i++)
    {
      menu +="<option value='"+i+"' " + ">"+display_currency("USD")+Math.ceil(convert_currency((i*50), "GBP", "USD"))  +
        "-" + display_currency("USD")+ Math.ceil(convert_currency(((i+1)*50), "GBP", "USD"))+ "</span></option>";
    }
    menu +="<option value='6' > More than "+display_currency("USD")+ Math.ceil(convert_currency(300, "GBP", "USD"))+"</option>";
    
    txtPriceFrom.innerHTML=menu;
}
function display_currency(currency)
{
    switch(currency)
    {
      case "GBP":
        return "&#163;";
        break;
      case "USD":
        return "&#36;";
        break;
    }
    return currency;
}
function attractionWindow(number, attraction){   
/*
    var text='<div id="map_info_window" style="position: relative; background: #FFFFFF; padding: 0; width:350px; border:2px solid #CCCCCC">';
    text +='  <table style=" margin: 5px;">';
    text +='  <col width=102px;>';
    text +='  <col width=221px;>';
    text +='  <tr style="background: #E0EBF1">';
    text +='  <td colspan=3 style="padding-left: 5px"><strong>'+attraction["name"]+'</strong></td>';
    text +='  </tr>';
    text +='  <tr>';
    text +='    <td style="vertical-align: top; padding-left:0; padding-top: 5px; padding-bottom: 0"><img style="width: 110px; height: 110px; border: 1px solid #000" src="'+ attraction["image"]+'" /></td>';
    text +='    <td colspan=2 >';
    text +='    <table>';
    text +='      <tr><td colspan=2 style="vertical-align: top; padding-top: 0">'+attraction["description"].substring(0,135)+'...'+'</td></tr>';
    text +="      <tr><td colspan=2 style='vertical-align: top; padding-top: 0; padding-bottom: 0; text-align: right'><a href='#' onclick='show_attraction_thickbox("+number+"); return false;'><img src='/images/find_out_more_rollover.png'/></a></td></tr>";
    text +='    </table>';
    text +='    </td>';
    text +=' </tr>';
    return text;
 */
    if (typeof(attraction["description"]) == null){
        attraction["description"] = '';
    }

    var text = '    <a class="hpAttrLink" href="#" onclick="cdWriteAttrCard(\''+ attraction["id"] +'\')"><img class="locCardImg" src="' + attraction["thumbnail"] + '"></a>';
    text += '       <div class="locText">';
    text +='            <a class="hpAttrLink" href="#" onclick="cdWriteAttrCard(\''+ attraction["id"] +'\')"><h3>' + attraction["name"] + '</h3></a>';
    text +='            <p class="attract">' + attraction["description"].substring(0,100)+ '...'+ '</p>'
    text +='            <a class="hpAttrLink orangeBtnSide" href="#" onclick="cdWriteAttrCard(\''+ attraction["id"] +'\')">Find Out More</a>';
    text +='        </div>';

    return text;
}

function getNearestHotels(){
    if (panel_active_tab.id == 'nearest_hotels'){
      sortHotelsByDistance();
    }
}

function sortDistance(a,b){ //helper function for sortHotelsByDistance()
    return a.distance - b.distance;
}
var displacement_origin;

function getDisplacementLimitData(){
/*-------------------------------------
Description:
Retrieves a table of numbers which shows the displacement limits before an update on google maps

Author: JL July'09
Updates:

TODO: retrieve as data from backend?
@parameter cityDefaults array - stores the array parameter
@return array
-------------------------------------*/
 
    var numberOfZoomLevels = 5
    var displacementAmounts = new Array(numberOfZoomLevels);
    
    //max close zoom = 16
    //min out zoom = 12 
    /*
    for (i=0; i<numberOfZoomLevels; i++){
        displacementAmounts[0]=i;        
    }
    */
    //element 1 = google zoom level
    //element 2 = displacement limit before update in miles
    //see http://stackoverflow.com/questions/966225/how-to-create-a-two-dimensional-array-in-javascript
        
    displacementAmounts = [[16,0.2],[15,0.35],[14,0.5],[13,0.7],[12,1]] ;

    /*
    displacementAmounts[1][0] = 15;
    displacementAmounts[1][1] = 0.35;
    displacementAmounts[2][0] = 14;
    displacementAmounts[2][1] = 0.5;
    displacementAmounts[3][0] = 13;
    displacementAmounts[3][1] = 0.7;
    displacementAmounts[4][0] = 12;
    displacementAmounts[4][1] = 1;    
    */
    return displacementAmounts;
}

function getDisplacementLimit(zoomLevel){
/*-------------------------------------
Description:
Gets the displacement distance limit in miles 

Author: JL July'09
Updates:

TODO: retrieve as data from backend?
@parameter zoomLevel numeric - current zoom level of the google map

@return array
-------------------------------------*/
    var displacementData = getDisplacementLimitData(); //array of displacement values
    var displaceAmount = 0; // actual displacement values
    var i=-1; //iterator for the displacement array
    for(i=0; 1 < displacementData.length; i++){
        if(displacementData[i][0] == zoomLevel){
            //we've found the displacement distance 
            displaceAmount =displacementData[i][1];
            return displaceAmount;
        }
        else if(i == displacementData.length-1 ){
            //reached the end of the array
            return -1;
        }
    }            
}

function showAttractionNearestTocenter()
{
/*-------------------------------------
Description:
Refreshes the map based on displacement

Author: AM
Updates:
july09 - Added smart displacement calculation (JL)
TODO: retrieve as data from backend?
@parameter zoomLevel numeric - current zoom level of the google map

@return array
-------------------------------------*/
    var debug = 0; //set to 1 to show debug
    var map_center = map.getCenter();
    var displacement = distance(map_center.lng(), map_center.lat(), displacement_origin.lng(), displacement_origin.lat());
    var zoom = map.getZoom();
    displacement=(displacement)*zoom/50;
    
    var displacementLimitMiles = getDisplacementLimit(zoom);
    
    if(debug){
        alert('showAttractionNearestTocenter.displacementLimitMiles is ' + displacementLimitMiles);
        alert('showAttractionNearestTocenter - current displace is ' + displacement)
    }

    //if the map have been moved for not longer than 1 mile do nothing //JL not sure thats true
    if(displacement<displacementLimitMiles)
    {
        if(debug){alert('showAttractionNearestTocenter - displacement limit not reached');}
        return;
    }
    //else update the map
    
    if(debug){alert('displacement reached updating code - UPDATING THE MAP!');}
    displacement_origin=map_center;
    get_containing_london_area(map_center.lng(), map_center.lat());
    sendAttRequest("/search/hotels_search.php?format=json&a=att&lng="+map_center.lng()+"&lat="+map_center.lat(),"text",
      function(jSonResponse)
      {
        eval("("+jSonResponse+")");
        var zoom = map.getZoom();
        initialize();
        filter();
        sortHotelsByDistance();
        showAttraction_data(attractions);
        map.setCenter(new GLatLng(map_center.lat(),map_center.lng()),zoom);
        displacement=0;
      }
    );
}

var sortedHotels = new Array();

function sortHotelsByDistance(){
    
    var map_center = map.getCenter();
    for (var i = 0; i < hotels.length; i++){
      hotels[i].distance = distance(map_center.lng(),map_center.lat(),hotels[i].longitude,hotels[i].latitude);
      sortedHotels.push(hotels[i]);
    }
    sortedHotels.sort(sortDistance);
    for( var i = 4 ; i > -1; i--){
      showInfo(0,sortedHotels[i]);
    }
    
}
function get_attractions_by_filters(page)
{
    var d= document.getElementById("disabled");
    var d_v=0;
      if(d.checked) d_v=1;
    var r= document.getElementById("recommended");
    var r_v=0;
      if(r.checked) r_v=1;
    var m = document.getElementById("monetisable");
    var m_v=0;
      if(m.checked) m_v=1;
    var s=document.getElementById("search");
    if(!page)
      page = 0;
    sendAttRequest("/hotels_admin/modules/attractions/actions/attractions.php?a=3&sa=1&s="+s.value+"&d="+d_v+"&r="+r_v+"&m="+m_v+"&page="+page,"text",
      function(jSonResponse)
      {
        eval("("+jSonResponse+")");
        display_admin_attractions_table(admin_attractions);
      });
}
function display_admin_attractions_table(admin_att)
{
    if(admin_att==null)
    {
      return;
    }
    var admin_att_table = document.getElementById("admin_att_table");
    var tmp="";
    var rec_size=0;
    for(var i=0;i< admin_att.length;i++)
    {
      if(admin_att[i]["rec_size"])
      {
        rec_size=admin_att[i]["rec_size"];
        break;
      }
      tmp+="<tr>"+
            "<td id='admin_att_name'>"+admin_att[i]["name"]+"</td>"+
            "<td>"+admin_att[i]["city"]+"</td>"+
            "<td>"+admin_att[i]["country"]+"</td>"+
            "<td id='admin_postcode'>"+admin_att[i]["postcode"]+"</td>"+
            "<td id='admin_p_image'>"+admin_att[i]["primary_image"]+"</td>"+
            "<td id='admin_s_image'>"+admin_att[i]["secondary_image"]+"</td>"+
            "<td id='admin_trackerUrl'>"+admin_att[i]["trackerUrl"]+"</td>";
      tmp+="<td>";
      if((admin_att[i]["att_types"])!=null)
      {
        
            for(var j=0; j<admin_att[i]["att_types"].length; j++)
            {
             tmp+= admin_att[i]["att_types"][j]["att_type"]+"<br>";
            }
      }
      tmp+="</td>"+
         "<td><a style='color: white' href='../actions/attractions.php?a=4&op=2&att_id="+admin_att[i]["id"]+"'"+
              "<img src=\"/images/b_edit.png\" title=\"edit\" />"+
            "</a>"+
         "</td>"+
         "<td><a style='color: white' href='../actions/attractions.php?a=5&att_id="+admin_att[i]["id"]+"'"+
              "onclick=\"return confirm('You are about to drop the record: att_id="+admin_att[i]["id"]+"\nClick [OK] if you are sure, otherwise [Cancel]')\">"+
              "<img src=\"/images/b_drop.png\" title=\"delete\" />"+
             "</a>"+
          "</td>"+
        "</tr>";
    }
    admin_att_table.innerHTML=tmp;
    var page_cnt_menu = document.getElementById("page_cnt_menu");
    var page_cnt = Math.ceil(rec_size/10);
    tmp="";
    if(page_cnt>1)
    for(var i=0; i<page_cnt; i++)
    {
        tmp +='<li><a href="#" onclick="get_attractions_by_filters('+i+'); return false;">'+i+'</a></li>';
    }
    page_cnt_menu.innerHTML=tmp;
}
function best_zoom(minLng, minLat, maxLng, maxLat)
{
    var pixelWidth = document.getElementById("map_canvas").offsetWidth;
    var pixelHeight = document.getElementById("map_canvas").offsetHeight;
    var mapdisplay = Math.min(pixelHeight, pixelWidth);
    var dist = distance(minLng, minLat,maxLng, maxLat)*1.6093;
    var zoom = Math.floor(8 - Math.log(1.6446 * dist*2/ Math.sqrt(2 * (mapdisplay * mapdisplay))) / Math.log(2));
    if(zoom > 17)
    {
      zoom = 17;
    }
    else if(zoom<12)
    {
      zoom = 12;
    }
    else
    {
      zoom +=1;
    }
    return zoom;
}

function center_hotel(lng, lat)
{
  map.setCenter(lng, lat);
}

function initialize(cityDefaults){
/*-------------------------------------
Description:
Gets the hotel and attraction data by doing a ajax call returning a Json object
of the hotel and attraction data

Author: Acquim
Dependencies: 
Updates:

@parameter cityDefaults array - stores the array parameter
@return none
-------------------------------------*/    
    var debug = 0 //set to 1 to show all debug
    
    //map.enableScrollWheelZoom(); - disabled as it was a bit annoying
    map.enableContinuousZoom();
    //map.addControl(new GOverviewMapControl());

    var hotel_length = hotels.length;    
    var highest_latitude = parseFloat(-90.0);
    var highest_longitude =  parseFloat(-180.0);
    var lowest_latitude = parseFloat(90.0);
    var lowest_longitude = parseFloat(180.0);
    var total_lat = 0;
    var total_long = 0;
    map.disableDoubleClickZoom();
    var geocoder = new GClientGeocoder();
    // create each marker
    GEvent.addListener(map, "move", checkBounds);   

    //restricting the zoom level range
    var mapTypes = map.getMapTypes();
    for(var i=0; i<mapTypes.length; i++)
    {
      mapTypes[i].getMinimumResolution=function(){return hotelsNrMap.mapMinZoom;}
      mapTypes[i].getMaximumResolution=function() {return hotelsNrMap.mapMaxZoom;}
    }
    largeContol = new GLargeMapControl();        
    map.addControl(largeContol);
    
    //get the map bounds of the map
    var bounds = map.getBounds();
    var southWest = bounds.getSouthWest();
    var northEast = bounds.getNorthEast();
    var lngSpan = northEast.lng() - southWest.lng();
    var latSpan = northEast.lat() - southWest.lat();

    //map.clearOverlays(); - JL 29mar - not needed? Was clearing map before ajax completes?
    hidden_hotel_markers = new Array();
    hotel_markers = new Array();
    for (var i = 0; i < hotel_length; i++){
      total_lat += parseFloat(hotels[i].latitude);
      total_long += parseFloat(hotels[i].longitude);
     
      //work out the lowest and highest point of the hotels long-lats of data in array
      //	only used if no city defaults provided
      if (parseFloat(hotels[i].latitude) > highest_latitude){
        highest_latitude = hotels[i].latitude;
      }
      if (parseFloat(hotels[i].longitude) > highest_longitude){
        highest_longitude = hotels[i].longitude;
      }      
      if (parseFloat(hotels[i].latitude) < lowest_latitude){
        lowest_latitude = hotels[i].latitude;
      }
      if (parseFloat(hotels[i].longitude) < lowest_longitude){
        lowest_longitude = hotels[i].longitude;         
      }
      
      //add the filtered and unfiltered hotel markers
      var point = new GLatLng(hotels[i].latitude,hotels[i].longitude);

        //adds the initially hidden marker for when we want to filter
      hidden_hotel_markers[hotels[i]["id"]] = createMarker(point, i + 1, hotels[i],"grey");
      map.addOverlay(hidden_hotel_markers[hotels[i]["id"]]);

        //adds the full red marker for inital load-no filtering and when hotel is part of the filter hotel group
      hotel_markers[hotels[i]["id"]] = createMarker(point, i + 1, hotels[i],"hotel");
      map.addOverlay(hotel_markers[hotels[i]["id"]]);

    }// loop through hotels array
/*
    //map.setCenter(new GLatLng(center_latitude,center_longitude),defaultZoomLevel);
   // old code to set center point
    //alert('cityDefaults.ZoomLevel aaa-'+cityDefaults.ZoomLevel);
    var center_latitude = total_lat / hotels.length;
    var center_longitude = total_long / hotels.length;
    
    var defaultZoomLevel;
    //rev1
    var useCityDefaults = true;


    try{
        var test = cityDefaults[0].ZoomLevel;
    }
    catch(e){
        useCityDefaults = false;
    }
        
    // if we have city defaults use that as the zoom level
    if (useCityDefaults){
        if(debug){alert('using the db value = ' + cityDefaults[0].ZoomLevel)}; 
        defaultZoomLevel = cityDefaults[0].ZoomLevel
    }
    else{
    	// calculate the zoom level from the points on the map
        defaultZoomLevel = best_zoom(lowest_longitude, lowest_latitude, highest_longitude, highest_latitude);
        //TODO: refactor?
        if(debug){alert('calculated default zoom = '+defaultZoomLevel)};
        var map_zoom = parseInt(document.getElementById("map_zoom").value);
        if(map_zoom)
        {
          defaultZoomLevel=map_zoom;
          if(debug){alert('using map_zoom = ' + map_zoom)};
        }
    }
*/
    
}

function addHotelmarkers(hotels){
/**
 * Description:
 * 	adds the hotels markers to the map. We add two types, the red and grey. 
 * 	One for filtered and unfiltered. 
 * Author: JL
 * Dependencies
 * 	googlemaps (duh)
 * Changelog: 
 * 	Rev1  August 09
 * @param array hotels - hotels aray returned from parsed json object
 * @return none
 **/
    map.clearOverlays();    
    hidden_hotel_markers = new Array();
    hotel_markers = new Array();
       
    for (var i = 0; i < hotels.length; i++){
      var point = new GLatLng(hotels[i].latitude,hotels[i].longitude);
      hidden_hotel_markers[hotels[i]["id"]]=createMarker(point, i + 1, hotels[i],"grey");
      map.addOverlay(hidden_hotel_markers[hotels[i]["id"]]);
      hotel_markers[hotels[i]["id"]]=createMarker(point, i + 1, hotels[i],"hotel");
      map.addOverlay(hotel_markers[hotels[i]["id"]]);
    }
}

function createMarker(point, number, hotel, type){
    // Create a base icon for all of our markers that specifies the shadow, icon dimensions, etc.
    var baseIcon = new GIcon(G_DEFAULT_ICON);
    //baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
    baseIcon.iconSize = new GSize(25, 30);
    //baseIcon.shadowSize = new GSize(34, 44);
    baseIcon.iconAnchor = new GPoint(9, 2);
    baseIcon.infoWindowAnchor = new GPoint(9, 2);
    var numIcon = new GIcon(baseIcon);

    //decide which icon to use
    if (type == 'grey'){
        numIcon.image = "/images/hotel_grey.png";
    }
    else{
        numIcon.image = "/images/hotel.png";
    }
    markerOptions = {icon:numIcon};
    var marker = new GMarker(point, markerOptions);
    marker.value = number;
    //GEvent.addListener(marker, 'click', function(){
    GEvent.addListener(marker, 'mouseover', function(){
        //GEvent.trigger(map, 'extinfowindowclose');
        clickState = 1;
        addRecent(hotel.id);
        //map.panTo(marker.getLatLng());
        //map.setCenter(marker.getLatLng());
        marker.openExtInfoWindow(
            map,
            //"simple_example_window",
            "locCardContainer",
            customWindow(number,hotel),
            {}
        );

        GEvent.addDomListener(document.getElementById('locCardContainer'), 'mouseout', function(e){
            if (!e) var e = window.event;
            var reltg = (e.relatedTarget) ? e.relatedTarget : e.toElement;
            while (reltg.tagName != 'BODY')
            {
                if (reltg.id == this.id){return;}
                reltg = reltg.parentNode;
            }
            marker.closeExtInfoWindow(map);
        });
        //showHotelInfo(hotel.id);        

        //attInfo.getAttractionpanelInfo(map.getCenter(),map.getZoom);
        //@todo - need to try find a way to auto refresh on closing the floating window
        //hotelsNrMap.doAutomapRefresh(map,marker.getLatLng());        
      });

    GEvent.addListener(marker, 'dblclick', function(){
        map.panTo(new GLatLng(hotel.latitude,hotel.longitude));
    });
    return marker;
}
function checkBounds()
{
      var allowedBounds = new GLatLngBounds(new GLatLng(49.5,-4), new GLatLng(59,1.5));
      if(allowedBounds.contains(map.getCenter()))
      {
        return;
      }
      var c=map.getCenter();
      var x=c.lng();
      var y=c.lat();
      var AmaxX = allowedBounds.getNorthEast().lng();
      var AmaxY = allowedBounds.getNorthEast().lat();
      var AminX = allowedBounds.getSouthWest().lng();
      var AminY = allowedBounds.getSouthWest().lat();
      
      if(x<AminX)
      {
        x=AminX;
      }
      if(y<AminY)
      {
        y=AminY;
      }
      if(x>AmaxX)
      {
        x=AmaxX;
      }
      if(y>AmaxY)
      {
        y=AmaxY;
      }
      map.setCenter(new GLatLng(y,x));
}
var hidden_hotel_markers = new Array();
var hotel_markers = new Array();

function showHotelMarker(hotel_id)
{
    if(hidden_hotel_markers[hotel_id])
    hidden_hotel_markers[hotel_id].hide();
    hotel_markers[hotel_id].show();
}
function hideHotelMarker(hotel_id)
{
    hotel_markers[hotel_id].hide();
    hidden_hotel_markers[hotel_id].show();
}
function showAttractionFilter()
{
    document.getElementById("attraction_filter").style.display="block";
}
function closeAttractionFilter()
{
    document.getElementById("attraction_filter").style.display="none";
}
function closeLinkPanel()
{
    document.getElementById("get_link_panel").style.display="none";
}
function showLinkPanel()
{
    var ratings="";
    var cnt =0;
    for(var i =0; i< filterRef.star_states.length; i++)
    {
      if(filterRef.star_states[i]==1)
      {
        if(cnt>0)
            ratings +="+"; 
        ratings += i+1
        cnt++;
      }
    }
    var tmp = document.getElementById('txtPriceFrom').value;
    var minimum_price = parseFloat(tmp*50);
    var maximum_price = minimum_price+50;
    var price_range = minimum_price+"-"+maximum_price;
    if(minimum_price<0)
      price_range="";
    var center = map.getCenter();
    var domain = window.location.hostname;
    var loc=Math.round(1000000*center.lng(),6)/1000000+","+Math.round(1000000*center.lat(), 6)/1000000;
    document.getElementById("link_panel_url").value="http://"+ domain +"/index.php?loc="+loc+"&zoom="+map.getZoom()+"&rating="+ratings+"&price="+price_range;
    document.getElementById("get_link_panel").style.display="block";
}
function showAjaxLoader()
{
    var ajax_loder=document.getElementById("ajax_loader");
    if(!ajax_loder)
      return;
    ajax_loder.style.display="block";
}
function hideAjaxLoader()
{
    var ajax_loder=document.getElementById("ajax_loader");
    if(!ajax_loder)
      return;
    ajax_loder.style.display="none";
}

function changeStarState(starObject, star_rank){
    if(star_rank>filterRef.star_states.length||star_rank<0)
      return;
    switch(filterRef.star_states[star_rank])
    {
      case 0: //filter off
        $('#'+starObject.id).addClass('starOn').removeClass('starOff');
        //starObject.style.backgroundPosition ="0 bottom";
        break;
      case 1: //filter on
        $('#'+starObject.id).addClass('starOff').removeClass('starOn');
        //starObject.style.backgroundPosition ="0 -30px";
        break;
    }
    filterRef.star_states[star_rank]++;
    filterRef.star_states[star_rank] %=2;
}

function createAttractionMarker(point, number, attraction){
// Create a base icon for all of our markers that specifies the shadow, icon dimensions, etc.
        var baseIcon = new GIcon(G_DEFAULT_ICON);
        baseIcon.shadow = "http://www.google.com/mapfiles/shadow50.png";
        baseIcon.iconSize = new GSize(25, 30);
        baseIcon.shadowSize = new GSize(37, 34);
        baseIcon.iconAnchor = new GPoint(9, 34);
        baseIcon.infoWindowAnchor = new GPoint(9, 2);
        var numIcon = new GIcon(baseIcon);
        numIcon.image = "/images/markers/blue_marker.png";
        if(attraction.icon)
        {
           numIcon.image = attraction.icon;
        }
        markerOptions = {icon:numIcon};
        var marker = new GMarker(point, markerOptions);
        marker.value = number;

      // create event listener for each marker				
        //GEvent.addListener(marker, 'click', function(){
      GEvent.addListener(marker, 'mouseover', function(){
         //showAttractionInfo(number,attraction);
         //map.panTo(marker.getLatLng());
         marker.openExtInfoWindow(
              map,
              "locCardContainer",
              attractionWindow(number,attraction),
              {}
         );
        GEvent.addDomListener(document.getElementById('locCardContainer'), 'mouseout', function(e){
            if (!e) var e = window.event;
            var reltg = (e.relatedTarget) ? e.relatedTarget : e.toElement;
            while (reltg.tagName != 'BODY')
            {
                if (reltg.id == this.id){return;}
                reltg = reltg.parentNode;
            }
            marker.closeExtInfoWindow(map);
        });

      });

/*
      GEvent.addListener(marker, 'mouseout', function(){
        marker.closeExtInfoWindow(map);
      });
*/
      
      GEvent.addListener(marker, 'click', function(){
          getNearbyHotels(false,false,true);
          //map.panTo(new GLatLng(attraction.latitude,attraction.longitude));
          map.setCenter(new GLatLng(attraction.latitude,attraction.longitude));
          marker.openExtInfoWindow(
              map,
              "locCardContainer",
              attractionWindow(number,attraction),
              {}
            );
        //showHotelNearByAttractions(marker.getPoint().lng(), marker.getPoint().lat());
        //map.setCenter(new GLatLng(attraction.latitude,attraction.longitude));
      });
      //  map.addOverlay(marker);

      return marker;
}
function reset_filters()
{
    //reset star
    filterRef.star_states=[1,1,1,1,1];
    for(var i=0; i<5; i++)
    {
      var starObject = document.getElementById("star_rate_"+i);
      changeStarState(starObject, i);
    }
    //reset facilities
    for (i = 0; i < 6; i++)
    {
      var fac=document.getElementById("facility_"+i);
      fac.checked =false;
    }
    //reset prices
    var price_range = document.getElementById('txtPriceFrom');
    price_range.selectedIndex=0;
    //initialize(); - to stop map resize
    filter();
    showAttraction_data(attractions); 
}
function do_filter(){
    //initialize();
    filter();
    hotelsNrMap.filterNearestHotelsTab(filterRef.star_states,
                                        parseFloat($('#lowerPrice').html()),
                                        filterRef.getUpperPriceFilterValue($('#upperPrice').html()),
                                        hotelsNrMap.getMapLongitude(map),
                                        hotelsNrMap.getMapLatitude(map)
                                    );
}
function filter_attractions()
{
    
    for(var j=0; j<hotels.length; j++)
    {
      hideHotelMarker(hotels[j]["id"]);
    }
    var att_filters= document.getElementsByName("attraction_checkbox");
    var selected_atts=new Array();
    for(var i=0; i<att_filters.length; i++)
    {
      if(att_filters.item(i).checked)
      {
        switch(att_filters.item(i).value)
        {
            case "Hotels":
            filter();
            break;
            default:
            selected_atts[att_filters.item(i).value]=1;
            break;
        }
      }
    }
    for(var i=0; i<attractions.length; i++){
        hideAttractionMaker(attractions[i]["id"]);
        if(selected_atts[attractions[i]["cat"]]==1){
            showAttractionMaker(attractions[i]["id"]);
        }
    }
    //initialize();
}
function showAttractionMaker(att_id)
{
    attractionMarkers[att_id].show();
}
function hideAttractionMaker(att_id)
{
    attractionMarkers[att_id].hide();
}
function filter(){

    var j = 0;

    var selected_stars = new Array();
    for(var i =0; i< 5; i++)
    {
      if(filterRef.star_states[i]==1)
      {
        selected_stars[j]= i+1;
        j++;
      }      
    }

    var filter_selected = false;
/*
    var facs = get_facilities();
    var price_range = document.getElementById('txtPriceFrom').value;
*/
    var currUpperPriceFilter = filterRef.getUpperPriceFilterValue($('#upperPrice').html());
    var currLowPriceFilter = parseFloat($('#lowerPrice').html());

    for (i = 0; i < hotels.length; i++){
        //Filter by price//
        display=false;
        hotels[i].visible = true;
        showHotelMarker(hotels[i].id);

        /*
        if (price_range<0){
        display=true;
        }
        else */

        if(hotels[i].price >= currLowPriceFilter && hotels[i].price <= currUpperPriceFilter){
            display=true;
        }
        //if hotel is already out of range it is excluded (no need to check)
        if(display==false){
            hotels[i].visible = false;
            hideHotelMarker(hotels[i].id);
            continue;
        }
    
        //do nothing when no star filters have been selected
        if(selected_stars.length>0){
            display=false;
        }
        //Filter by stars //
      for(var j =0; j<selected_stars.length; j++)
      {
        if(hotels[i].Hotel_Rating == selected_stars[j])
        {
            display=true;
            break;
        }
      }
      //if hotel is already out of range it is excluded (no need to check)
      if(display==false)
      {
        hotels[i].visible = false;
        hideHotelMarker(hotels[i].id);
        continue;
      }
      
      /***Filter by facilities....*/
/*
      for(j=0; j<facs.length; j++)
      {
        var found=false;
        
        for( jj=0; jj<hotels[i].facilities.length; jj++)
        {
            if(hotels[i].facilities[jj]==facs[j])
            {
              found=true;
              break;
            }
        }
        if(!found)
        {
            display=false;
        }
      }
*/
      if(display==false)
      {
        hideHotelMarker(hotels[i].id);
        hotels[i].visible = false;
      }
    }//end hotels loop
}

function get_facilities()
/*
*This function returns the set of facilities selected by the user at the interface
*/
{
    var facilities= new Array();
    var i=0;
    for (j = 0; j < 6; j++)
    {
      var fac=document.getElementById("facility_"+j);
      if (fac.checked == true)
      {
        facilities[i]= fac.value;
        i++;
      }
    }
    return facilities;
}
function show_result_message(display)
{
    var searchResults=document.getElementById("lblResults");
    if(display)
    {
    //  searchResults.style.color = "grey";
    //  searchResults.innerHTML = display + " hotels found";
    }
    else
    {
      //searchResults.style.color = "orange";
    }
}
function set_loc_search(value)
{
    var search_value= document.getElementById("txtHotelNameSearch");
    search_value.value=value;
}

function getLocations(){
/********************
 * Description:
 *  Doesnt actually get the location. Updates the hotel search box div with results as user types it in.
 * Author: AM
 * Dependencies
 * Changelog: 
 *  Rev1 acquim, then JL added decription.
 *  31-jul09 - remove setting of cookie for loc
 * @param none
 * @return none
 */   
    loc = document.getElementById('txtHotelNameSearch').value;
    resultsDiv = document.getElementById('hotelSearchResults');
    var text = '';
    for (var i = 0; i < hotels.length; i++ ){
      if ( hotels[i].name.toUpperCase().indexOf(loc.toUpperCase()) != -1 && loc != ''){
        text +=  '<a onclick="hideList();populateBox(\'' + hotels[i].name + '\'); createCookie(\'searchParams_name_cookie\',\'' + hotels[i].name + '\', 365);showHotel(' +  hotels[i].id+ ',true)">' +  hotels[i].name + '</a>' + '<br />';
      }      
    }    
    resultsDiv.className = "hotelSearchResults";
    resultsDiv.innerHTML=text;
    if (text =='' && loc != ''){
      resultsDiv.innerHTML = 'No hotels found'      
    }
    if (loc == ''){
      resultsDiv.className = "hotelSearchResults_hidden";
    }
}

function populateBox(txt){
    document.getElementById('txtHotelNameSearch').value = txt
}

function hideList(){
    resultsDiv.className = "hotelSearchResults_hidden";
}

var box_index=new Array();
var nearest_hotels = new Array();

function showInfo(number, hotel){
/*-------------------------------------
Description:
 

Author: AM July'09
Updates:

TODO: retrieve as data from backend?
@parameter 
@return array
-------------------------------------*/
/*
    box = document.getElementById('infobox');
    if (hotel == 0){
      switch_active('nearest_hotels');
      box.innerHTML = '';
      for (var i =  nearest_hotels.length -1; i > -1; i--){
        box.innerHTML = box.innerHTML + nearest_hotels[i];
      }
      return;
    }
      for(var i=0; i<nearest_hotels.length;i++)
      {
        if(nearest_hotels[i].indexOf("id='box_"+hotel.id+"'")>=0)
        {
            return;
        }
      }
      var first_name ="";
      var text = "<table class='"+first_name+"' id='box_"+hotel.id+"'><tr><td rowspan='6'><a href='#' onclick='show_hotel_thickbox(\""+hotel.id+"\",\""+hotel.name+"\"); return false;'><img class='description_image' src='" + hotel.imageUrl + "' style='width: 75px; height: 75px;'></a></td></tr>";
      text = text + "<tr><td><a class='sideHotelName' onclick='show_hotel_thickbox(\""+hotel.id+"\",\""+hotel.name+"\"); return false;'><b>" + hotel.name.substr(0,30) + "...</b></a></td></tr>";		
		//text = text + "<tr><td><a onclick='showHotelInfo("+ hotel.id +"); '><b>" + hotel.name.substr(0,16) + "...</b></a></td></tr>";
      text = text + "<tr><td>" + showStar(hotel.Hotel_Rating) + "</td></tr>";
      text = text + "<tr><td><label>From " + display_currency("USD") + " " + hotel["price"] + " /Night</label></td></tr>"; 
      text += "</table>";
      if (box_index > 0)
      {
         text +="<hr />";
      }
      if (nearest_hotels.length < 5){
        nearest_hotels.push(text);
      } else {
        while(nearest_hotels.length > 4){ 
            nearest_hotels.shift();      
        }
        if(box_index==0)
        {
            nearest_hotels= new Array();
        }
        nearest_hotels.push(text);
      }
      box.innerHTML = '';
      for (var i = nearest_hotels.length - 1; i > -1; i--){
        box.innerHTML = box.innerHTML + nearest_hotels[i];
      }
      box_index++;
      box_index %=5;
*/
}

function insert_box(box)
{
    var is_in = false;
    var len = boxes.length;
    for(var i=0; i<len; i++)
    {
      if(boxes[i]==box)
      {
         is_in=false;
         boxes[i]="";
         len--;
      }
      if(is_in)
      {
        boxes[i]=boxes[i+1];
      }
    }
    boxes.push(box);
}
function zz_showHotelInfo(id)
{
    switch_active("hotel_info");
    last_used_hotel_id = id;
    var hotel;
    var found=false;
    for(var i = 0; i < viewed.length; i++ ){
      if (viewed[i].id == id){
        hotel = viewed[i];
        found=true;
      }
    }
    if(!found)
      for(var i = 0; i < hotels.length; i++ ){
        if (hotels[i].id == id){
            hotel = hotels[i];
            found=true;
        }
      }
    map.setCenter(new GLatLng(hotel.latitude,hotel.longitude ));
    box = document.getElementById('infobox');
    var text="<table>"+
              "<tr>"+
                 "<td colspan=2><strong style='font-size: 12px; '>"+hotel.name+"</strong>"+
                    "<br>"+
                    "<hr />"+
                 "</td>"+
              "</tr>"+
              "<tr>"+
                 "<td rowspan=1>"+
                    "<img class='description_image' style='width: 127px;height: 104px; margin-top: 5px' src='"+ hotel.imageUrl +"'/>"+
                    "<br>"+
                    "<a href='"+hotel.imageUrl+"' rel='prettyPhoto[a]' title='' class='link'>show more pictures</a>"+
                "</td>"+
                "<td style='vertical-align: top'>"+
                    "<table id='hotel_info_side'>"+
                        "<tr><td style='padding-top:0'><strong>"+hotel.Postal_Code+"</strong></td></tr>"+
                          "<tr>"+
                            "<td>"+showStar(hotel.Hotel_Rating)+"</td>"+
                          "</tr>"+
                          "<tr>"+
                            "<td>From <strong>"+display_currency("USD")+"</strong> "+ convert_currency(hotel["price"], "GBP", "USD") +"</td>"+
                          "</tr>"+
                          "<tr>"+
                             " <td><a href='#' class='link sideHotelName' onclick='show_hotel_thickbox(\""+hotel.id+"\",\""+hotel.name+"\"); return false;'>More Info</a></td>"+
                          "</tr>"+
                          "<tr>"+
                             "<td><a onclick='window.open(\""+hotel.productUrl+"\"); return false' href='#'><img style='border: none' src='/images/book_now.png'/></a></td>"+
                          "</tr>"+
                    "</table>"+
                "</td>"+
              "</tr>"+
              "<tr>"+
                "<td colspan='2' style='padding-top:10px'>"+hotel.description.substr(0,400)+"...</td>"+
              "</tr>"+
              "<tr><td style='padding-top: 5px'><a href='#' class='link sideHotelName' onclick='show_hotel_thickbox(\""+hotel.id+"\",\""+hotel.name+"\"); return false;'>More Info</a></td></tr>"+
        "</table>";
        box.innerHTML = text;
        getHotelImages(hotel.HotelID);
}
function getHotelImages(hotelID)
{
    sendAttRequest("/search/hotels_search.php?format=json&a=img&hotelID="+hotelID,"text",
      function(jSonResponse)
      {
        eval("("+jSonResponse+")");
        var infobox = document.getElementById('infobox');
        var gallery = "<ul style='display:none'>";
        if(hotel_images)
            for(var i=0; i<hotel_images.length; i++)
            {
              gallery+="<li><a href='"+hotel_images[i]["URL"]+"' rel='prettyPhoto[a]' title='"+hotel_images[i]["Caption"]+"'>"+i+"</a></li>";
            }
        gallery +="</ul>";
        infobox.innerHTML +=gallery;
        $("a[rel^='prettyPhoto']").prettyPhoto({
                animationSpeed: 'fast', /* fast/slow/normal */
                padding: 40, /* padding for each side of the picture */
                opacity: 0.55, /* Value betwee 0 and 1 */
                showTitle: true, /* true/false */
                allowresize: true, /* true/false */
                counter_separator_label: '/', /* The separator for the gallery counter 1 "of" 2 */
                theme: 'dark_rounded', /* light_rounded / dark_rounded / light_square / dark_square */
                callback: function(){}
        });
      }
    );
}
function select_region(area)
{
    setAreaOver(area,'gmipam_0_canvas','0,0,255','0,0,0','0.33',0,0,0);
}
function show_hotel_thickbox(hotel_id, hotel_name)
{
      var thickbox = document.getElementById('thickbox_button');
      thickbox.alt="/hotel_detail/index.php?height=550&width=800&h_id="+hotel_id;
      thickbox.title="<h1>"+hotel_name+"</h1>";
      thickbox.click();
}
function show_attraction_thickbox(i){
    //creates the pop up
      var attraction = attractions[i];
      var icon = attraction["icon"];
      icon = icon.replace(".", "_1.");
      var thickbox = document.getElementById('thickbox_button');
      thickbox.alt="/attraction_detail/index.php?height=550&width=800&att_id="+attraction["id"];
      thickbox.title="<table><tr><td style='vertical-align: top'><img src='"+icon+"'/></td>"+"<td style='padding: 5px; padding-top: 7px'><h1>"+attraction["name"]+"</h1></td></tr></table>";
      thickbox.click();
}
function showAttractionInfo_(number, attraction){
    box = document.getElementById('infobox');     
    var text = "<table><tr><td rowspan='6'><img class='description_image' src='" + hotel.imageUrl + "' style='width: 110px; height: 110px;'></td></tr>"
    text = text + "<tr><td><a href='hotel/" + hotel.name + "'><b>" + hotel.name + "</b></a></td></tr>"
    text = text + "<tr><td>" + showStar(hotel.Hotel_Rating) + "</td></tr>"
    text = text + "<tr><td><label>" + display_currency("USD") + " " + convert_currency(hotel["price"], "GBP", "USD") + "</label></td></tr>";    
    text = text + "</table>"
    box.innerHTML = text;
}
function visit_attraction(att_id)
{
    for(var i =0; i<attractions.length; i++)
    {
      if(att_id==attractions[i]["id"])
            var attraction = attractions[i];
    }
    showAttractionMaker(att_id);
    //map.setZoom(17);
    map.setCenter(new GLatLng(attraction.latitude,attraction.longitude), 17);
    tb_remove();
    return false;
}
function visit_hotel(hotel_id)
{
    for(var i =0; i<hotels.length; i++)
    {
      if(hotel_id==hotels[i]["id"])
            var hotel = hotels[i];
    }
    showHotelMarker(hotel_id);
    map.setCenter(new GLatLng(hotel.latitude,hotel.longitude), 17);
    tb_remove();
    return false;
}
function distance(lon1, lat1, lon2,lat2)
/*
 *This function computes the distance between two points in miles
*/
{
    var HEARTH_RADIUS = 6371; // km
    var K=1.6093; //conversion factor from kms==>miles
    var dLat = toRad(lat2-lat1);
    var dLon = toRad(lon2-lon1); 
    var a = Math.sin(dLat/2) * Math.sin(dLat/2) +
        Math.cos(toRad(lat1)) * Math.cos(toRad(lat2)) * 
        Math.sin(dLon/2) * Math.sin(dLon/2); 
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 
    var distance = HEARTH_RADIUS* c;
    return distance/K;
}
function toRad(degrees)
{
    return degrees*(Math.PI/180);
}

function populate()
{
    var p_menu_in= document.getElementById("area_two");
    //get selected options from "area_one"
    var p_menu= document.getElementById("area_one");
    for(var i=0; i<p_menu.options.length; i++)
    {
      
      if(p_menu.options[i].selected)
      {
        p_menu_in.options[p_menu_in.options.length]=new Option(p_menu.options[i].value, p_menu.options[i].value);
      }
    }
    //append them to "area_two"
}
function depopulate()
{
    p_menu= document.getElementById("area_two");
    //get selected items
    for(var i=0; i<p_menu.options.length; i++)
    {
      if(p_menu.options[i].selected)
      {
        p_menu.options[i]=null;
      }
    }
    //remove them from list
}

function sendAttRequest(dest,method, callback)
{
    showAjaxLoader();
    var xmlHttp;
    try {
        // Firefox, Opera 8.0+, Safari
	xmlHttp=new XMLHttpRequest();
    } catch (e) {
		// Internet Explorer
        try{
			
            xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
	    } catch (e) {
                try {
                    xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
		} catch (e) {
                    alert("Your browser does not support AJAX!");
                    return false;
		}
	    }
    }

    //do the actual ajax stuff
    xmlHttp.onreadystatechange=function(){
        if(xmlHttp.readyState==4||xmlHttp.readyState=="complete"){
            var xmlResponse ;
            if(method=="text"){
                xmlResponse=xmlHttp.responseText;
              }
              else 
              {
                xmlResponse =xmlHttp.responseXML;
              }
              hideAjaxLoader();
              callback(xmlResponse);
		}  
	}
	xmlHttp.open("post",dest,true);
	xmlHttp.send(null);  
}
var keyword;
function zz_getSuggestionsList(element)
{
    //get the keyword
    keyword = element.value;
    if(keyword.length>2)
    {
      //send search query to the server
      sendAttRequest("/search/attractions.php?action=search&searchParams_name="+keyword,"xml",
                 displaySuggestedList);
    }
    
}
function zz__displaySuggestedList(xmlResponse)
{
    var suggestionsList=document.getElementById("suggestionsList");
    hotel_names = xmlResponse.getElementsByTagName("hotel");
    var test="";
    for(var i=0; i<hotel_names.length; i++)
    {
      for(var ii=0; ii<hotel_names[i].childNodes.length; ii++)
      {
        var s=hotel_names[i].childNodes.item(ii).childNodes.item(0).nodeValue;
        if(s!="N/A" && s.toLowerCase().indexOf(keyword.toLowerCase())>0)
        {
            keyword=document.getElementById("address").value;
            s = s.toLowerCase().replace(keyword, "<b>"+keyword+"</b>");
            test +="<tr onmouseover=\"this.style.backgroundColor='#e1e1e1'\" onmouseout=\" "+
                "this.style.backgroundColor='transparent'\"><td onclick='removeSuggestedList(this.innerHTML)'>"
                +s+"</td></tr>";
        }
        
      }
    }
    suggestionsList.innerHTML = "<table>"+ test +"</table>";
    suggestionsList.style.display="block";
}
function zz__removeSuggestedList(selectedItem)
{
    keyword=document.getElementById("address").value;
    selectedItem= selectedItem.replace("<b>"+keyword+"</b>", keyword);
    if(keyword=="")
    {
      selectedItem= selectedItem.replace("<b>", "");
      selectedItem= selectedItem.replace("</b>", "");
    }
    document.address_form.address.value=selectedItem;
    var suggestionsList=document.getElementById("suggestionsList");
    suggestionsList.style.display="none";
}
function refreshMap(map){
	var coords ;
	var mapCenter = map.getCenter();
	coords = '0,' + mapCenter.lng()+','+mapCenter.lat();
	getNearbyHotels(coords);
}

function getNearbyHotels(query,hotelInfo,isSynchCall){
/**
 * Description:
 * 	Refresh maps based on a string comprising of the long lat
 * 	NOTE: THIS ACTUALLY GETS THE ATTRACTIONS AS WELL!
 * Author: AM
 * Changelog:   	 
 *  mar10 JL - added extra param
 * @param String query - lng lat string separated by a comma
 *              deprecated - using map bound calls now
 * @param array hotelInfo - hotel array - used to create floating window
 * @param bool isSynchCall - indicate if it is a synchronous call. Most of time we do ajax asynch calls
 * @return none
 */
    var coords = new Array();
    var mapCenterPoint;

    //optional parameter mimick - setting the default
    if(typeof(hotelInfo) == "undefined"){
        hotelInfo = false;
    }
    if(typeof(isSynchCall) == "undefined"){
        isSynchCall = false;
    }

    //show loading gif while it is loading
    $('#loadImg').css('visibility', 'visible');

    var ajxUrl = "/search/hotels_search.php?format=json&"+hotelsNrMap.createAjaxBoundsCallStrg(map);
    if(isSynchCall){
        $.ajax({
            url : ajxUrl,
            dataType: 'json',
            async: false,
            success : function(data){
                eval(data);
                addHotelmarkers(hotels);
                map.setCenter(mapCenterPoint);
                filter();
                sortHotelsByDistance();
                showAttraction_data(attractions);
                if(hotelInfo){
                    hotelsNrMap.AddHotelFloatingWindow(hotelInfo)
                }
               //hide loading image
               $('#loadImg').css('visibility', 'hidden');
            }
        })        
    }
    else{//regular asynch call
        $.ajax({
            url : ajxUrl,
            dataType: 'json',
            async: true,
            success : function(data){
                eval(data);
                addHotelmarkers(hotels);
                map.setCenter(mapCenterPoint);
                filter();
                sortHotelsByDistance();
                showAttraction_data(attractions);
                if(hotelInfo){
                    hotelsNrMap.AddHotelFloatingWindow(hotelInfo)
                }
               //hide loading image
               $('#loadImg').css('visibility', 'hidden');
            }
        })
    }

}

function checkGetFriendlyUrl(){
/*-------------------------------------
Description:
chks if there is a friendly URL present. We check for '/find/' in the path, 
if so return the friendly string.

Author: JL
Dependencies: 
Updates:
rev 1 - JL - 
-------------------------------------*/
	if (location.pathname.substring(0,6) == '/find/'){
		return location.pathname.substr(6,location.pathname.length);		
	}
	else{
		
		return false;
	}
}

function init_hotels_arr(map){
/*-------------------------------------
Description:
Gets the hotel and attraction data by doing a ajax call returning a Json object of the hotel and attraction data

Author: Acquim
Dependencies: 
Updates:
rev 2 - JL - 

todo:
update to get city from either cookie or embedded hidden field?
-------------------------------------*/
    var debug = 0 // set 0 for no debug
    //var map_center = document.getElementById("map_center").value;
    var center_longitude="";
    var center_latitude="";
    
    //center map to the location retrieved from location search
    if(!GetParameterFromURL('searchFor')){
        //default to oxxford street
        map.setCenter(hotelsNrMap.defaultCenter,hotelsNrMap.defaultZoom);
    }
    //(For after url rewrite) center map to the location retrieved from location search
    else if(!getSearchFromURL('/hotels-near-')){
        //default to oxxford street
        map.setCenter(hotelsNrMap.defaultCenter,hotelsNrMap.defaultZoom);
    }


    // if friendly url present then get the parameters from the backend then render map
    if (checkGetFriendlyUrl()){
    	//alert(checkGetFriendlyUrl());
        sendAttRequest("/search/hotels_search.php?format=json&a=fURL&niceUrl="+checkGetFriendlyUrl(),"text",
        		function(jSonResponse){
        		//initialize both hotels and attractions
        			eval("("+jSonResponse+")");
        			initialize(cityDefaults);
        			//filter();
        			//sortHotelsByDistance();
        			//showAttraction_data(attractions);
        			//do_thickbox();
        		}
        );
    }
    else{//rendet it using the map defaults or from the get params        
        var ajxUrl = "/search/hotels_search.php?format=json&"+hotelsNrMap.createAjaxBoundsCallStrg(map);
        $.ajax({
            url : ajxUrl,
            dataType: 'json',
            success : function(data){
                eval(data);
                if (typeof(cityDefaults) === 'undefined'){
                    cityDefaults =0
                }
                initialize(cityDefaults);
                filter();
                sortHotelsByDistance();
                showAttraction_data(attractions);
                do_thickbox();
            }
        })

/*
    ---old call
        sendAttRequest(,"text","/search/hotels_search.php?format=json&lng="+center_longitude+"&lat="+center_latitude+"&"+hotelsNrMap.createAjaxBoundsCallStrg(map)
        		function(jSonResponse){
        		//initialize both hotels and attractions
                                //alert('fassdfsdf');
        			eval("("+jSonResponse+")");
                                //resetSearchParms();
        			if (typeof(cityDefaults) === 'undefined'){
                                    cityDefaults =0
        			}
        			initialize(cityDefaults);
        			filter();
        			sortHotelsByDistance();
        			showAttraction_data(attractions);
        			do_thickbox();
        		}
        );
*/
    }
    hotelsNrMap.lastRefreshLatLng = map.getCenter();
    attInfo.getAttractionpanelInfo(map.getCenter(),map.getZoom);

    //populate nearest hotels sidepanel
    hotelsNrMap.getNearestHotels(map.getCenter());
}    

function get_attraction_menu(att_name)
{
      if(att_name.length>3)
        sendAttRequest("../actions/events.php?a=7&as=1&att_name="+att_name+"&format=json","text",
            function(jSonResponse)
            {
              eval("("+jSonResponse+")");
              var att_menu = document.getElementById("admin_att_menu");
              var table = "<table>";
              for(var i=0; i<attractions.length; i++)
              {
                table +="<tr>"+
                        "<td><a href='#' onclick='fill_att_menu_value(this.innerHTML,"+attractions[i]["id"]+"); return false;'>"+attractions[i]["name"]+"</a></td>"+
                      "</tr>";
              }
              table += "</table>";
              att_menu.innerHTML=table;
              att_menu.style.display="block";
            });
}
function fill_att_menu_value(value, value_id)
{
    document.getElementById("att_name").value=value;
    var att_menu = document.getElementById("admin_att_menu");
    att_menu.style.display="none";
    document.getElementById("att_id").value=value_id;
}
function resetSearchParms(){
/*****************************
 *Description:
 *      Reads the cookie and sets the text box 'hotel search' with the cookie value
 * Author: AM
 * Dependencies
 * Changelog:
   o Rev1
 * @param none
 * @return non 
 */ 
    var cookie = readCookie("searchParams_name_cookie");
    var txtHotelNameSearch = document.getElementById('txtHotelNameSearch');
    if(!txtHotelNameSearch.value && cookie!=null){
        txtHotelNameSearch.value = cookie;
    }
    getLocations();
    cookie=readCookie("address_cookie");
    var address = document.getElementById('address');
    if(!address.value && cookie!=null)
    address.value = cookie;
}
function showLondonArea(lon_area, area_elem)
{
    sendAttRequest("/search/hotels_search.php?format=json&a=lon_area&area_name="+lon_area,"text",
      function(jSonResponse)
      {
        eval("("+jSonResponse+")");
        display_london_area(london_area);
        initialize();
        filter(); 
        sortHotelsByDistance();
        showAttraction_data(attractions);
        var point = new GLatLng(london_area.latitude,london_area.longitude);
        map.setCenter(point);
      });
    
}
function display_london_area(london_area)
{
    var photo= document.getElementById("lon_area_photo");
    photo.src=london_area.photo;
    var desc_td = document.getElementById("lon_area_desc");
    desc_td.innerHTML=london_area.descr;
    var title= document.getElementById("lon_area_title");
    title.innerHTML=london_area.name;
}
function getHotelDataResponse(xmlResponse)
/*
 *This function handlers the server response and create the hotels array for use @ the client side
*/
{
    var status = xmlResponse.getElementsByTagName("status").item(0).childNodes.item(0).nodeValue;
    if(status!=200)
    {
      return;
    }
    hotel_names = xmlResponse.getElementsByTagName("hotel");
    for(var i=0; i<hotel_names.length; i++)
    {
      var hotel = new Object();
      hotel["visible"] = true ;
      for(var ii=0; ii<hotel_names[i].childNodes.length; ii++)
      {
        if(!hotel_names[i].childNodes.item(ii).hasChildNodes())
        {
            continue;
        } 
        var name= hotel_names[i].childNodes.item(ii).nodeName;
        if(name=="facilities")
        {
            var facs = hotel_names[i].childNodes.item(ii).childNodes;
            hotel["facilities"]=new Array();
            for(var iii=0; iii<facs.length; iii++)
            {
              hotel["facilities"][iii]=facs[iii].childNodes.item(0).nodeValue;
            }
            continue;
        }
        var value=hotel_names[i].childNodes.item(ii).childNodes.item(0).nodeValue;
        hotel[name]=value;
      }
      if(i==0)
        hotels = new Array();
      hotels.push(hotel);
    }
}
function switch_active(ob){
    //shows the correct tab on the left handside
    new_panel = document.getElementById(ob);
    if (panel_active_tab.id != new_panel.id){      
      panel_active_tab.className = '';
      new_panel.className = 'active';
      panel_active_tab = new_panel;      
    }
    
}

function showAndSwitch(hotelId,tabId){
    if (hotelId != 0){
      //showHotelInfo(hotelId);
      switch_active(tabId);
    }
}

/**
 * adds a hotel to the list of recently viewed as a cookie
 * @author Chee
 * @param id The hotel id
 *
 * update log
 * 17 Mar'10 - Rewrote this function, orginal wasn't functioning consistently  - CD
 */
function addRecent(id){
    /*
    for ( var i = 0; i < hotels.length; i++ )
    {

          if (hotels[i].id == id)
          {
                while ( viewed.length > 4 )
                    viewed.shift();

                for( var j=0; j < viewed.length; j++ )
                {
                    if( viewed[j].id == id )
                    {
                          for(var k=j; k>0; k--)
                          {
                                viewed[k]= viewed[k-1];
                          }
                          viewed.shift();
                          break;
                    }
                }
                viewed.push(hotels[i]);
          }
    }
    for (var z = 0; z < viewed.length; z++){
      eraseCookie('hotel' + (z + 1));
      createCookie('hotel' + (z + 1 ), viewed[z].id, 365);
    }
    //showRecent();
   */

    var inList = false; //boolean flag for in product already in recently viewed list.
    var countArray = new Array( 0, 0, 0, 0, 0 );

    for( var i = 1; i < 6; i++ )
    {
        //put all available cookies into an array
        if( $.cookie('hotel'+i) != undefined )
            countArray[i] = $.cookie('hotel'+i);
        
        //check if id is already in list
        if( id == $.cookie('hotel'+i) )
            inList = true;
    }

    if(inList == false)
    {
        var k;
        //Shift all the cookies to +1
        for( var j = countArray.length; j > 0; j-- ) 
        {
            k = j-1;
            $.cookie('hotel'+j, $.cookie('hotel'+k), {path: "/"});
        }
        // put new id as the 1st cookie
        $.cookie('hotel1', id, {path: "/"});
    }
    //Live update recently viewed list
    cdShowRecent();
}

function zz_showRecent(){
/**
 * Description:
 * 	Createst the mark up for the left hand nav bar "recently viewed"
 * Author:
 * 	JL
 * Dependencies
 * Changelog: 
 * @param none
 * @return none
 */
    number = 1;
    //switch_active('recently_viewed');
    box = document.getElementById('infobox')
    box.innerHTML = '';
    var text = '';
    for (var i = viewed.length - 1; i > -1 ; i--){
      var first_name="";
      if(i == viewed.length - 1)
      {
        first_name="first";
      }
      text = '<table class="'+first_name+'">\n';
      text += '   <tbody>';
      text += '     <tr>';
      text += '         <td rowspan="6">';
      text += "           <a  class='sideHotelName' href='#' onclick='show_hotel_thickbox(\""+viewed[i].id+"\",\""+viewed[i].name+"\"); return false;'><img style='width: 75px; height: 75px;' src='"+ viewed[i].imageUrl +"' class='description_image'/></a>";
      text += '         </td>';
      text += '     </tr>';
      text += '     <tr>';
      text += '         <td colspan=2>';
      text += "           <a class='sideHotelName' onclick='show_hotel_thickbox(\""+viewed[i].id+"\",\""+viewed[i].name+"\"); return false;'>";
      text += '            <b>'+ viewed[i].name +'</b>';
      text += '           </a>';
      text += '         </td>';
      text += '     </tr>';
      text += '     <tr>';
      text += '         <td colspan=2>';
      text += '           ' + showStar(viewed[i].Hotel_Rating);
      text += '         </td>';
      text += '     </tr>';
      text += '     <tr>';
      text += '         <td>';
      text += '           <label>From '+display_currency("USD")+" "+convert_currency(viewed[i]["price"], "GBP", "USD") +' /Night</label>';
      text += '         </td>';
      text += "         <td style=\"width: 50px\"><a href='#' class='link sideHotelName' onclick='show_hotel_thickbox(\""+viewed[i].id+"\",\""+viewed[i].name+"\"); return false;' style='font-size: 9px'>More Info</a></td>";
      text += '     </tr>';
      text += '   </tbody>';
      text += '</table>';
      if (i > 0){
        text += '<hr width=100%/>';
      }
      box.innerHTML += text;
    }
}

function showStar(num){
    //shows the hotel star rating
    if (num == ''){
      text = "No hotel rating provided";
    }
    
    text = '<ul>';
    for ( i = 0; i < num; i++){
      text += '<li class="starOn_med"></li>';
    }    
    text += '</ul>';
    return text;
}
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name){
/*****************************
 *Description:
 *  Reads the cookie using the old javascript method
 * Author: A
 * Dependencies
 * Changelog:
   o Rev1
 * @param String $name name if the cookie being extracted
 * @return type description of return type 
 */    
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
var attractionMarkers= new Array();

function showAttraction_data(att)
{//outputs the attractions array 
    attractionMarkers= new Array();
    for (var i = 0 ; i < att.length; i++){
        var point = new GLatLng(att[i].latitude,att[i].longitude);
        var maker = createAttractionMarker(point, i, att[i]);
        attractionMarkers[att[i].id]=maker;
        map.addOverlay(maker);

        if(!att[i]["event_name"]){
            att[i]["event_name"]="No events at this venue";
        }
        if(!att[i]["event_image"]){
            att[i]["event_image"]="/images/noImageAttractionsmall.png";
        }

        //check if this marker should be hidden or shown based on it's category
        if( categoryArray[att[i].cat.toLowerCase()] == 'hidden' )
            maker.hide();
        else if( att[i].cat == 'Tourist Attraction' && categoryArray['tourist'] == 'hidden'  )
            maker.hide();

    }// close for loop of attractions array

}

function addAttractionEvent(thumbImage,name, description,distance, offLinkUrl,thickboxNum){
/********************
 * Description:
 *  Creates html of an attraction or event  
 * Author: JL
 * Dependencies
 * Changelog: 
 *  Rev1 JL
 *  Aug 09 - remove setting of cookie for loc
 * @param string thumbImage - url og the image location
 * @param string name - name of the attraction or event
 * @param string offLinkUrl - the money making url/monetisable link
 * @param string thickboxNum - this is the thickbox id we used to open the floating box
 * @return string - html of the attraction/event data
 * 
 * todo: convert to css, get rid of tables
 * todo: add code show complete name of name if > 25 - modify the 
 * 
 */  
    //create book now button if we have a off site link

    //chk if link is valid
	if(Left(offLinkUrl,4) == 'http'){
        book_now_button ='<a onclick=\'window.open("' + offLinkUrl + '"); return false\' href="#">' +
            '   <img src="/images/book_white.png"></a>';
    }
    else{
        book_now_button ='';
    }
    
    // work out distance
    distance = Math.round(distance *100, 2)/100;
    
    
    attrEventHtml = '<table class="attractionEventItem"><col width: 40%>' +
        '   <tr>'+
        '       <td rowspan="4">'+
        '           <img src="'+ thumbImage + '" style=\"width: 130px; height: 130px;\">' +
        '       </td>' +
        '       <td class="att_panel_header">' +
        '           <b>' + name.substring(0,25) + '</b>' +
        '       </td>'+
        '       <td class="att_panel_header" style="text-align: center; font-size: 80%;">' +
        '           <span style="line-height: 3"><b>' + 
        '               ' + distance + '</b> miles away</span>' +
        '       </td>' +
        '   </tr>' +
        '   <tr>' +
        '       <td colspan=2>' + description.substring(0,160) + '...' + '</td>' +
        '   </tr>' +
        '   <tr><td colspan=2 style="text-align:right; vertical-align:bottom">' +
        book_now_button +
        '       <a href="#" onclick=\'show_attraction_thickbox('+thickboxNum+'); return false;\'>' +
        '           <img src=\"/images/find_out.png\"/> '+
        '       </a></td></tr>' +
        '   </tr> </table>';
    
    return attrEventHtml;
}


function eraseCookie(name) {
	createCookie(name,"",-1);
}

function showHotel(id,highLightHotel){
    for (var i = 0; i < hotels.length; i++){
      if (hotels[i].id == id){
        map.setCenter(new GLatLng(hotels[i].latitude,hotels[i].longitude));
        map.setZoom(19);
        if(highLightHotel){
        	show_hotel_thickbox(id,hotels[i].name);
        }
      }
    }

}
function get_containing_london_area(lng, lat)
{
    for(var i=0; i<london_areas.length; i++)
    {
      var dist = distance(london_areas[i]["lng"], london_areas[i]["lat"], lng, lat);
      var name = london_areas[i];
      var priority = -1*dist;
      priorityQueue.insert(name, priority);
    }
    var containing_area = priorityQueue.get();
    display_london_area(containing_area);
    var area = document.getElementById(containing_area["name"]);
    while(!area)
    {
      containing_area = priorityQueue.get();
      if(!containing_area)
        break;
      area = document.getElementById(containing_area["name"]);
    }
    if(!area)
      return;
    clear_selection(area,'gmipam_0_canvas',0,0);
    selected_region=area;
    setAreaOver(selected_region,'gmipam_0_canvas','0,0,255','0,0,0','0.38',0,0,0);
}

var priorityQueue = function () {

    // "private"
    var priorityArray = [];

    // "public"
    return {
      insert: function (name, priority) {
        var i = 0;
        while (i <= priorityArray.length && priority < ((priorityArray[i] || {"priority": Infinity}).priority || Infinity)) {                    
            i++;
        }             
        priorityArray.splice(i, 0, {"name": name, "priority": priority});
        return true;        
      },
      get: function () {
        return (priorityArray.shift() || {"name": undefined}).name;
      },
      peek: function () {
        return (priorityArray[0] || {"name": undefined}).name;
      }
    };
}();

//function attractionMenu()
//{
    //alert("showing attractions menu");
    var menu=function(){
	var t=15,z=100,s=6,a;
	function dd(n){this.n=n;this.h=[];this.c=[]}
	dd.prototype.init=function(p,c){
		a=c;var w=document.getElementById(p), s=w.getElementsByTagName('ul'), l=s.length, i=0;
		for(i;i<l;i++){
			var h=s[i].parentNode;this.h[i]=h;this.c[i]=s[i];
			h.onmouseover=new Function(this.n+'.st('+i+',true)');
			h.onmouseout=new Function(this.n+'.st('+i+')');
                h.onclick=new Function(this.n+'.st('+i+')');
		}
	}
	dd.prototype.st=function(x,f){
		var c=this.c[x], h=this.h[x], p=h.getElementsByTagName('a')[0];
		clearInterval(c.t);c.style.overflow='hidden';
		if(f){
			p.className+=' '+a;
			if(!c.mh){c.style.display='block';c.style.height='';c.mh=c.offsetHeight;c.style.height=0}
			if(c.mh==c.offsetHeight){c.style.overflow='visible'}
			else{c.style.zIndex=z;z++;c.t=setInterval(function(){sl(c,1)},t);}
		}else{p.className=p.className.replace(a,'');c.t=setInterval(function(){sl(c,-1)},t)}
	}
	function sl(c,f){
		var h=c.offsetHeight;
		if((h<=0&&f!=1)||(h>=c.mh&&f==1)){
			if(f==1){c.style.filter='';c.style.opacity=1;c.style.overflow='visible'}
			clearInterval(c.t);return
		}
		var d=(f==1)?Math.ceil((c.mh-h)/s):Math.ceil(h/s), o=h/c.mh;
		c.style.opacity=o;c.style.filter='alpha(opacity='+(o*100)+')';
		c.style.height=h+(d*f)+'px'
	}
	return{dd:dd}
    }();
    //return menu;
//}

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];
}

function isSet(objTest){
/*-------------------------------------
Description:
chk if object set.

Author: JL

Updates:
@Parameters: objName = name of the object we are checking for
-------------------------------------*/

try{
    var test = objTest;  
}
catch(e){
    return false;
}
return true;
}

function showSearch(searchToShow){
/*-------------------------------------
Description:
Displays the correct search tab and hides the other

Author: JL

Updates:
@Parameters: searchToShow = id name of the tab to show
-------------------------------------*/
    //alert('Show ' + searchToShow);
    if(searchToShow =='hotel'){
    	//show/high search areas
    	$('#locationSearch').css('display','none');
        $('#hotelSearch').css('display','block');
        
        //change button states
        $('#locSearchTab').removeClass('searchContainerBtnSelected');
        $('#hotelSearchTab').addClass('searchContainerBtnSelected');
    }
    if(searchToShow =='location'){
        $('#locationSearch').css('display','block');
        $('#hotelSearch').css('display','none');
        
        //change button states
        $('#locSearchTab').addClass('searchContainerBtnSelected');
        $('#hotelSearchTab').removeClass('searchContainerBtnSelected');
    }
}

function Left(str, n){
/*-------------------------------------
Description:
returns the left n amount of letters eg left('ABCDEF',3) returns 'ABC'

Author: JL

Updates:
@Parameters: searchToShow = id name of the tab to show
-------------------------------------*/
   if (n <= 0)
         return "";
   else if (n > String(str).length)
         return str;
   else
         return String(str).substring(0,n);
}

