

function loadMap()
{
   if(document.getElementById('map'))
   {
      load();
   }
}

function unloadMap()
{
   if(document.getElementById('map'))
   {
      GUnload();
   }
}



function searchOption(type)
{
   if(current_selection == type)
   {
      resetSearchOptions();   
   }
   else
   {
      if(current_selection != '')
      {
         document.getElementById('search_option_'+current_selection+'_div').style.borderBottom = '1px solid #FFFFFF';   
      }
      var search_option_content = '';
      
      if(type == 'region')
      {
         search_option_content = populateRegion(document.getElementById('search_country').value); 
      }
      else if(type == 'area')
      {
         if(document.getElementById('region'))
         {
            search_option_content = populateArea(document.getElementById('search_region').value);  
         }
      }
      else
      {
         search_option_content = search_options_html[type];
      }
      document.getElementById('set_search_option_div').innerHTML = search_option_content;
      
      
      // If multi-option, populate current values
      if(type == 'location_features' ||
         type == 'property_features')
         {
            populateMultiOptions(type);     
         }
      // If dates, populate the calendars
      else if(type == 'dates')
      {
         showSearchDates('both');
      }
      // Otherwise set the radio button
      else
      {
         populateRadioButton(type);  
      }
      
      
      current_selection = type;
   }
      
}




var called = 0;
function enableOption(option,enable)
{
   obj = document.getElementById('search_option_'+option+'_div');
   if(obj)
   {
      var enabled = '<span>&raquo; </span><a href="javascript:searchOption(\''+option+'\');">'+option+'</a>';
      var disabled = '<span>&raquo; </span><a href="#" onclick="return false;">'+option+'</a>';
      obj.innerHTML = (enable) ? enabled : disabled;
      obj.className = (enable) ? 'search_option' : 'search_option_disabled';  
   }                                                               
}


function selectOption(option,select)
{
   obj = document.getElementById('search_option_'+option+'_div');
   if(obj)
   {
      obj.className = (select) ? 'search_option_selected' : 'search_option';  
   }   
}   




function toggleFlexibleDates(obj)
{
   document.getElementById('results_option_flexible_dates').value = (document.getElementById('search_flexible_dates').checked) ? 'yes' : 'no';
   updateNavFlexibleDates();       
   if(checkInAndCheckOutSet()) updateCurrentSelection();
}




function changeSearchOption(change,to)
{
   var objName = '';
   var val_obj = document.getElementById('results_option_'+change);
   var current_value = val_obj.value;    
   if(current_value)
   {
      objName = 'results_option_'+change+'_'+current_value.replace(/ /g,'_');
      var current_obj = document.getElementById(objName);
      current_obj.className = 'results_option'; 
   }
   objName = 'results_option_'+change+'_'+to.replace(/ /g,'_');
   var obj = document.getElementById(objName);
   obj.className = 'results_option_selected';
   val_obj.value = to;
   
   // If we're setting the 'results_to_display' variable
   // make sure we reset the page number, note that that
   // will automatically call doSearch so no need to call
   // it again in this function...
   if(change == 'results_to_display')
   {
      setPage(1);  
   }
   // Changing the flexibility option is the only
   // option which potentially results in a different
   // number of results being displayed. If we're not
   // setting that particular option, just skip ahead to the
   // actual search...
   else
   {
      doSearch();  
   }
}


function toggleResultsOptionDiv(objName)
{
   for(var i = 0; i < results_option_divs.length; i++)
   {
      if(results_option_divs[i]!=objName) document.getElementById(results_option_divs[i]+'_div').style.display = 'none';  
   }
   var obj = document.getElementById(objName+'_div');
   obj.style.display = (obj.style.display == 'none') ? '' : 'none';
}





function showSearchDates(show_type)
{
    if(show_type == 'both')
    {
       setLoading('search_dates_checkin_calendar',true);
       show_type_both = true;
       current_show_type = 'checkin';
       qs = "type="+current_show_type+"&month="+current_cim+"&year="+current_ciy;
       var url = '/ajax/search_get_dates_calendar.ajax.php?'+qs;
       ajaxRequest(url, true, 'showSearchDatesResponse');  
    }
    else
    {
       setLoading('search_dates_'+show_type+'_calendar',true); 
       current_show_type = show_type;
       qs = "type="+show_type;
       qs += (show_type=='checkin') ? "&month="+current_cim+"&year="+current_ciy : "&month="+current_com+"&year="+current_coy;
       // If loading checkout and check-in is set, but not check out, make sure checkout calendar is up to date
       if(current_cim!='' && current_ciy!='' && current_com=='' && current_coy=='' && show_type=='checkout') qs = "type=checkout&month="+current_cim+"&year="+current_ciy;
       var url = '/ajax/search_get_dates_calendar.ajax.php?'+qs;
       ajaxRequest(url, true, 'showSearchDatesResponse');  
    }
}


function panCalendar(type, month, year)
{
   current_show_type = type;
   qs = "type="+current_show_type+"&month="+month+"&year="+year;
   var url = '/ajax/search_get_dates_calendar.ajax.php?'+qs;
   ajaxRequest(url, true, 'showSearchDatesResponse'); 
}


function populateSearchDates()
{
   var bgcolor_selected = "/images/bgcolor_selected.png";   
   if(current_cid != 0 && current_cim != 0 && current_ciy != 0)
   {
      objName = 'search_checkin_date_'+current_cid+'_'+current_cim+'_'+current_ciy;
      obj = document.getElementById(objName);
      if(obj) obj.style.backgroundImage = 'url('+bgcolor_selected+')';  
   } 
   if(current_cod != 0 && current_com != 0 && current_coy != 0)
   {
      objName = 'search_checkout_date_'+current_cod+'_'+current_com+'_'+current_coy;
      obj = document.getElementById(objName);
      if(obj) obj.style.backgroundImage = 'url('+bgcolor_selected+')';  
   }
   if(document.getElementById('search_flexible_dates'))  
      document.getElementById('search_flexible_dates').checked = (document.getElementById('results_option_flexible_dates').value == 'no') ? false : true;  
}



function checkInAndCheckOutSet()
{
   return (document.getElementById('search_dates_checkin').value!='' && document.getElementById('search_dates_checkout').value!='');  
}

function checkOutSet()
{
   return (document.getElementById('search_dates_checkout').value!='');  
}

function updateNavDates()
{
   var _search_dates_checkin = new Date(document.getElementById('search_dates_checkin').value * 1000);
   var _search_dates_checkout = new Date(document.getElementById('search_dates_checkout').value * 1000);
   var from_day_obj = document.getElementById('from_day');   
   var from_month_obj = document.getElementById('from_month');  
   var from_year_obj = document.getElementById('from_year');  
   var to_day_obj = document.getElementById('to_day');   
   var to_month_obj = document.getElementById('to_month');  
   var to_year_obj = document.getElementById('to_year');  
   from_day_obj.value = _search_dates_checkin.getDate();
   from_month_obj.value = _search_dates_checkin.getMonth()+1;
   from_year_obj.value = _search_dates_checkin.getFullYear();
   to_day_obj.value = _search_dates_checkout.getDate();
   to_month_obj.value = _search_dates_checkout.getMonth()+1;
   to_year_obj.value = _search_dates_checkout.getFullYear();
}

function updateNavFlexibleDates()
{
   var to_set = document.getElementById('results_option_flexible_dates').value;
   // Equals no or yes no but if no search dates set, set it to any
   if(!checkInAndCheckOutSet()) to_set = 'any';
   document.getElementById('flexible_'+to_set).checked = true;
   enableNavDates();
}

function searchDateSelect(d,m,y,type)
{
   if(selectedDateIsValid(d,m,y,type))
   {
      searchDateHighlight(d,m,y,type);
      var _d = Date.UTC(y,m-1,d,0,0,0,0); 
      _d/=1000;
      document.getElementById('search_dates_'+type).value=_d;
      if(checkInAndCheckOutSet())
      {
         selectOption('dates',true);
         updateNavFlexibleDates(); 
         updateNavDates();
         updateCurrentSelection();
      }
      // If check in day is selected, check out day not set and we're not showing that month presently, pan the calendar
      else if(type == 'checkin' && !checkOutSet() && (display_com != m || display_coy != y))
      {
         setLoading('search_dates_checkout_calendar',true);
         panCalendar('checkout',m,y);     
      }
   }
   else
   {
      if(type == 'checkin')
      {
         alert("Please ensure the check-in date is before the check-out date");  
      }
      else if(type == 'checkout')
      {
         alert("Please ensure the check-out date is after the check-in date"); 
      }
   }
}


function selectedDateIsValid(d,m,y,type)
{
   if(type == 'checkin')
   {
      // If check-out date is set, ensure it's after the selected date
      if(current_cod != 0 && current_com != 0 && current_coy != 0)
      {
         if(current_coy > y ||
           (current_coy == y && current_com > m) ||
           (current_coy == y && current_com == m && current_cod > d))
           {
              return true;
           } 
         else
         {
            return false;  
         }
      }
      // You can select any date if no check-out date is set
      else
      {
         return true;  
      }
   }
   else if(type == 'checkout')
   {
      // If check-in date is set, ensure it's before the selected date
      if(current_cid != 0 && current_cim != 0 && current_ciy != 0)
      {
         if(current_ciy < y ||
           (current_ciy == y && current_cim < m) ||
           (current_ciy == y && current_cim == m && current_cid < d))
           {
              return true;
           } 
         else
         {
            return false;  
         }
      }
      // You can select any date if no check-out date is set
      else
      {
         return true;  
      }
   }  
}



function searchDateHighlight(d,m,y,type)
{
   var bgcolor_selected = "/images/bgcolor_selected.png";
   var objName;
   var obj;
   if(type == 'checkin')
   {
      if(current_cid != 0 && current_cim != 0 && current_ciy != 0)
      {
         objName = 'search_'+type+'_date_'+current_cid+'_'+current_cim+'_'+current_ciy;
         obj = document.getElementById(objName);
         if(obj) obj.style.backgroundImage = ''; 
      }
      current_cid = d;
      current_cim = m;
      current_ciy = y;
   }
   else
   {
      if(current_cod != 0 && current_com != 0 && current_coy != 0)
      {
         objName = 'search_'+type+'_date_'+current_cod+'_'+current_com+'_'+current_coy;
         obj = document.getElementById(objName);
         if(obj) obj.style.backgroundImage = ''; 
      }
      current_cod = d;
      current_com = m;
      current_coy = y;
   }    
   objName = 'search_'+type+'_date_'+d+'_'+m+'_'+y;
   obj = document.getElementById(objName);
   obj.style.backgroundImage = 'url('+bgcolor_selected+')';
}





function populateMultiOptions(type)
{
   var current_value = ","+document.getElementById('search_'+type).value;    
   var selection = new Array();
   selection = current_value.split(',');
   for(var i = 0; i < selection.length; i++)
   {
      var val = selection[i];
      if(val != null && val != "" && !isNaN(val))
      {
         var obj = type+"_cb_"+selection[i];
         document.getElementById(obj).checked = true;
      }  
   }
}



function populateRadioButton(type)
{
   var obj = document.getElementById('search_'+type);
   var inputs = document.getElementsByTagName('input');
   if(inputs)
   {
      for(var i = 0; i < inputs.length; i++)
      {
         if(inputs[i].type == 'radio' && inputs[i].name == type+'_rb')
         {
            inputs[i].checked = inputs[i].value == obj.value;  
         }
      }  
   }
}





function useOption(search_by,value)
{
   if(search_by == 'country')
   {
       // If country, enable region, disable area
       enableOption('region',true);
       enableOption('area',false);
       resetRegion();
       resetArea(); 
   }
   if(search_by == 'region')
   {
       // If region, enable area
       enableOption('area',true); 
       resetArea();  
   }
   document.getElementById('search_'+search_by).value = value; 
   selectOption(search_by,true);
   resetSearchOptions();
   updateCurrentSelection();
}


function optionClickHandler(search_by,value,do_toggle)
{
   var obj = document.getElementById(search_by+"_cb_"+value);
   if(do_toggle) toggleCheckBox(obj); 
   if(obj.checked) useMultiOption(search_by,value);
   else removeSearchMultiOption(search_by,value);
}




function toggleCheckBox(obj)
{
   obj.checked = !obj.checked; 
}


function setRadioButton(obj,value)
{
   obj.value = value;
}


function toggleMapOption(option)
{
   var obj = document.getElementById('slideshow_button');
   var src = obj.src;
   if(option == 'slideshow')
   {
      if(src.indexOf("pause") == -1)
      {
         obj.src = "/images/pause.gif";
         // Start slideshow
         showOnMap();
      }
      else
      {
         obj.src = "/images/play.gif"; 
         // Pause slideshow
         stopSlideShow();
      }
   } 
}


function useMultiOption(search_by,value)
{
   var current_value = document.getElementById('search_'+search_by).value;
   if(current_value.indexOf(value+",")==-1)
   {
      document.getElementById('search_'+search_by).value = current_value + value+",";
      selectOption(search_by,true);
      updateCurrentSelection();
   }
}


function removeSearchOption(search_by,value)
{
   if(search_by == 'dates')
   {
      document.getElementById('search_dates_checkin').value = '';
      document.getElementById('search_dates_checkout').value = '';   
      if(current_cid != 0 && current_cim != 0 && current_ciy != 0)
      {
         objName = 'search_checkin_date_'+current_cid+'_'+current_cim+'_'+current_ciy;
         obj = document.getElementById(objName);
         if(obj) obj.style.backgroundImage = ''; 
      }
      if(current_cod != 0 && current_com != 0 && current_coy != 0)
      {
         objName = 'search_checkout_date_'+current_cod+'_'+current_com+'_'+current_coy;
         obj = document.getElementById(objName);
         if(obj) obj.style.backgroundImage = ''; 
      }
      current_cid = 0;
      current_cim = 0;
      current_ciy = 0;
      current_cod = 0;
      current_com = 0;
      current_coy = 0;
      updateNavFlexibleDates();   
   }
   else
   {
      document.getElementById('search_'+search_by).value = '';
      if(search_by == 'country')
      {
         // If country is removed, so is region > area
         // and both become disabled
         document.getElementById('search_region').value = '';
         document.getElementById('search_area').value = '';
         enableOption('region',false);
         enableOption('area',false);  
      }
      if(search_by == 'region')
      {
         // If region is removed, so is area
         // and the area option is disabled
         document.getElementById('search_area').value = '';
         enableOption('area',false);  
      }
   }
   resetSearchOptions();
   selectOption(search_by,false); 
   updateCurrentSelection();  
}


function removeSearchMultiOption(search_by,value)
{
   var objName = search_by+"_cb_"+value;
   var obj = document.getElementById(objName);
   if(obj) obj.checked = false;
   var current_value = ","+document.getElementById('search_'+search_by).value;
   var new_value = current_value.replace(","+value+",",",");
   new_value = new_value.substring(1);
   document.getElementById('search_'+search_by).value = new_value;
   if(new_value == '')
   {
      selectOption(search_by,false); 
   }
   updateCurrentSelection(); 
}



function resetArea()
{
   document.getElementById('search_area').value = '';  
}


function resetRegion()
{
   document.getElementById('search_region').value = '';  
}

function resetSearchOptions()
{
   if(current_selection != '')
   {
      document.getElementById('search_option_'+current_selection+'_div').style.borderBottom = '1px solid #FFFFFF';   
   }   
   document.getElementById('set_search_option_div').innerHTML = '&nbsp;';  
   document.getElementById('set_search_option_div').style.borderLeft = '1px solid #FFFFFF';  
   current_selection = '';
}

function populateArea(region)
{
   var search_option_content = '';
   if(!isNaN(region) && region > 0)
   {
      search_option_content = ajaxRequestAlt('/ajax/get_sub_menu.ajax.php?area_obj_name=area_rb&area_id='+region+'&format=radio', false);
   } 
   else
   {
      search_option_content = 'please select a region before narrowing your search to a particular area';
   }
   return search_option_content;
}


function populateRegion(country)
{
   var search_option_content = '';
   if(!isNaN(country) && country > 0)
   {
      search_option_content = ajaxRequestAlt('/ajax/get_sub_menu.ajax.php?area_obj_name=region_rb&area_id='+country+'&format=radio', false);
   } 
   else
   {
      search_option_content = 'please select a country before narrowing your search to a particular region';
   }
   return search_option_content;
}







function showSearchDatesResponse()
{
   if (xmlHttp.readyState==4)
   {
      rc = xmlHttp.responseText;
      var _arr = rc.split("|");
      if(_arr[0] == 'checkin')
      {
         display_cim = _arr[1];
         display_ciy = _arr[2];  
      }
      else if(_arr[0] == 'checkout')
      {
         display_com = _arr[1];
         display_coy = _arr[2];  
      }
      var div = 'search_dates_'+current_show_type+'_calendar_div';
      document.getElementById(div).innerHTML = _arr[3];
      setLoading('search_dates_'+current_show_type+'_calendar',false); 
      if(show_type_both && current_show_type == 'checkin') { current_show_type == 'checkout'; show_type_both = false; showSearchDates('checkout'); }
      populateSearchDates();
   }
}





function setPage(page)
{
   setLoading('search_results',true);
   var obj = document.getElementById('search_page');
   obj.value = page;
   doSearch();
   var idx = this.location.href.indexOf("#");
   this.location.href = (idx==-1) ? this.location.href+"#search" : this.location.href.substring(0,idx)+"#search";
   window.location.href="#q="+getQ();
}





function doSearchResponse()
{
   if (xmlHttp.readyState==4)
   {
      rc = xmlHttp.responseText;
      var search_results_div = document.getElementById('search_results_div');
      var _div = document.createElement("div"); 
      _div.innerHTML = rc;
      search_results_div.innerHTML = "";
      search_results_div.appendChild(_div);
      setLoading('search_results',false);
      // This is for map data
      if(document.getElementById("to_eval"))
      {
         eval(document.getElementById("to_eval").innerHTML.substring(4));
      }
      // This is for analytics
      if(document.getElementById("urchin_data_to_eval"))
      {
         eval(document.getElementById("urchin_data_to_eval").innerHTML.substring(4));
      }
      if(server_post_load_images == 1)
      {
         lzload();
		}
   }
}


function base64_encode( data ) {
        
    var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, enc="", tmp_arr = [];
 
    if (!data) {
        return data;
    }
 
    data = utf8_encode(data+'');
    
    do {
        o1 = data.charCodeAt(i++);
        o2 = data.charCodeAt(i++);
        o3 = data.charCodeAt(i++);
 
        bits = o1<<16 | o2<<8 | o3;
 
        h1 = bits>>18 & 0x3f;
        h2 = bits>>12 & 0x3f;
        h3 = bits>>6 & 0x3f;
        h4 = bits & 0x3f;
 
        tmp_arr[ac++] = b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
    } while (i < data.length);
    
    enc = tmp_arr.join('');
    
    switch( data.length % 3 ){
        case 1:
            enc = enc.slice(0, -2) + '==';
        break;
        case 2:
            enc = enc.slice(0, -1) + '=';
        break;
    }
 
    return enc;
}


function utf8_encode ( string ) {
 
    string = (string+'').replace(/\r\n/g, "\n").replace(/\r/g, "\n");
 
    var utftext = "";
    var start, end;
    var stringl = 0;
 
    start = end = 0;
    stringl = string.length;
    for (var n = 0; n < stringl; n++) {
        var c1 = string.charCodeAt(n);
        var enc = null;
 
        if (c1 < 128) {
            end++;
        } else if((c1 > 127) && (c1 < 2048)) {
            enc = String.fromCharCode((c1 >> 6) | 192) + String.fromCharCode((c1 & 63) | 128);
        } else {
            enc = String.fromCharCode((c1 >> 12) | 224) + String.fromCharCode(((c1 >> 6) & 63) | 128) + String.fromCharCode((c1 & 63) | 128);
        }
        if (enc != null) {
            if (end > start) {
                utftext += string.substring(start, end);
            }
            utftext += enc;
            start = end = n+1;
        }
    }
 
    if (end > start) {
        utftext += string.substring(start, string.length);
    }
 
    return utftext;
}


function base64_decode( data ) {
 
    var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
    var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, ac = 0, dec = "", tmp_arr = [];
 
    if (!data) {
        return data;
    }
 
    data += '';
 
    do {
        h1 = b64.indexOf(data.charAt(i++));
        h2 = b64.indexOf(data.charAt(i++));
        h3 = b64.indexOf(data.charAt(i++));
        h4 = b64.indexOf(data.charAt(i++));
 
        bits = h1<<18 | h2<<12 | h3<<6 | h4;
 
        o1 = bits>>16 & 0xff;
        o2 = bits>>8 & 0xff;
        o3 = bits & 0xff;
        
        if (h3 == 64) {
            tmp_arr[ac++] = String.fromCharCode(o1);
        } else if (h4 == 64) {
            tmp_arr[ac++] = String.fromCharCode(o1, o2);
        } else {
            tmp_arr[ac++] = String.fromCharCode(o1, o2, o3);
        }
    } while (i < data.length);
 
    dec = tmp_arr.join('');
    dec = utf8_decode(dec);
 
    return dec;
}


function utf8_decode ( str_data )
{
 
    var tmp_arr = [], i = 0, ac = 0, c1 = 0, c2 = 0, c3 = 0;
    
    str_data += '';
    
    while ( i < str_data.length ) {
        c1 = str_data.charCodeAt(i);
        if (c1 < 128) {
            tmp_arr[ac++] = String.fromCharCode(c1);
            i++;
        } else if ((c1 > 191) && (c1 < 224)) {
            c2 = str_data.charCodeAt(i+1);
            tmp_arr[ac++] = String.fromCharCode(((c1 & 31) << 6) | (c2 & 63));
            i += 2;
        } else {
            c2 = str_data.charCodeAt(i+1);
            c3 = str_data.charCodeAt(i+2);
            tmp_arr[ac++] = String.fromCharCode(((c1 & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
            i += 3;
        }
    }
 
    return tmp_arr.join('');
}








function initAJAXHistory()
{ 
   dhtmlHistory.initialize();
   dhtmlHistory.addListener(historyChange);
}




function addHistoryEvent(l,d) 
{
   dhtmlHistory.add(l,d);
}





function updateCurrentSelection(no_reset_page)
{
    setLoading('current_selection',true);
    
    if(no_reset_page != true)
    {
       // Reset the page number because results will be different
       document.getElementById('search_page').value = 1;
    }
    var vars = [];
    var qs = '';
    // SEARCH VARIABLES 
    vars[0]='region';vars[1]='area';vars[2]='property_type';vars[3]='bedrooms';vars[4]='sleeps';vars[5]='price';vars[6]='dates_checkin';vars[7]='dates_checkout';vars[8]='location_features';vars[9]='property_features';vars[10]='country';vars[11]='page';
    for(var i = 0; i < vars.length; i++)
    {
       qs += vars[i]+"="+document.getElementById('search_'+vars[i]).value+"&";
    }
    // RESULTS VARIABLES
    vars = [];
    vars[0]='results_to_display';vars[1]='display_map';vars[2]='flexible_dates';vars[3]='sort_by';vars[4]='sort_type';
    for(var i = 0; i < vars.length; i++)
    {
       qs += vars[i]+"="+document.getElementById('results_option_'+vars[i]).value+"&";
    }
    
    qs = qs.substring(0,qs.length-1);
    var url = '/ajax/search_get_current_selection_text.ajax.php?'+qs;
    ajaxRequest(url, true, 'updateCurrentSelectionResponse');
}


function updateCurrentSelectionResponse()
{
   if (xmlHttp.readyState==4)
   {
      rc = xmlHttp.responseText;
      var current_selection_div = document.getElementById('current_selection_div');
      current_selection_div.innerHTML = rc;
      setLoading('current_selection',false);
      doSearch();
   }
}


function setLoading(obj,loading)
{
    var div = document.getElementById(obj+'_div');
    var loading_div = document.getElementById(obj+'_loading_div');
    div.style.display = (loading) ? 'none' : '';
    loading_div.style.display = (loading) ? '' : 'none';  
}


 var map;
 var tooltip;
 var gmarkers = [];
 var marker_counter = 0;
 var baseIcon = new GIcon();
 var map_geo_lat = 0;
 var map_geo_lng = 0;
 baseIcon.iconSize=new GSize(32,32);
 baseIcon.shadowSize=new GSize(56,32);
 baseIcon.iconAnchor=new GPoint(16,32);
 baseIcon.infoWindowAnchor=new GPoint(16,0);
 var propertyIcon = new GIcon(baseIcon, "http://maps.google.com/mapfiles/kml/pal5/icon12.png", null, "http://maps.google.com/mapfiles/kml/pal5/icon12s.png");

 function load() 
 {
   if (GBrowserIsCompatible())
   {
     var loc;
     map = new GMap2(document.getElementById("map"));
     map.addControl(new GSmallMapControl());
     map.setCenter(new GLatLng(map_geo_lat,map_geo_lng),13);
     map.setMapType(G_HYBRID_MAP);
     tooltip = document.createElement("div");
     map.getPane(G_MAP_FLOAT_PANE).appendChild(tooltip);
     tooltip.style.visibility="hidden";
   }
 }
 
 
 
 function setMapGeoLatLng(lat,lng)
 {
    map_geo_lat = lat;
    map_geo_lng = lng;  
 }
 
 function importanceOrder (marker,b) 
 {
    return GOverlay.getZIndex(marker.getPoint().lat()) + marker.importance*1000000;
 }

 function createMarker(pPoint,pName,pLink,pIcon,pStyling,pImportance)
 {
     var marker = new GMarker(pPoint,{icon:pIcon,zIndexProcess:importanceOrder});
     marker.importance = pImportance;
     marker.tooltip = '<div class="tooltip" style="'+pStyling+'">'+pName+'</div>';
     marker.url = pLink;
     gmarkers[marker_counter++] = marker;
     map.addOverlay(marker);

     GEvent.addListener(marker, "click", function()
     {
       registerCTR('Map - Search','','0','0','','1','Map');
       window.location.href=marker.url;
     });
     GEvent.addListener(marker,"mouseover", function()
     {
         var obj = document.getElementById('slideshow_button');
         if(obj)
         {
            obj.src = "/images/play.gif";
            // Pause slideshow
            stopSlideShow();
         }
         showTooltip(marker);
     });
     GEvent.addListener(marker,"mouseout", function()
     {
       tooltip.style.visibility="hidden"
     });
     return (marker_counter-1);
 }                       

 function showTooltip(marker)
 {
    tooltip.innerHTML = marker.tooltip;
    var point=map.getCurrentMapType().getProjection().fromLatLngToPixel(map.fromDivPixelToLatLng(new GPoint(0,0),true),map.getZoom());
    var offset=map.getCurrentMapType().getProjection().fromLatLngToPixel(marker.getPoint(),map.getZoom());
    var anchor=marker.getIcon().iconAnchor;
    var width=marker.getIcon().iconSize.width;
    var height = 130;
    var pos = new GControlPosition(G_ANCHOR_TOP_LEFT, new GSize(offset.x - point.x - anchor.x + width, offset.y - point.y -anchor.y -height));
    pos.apply(tooltip);
    tooltip.style.visibility="visible";
 }
 
 
function showOnMap()
{
   startSlideShow(gmarkers); 
}

var currentSlideShowList = '';
var currentSlideShowT = '';
var slideShowIntermission = 4;

function startSlideShow(item_list)
{
   currentSlideShowList = item_list;
   currentSlideShowT = setInterval('nextSlideShowItem();',slideShowIntermission*1000);
}


function resetMapVariables()
{
   stopSlideShow();
   gmarkers = [];
   marker_counter = 0;
   currentSlideShowList = '';
   currentSlideShowT = '';
   slideShowIntermission = 4; 
}


function nextSlideShowItem()
{
   var nextMarker = currentSlideShowList.shift();
   map.panTo(new GLatLng(nextMarker.getPoint().lat()+0.01,nextMarker.getPoint().lng()+0.02));
   showTooltip(nextMarker);
   currentSlideShowList.push(nextMarker); 
}

function stopSlideShow()
{
   if(currentSlideShowT)
   {
      clearInterval(currentSlideShowT);  
   }
}


function toggleShowSearch()
{
   sToggleDiv('show_search_div');
   sToggleDiv('show_search_desc_div');
   sToggleImg('customise_img');
}
 
function sToggleDiv($WhichDiv) {
   if (document.getElementById($WhichDiv).style.display == "none") {
      document.getElementById($WhichDiv).style.display = "block";
   } else {
      document.getElementById($WhichDiv).style.display = "none";
   }
}

function sToggleImg($WhichImg) {
   if (document.getElementById($WhichImg).src.indexOf("_up_") == -1) {
      document.getElementById($WhichImg).src = '/images/shortlist_move_up_s.png';
   } else {
      document.getElementById($WhichImg).src = '/images/shortlist_move_down_s.png';  
   }
}




function updateSearchBoxFormCheckout()
{
   var sd = document.getElementById("search_from_day").value;  
   var sm = document.getElementById("search_from_month").value;
   var sy = document.getElementById("search_from_year").value;
   var fd = document.getElementById("search_to_day").value;
   var fm = document.getElementById("search_to_month").value;
   var fy = document.getElementById("search_to_year").value;
   var sdate = new Date();
   var fdate = new Date();
   sdate.setDate(sd);
   sdate.setMonth(sm-1);
   sdate.setFullYear(sy);
   fdate.setDate(fd);
   fdate.setMonth(fm-1);
   fdate.setFullYear(fy);
   var _sdate = Date.UTC(sy,sm-1,sd,0,0,0,0);
   var _fdate = Date.UTC(fy,fm-1,fd,0,0,0,0); 
   if(_fdate < _sdate)
   {
      var nfdate = sdate;
      nfdate.setDate(sdate.getDate()+7);
      document.getElementById("search_to_month").value = nfdate.getMonth()+1;
      document.getElementById("search_to_year").value = nfdate.getFullYear();
      adjustDays('search_to_month','search_to_day','search_to_year');
      document.getElementById("search_to_day").value = nfdate.getDate();
   }
}
    
function search_box_formSelectDateCheckIn(d,m,y)
{
    // set dates to flexible
    var val = getSearchFlexibilityValue();
    if(val == 'any')
    {
       setSearchFlexibilityValue('exact');
       enableSearchBoxFormDates();
    }
    
   from_day_obj = document.getElementById('search_from_day');
   from_month_obj = document.getElementById('search_from_month');
   from_year_obj = document.getElementById('search_from_year');
   to_day_obj = document.getElementById('search_to_day');
   to_month_obj = document.getElementById('search_to_month');
   to_year_obj = document.getElementById('search_to_year');
      
    from_day_obj.value = d;
    from_month_obj.value = m;   
    from_year_obj.value = y;       
    _closeCalendar();
    _setSearchBoxFormDate(d,m,y,'checkin');
    
    var fromDate = new Date();
    var toDate = new Date();
   fromDate.setFullYear(y,m-1,d); 
   toDate.setFullYear(to_year_obj.value,to_month_obj.value-1,to_day_obj.value); 
   
    // if to date before from date, set to date = from date + 1 week
    if(toDate < fromDate)
    {
      toDate.setFullYear(y,m-1,d);  
      toDate.setDate(toDate.getDate()+7);
       _setSearchBoxFormDate(toDate.getDate(),toDate.getMonth()+1,toDate.getFullYear(),'checkout');
    }
    
    _updateCurrentSelection();     
}

function getSearchFlexibilityValue()
{
  var val = '';
  for(var i = 0; i < document.forms['search_box_form'].search_flexibility_rb.length; i++)
  {
     if(document.forms['search_box_form'].search_flexibility_rb[i].checked)
     {
        val = document.forms['search_box_form'].search_flexibility_rb[i].value;
     }    
  }  
  return val; 
}

function setSearchFlexibilityValue(val)
{
  for(var i = 0; i < document.forms['search_box_form'].search_flexibility_rb.length; i++)
  {
     if(document.forms['search_box_form'].search_flexibility_rb[i].value == val)
     {
        if(!document.forms['search_box_form'].search_flexibility_rb[i].checked)
        {
            _useOption('search_flexibility',val,true); 
        }
     }    
  }  
}

function enableSearchBoxFormDates()
{
  var val = getSearchFlexibilityValue();
  if(val == 'any')
  {
     document.getElementById('search_from_day').disabled = true;
     document.getElementById('search_from_month').disabled = true; 
     document.getElementById('search_from_year').disabled = true; 
     document.getElementById('search_to_day').disabled = true; 
     document.getElementById('search_to_month').disabled = true; 
     document.getElementById('search_to_year').disabled = true; 
     positionSearchBoxFormScreenDiv();
  }
  else
  {
     document.getElementById('search_from_day').disabled = false;
     document.getElementById('search_from_month').disabled = false; 
     document.getElementById('search_from_year').disabled = false; 
     document.getElementById('search_to_day').disabled = false; 
     document.getElementById('search_to_month').disabled = false; 
     document.getElementById('search_to_year').disabled = false; 
     removeSearchBoxFormScreenDiv(); 
  }  
}

function handleSearchBoxFormScreenClick()
{
    var val = getSearchFlexibilityValue();
    if(val == 'any')
    {
       setSearchFlexibilityValue('exact');
       enableSearchBoxFormDates();
    }
}

function removeSearchBoxFormScreenDiv()
{
   if(document.getElementById('search_box_form_click_screen_div'))
   {
      document.getElementById('search_box_form_click_screen_div').style.left = '-300px';    
   }
}

function positionSearchBoxFormScreenDiv()
{
   if(document.getElementById('search_box_form_click_screen_div'))
   {
      _P7_Snap('search_box_form_calendar_checkin_img','search_box_form_click_screen_div',-155,-30);
   }
}

function search_box_formSelectDateCheckOut(d,m,y)
{
    // set dates to flexible
    var val = getSearchFlexibilityValue();
    if(val == 'any')
    {
       setSearchFlexibilityValue('exact');
       enableSearchBoxFormDates();
    }
    
    document.getElementById('search_to_day').value = d;
    document.getElementById('search_to_month').value = m;   
    document.getElementById('search_to_year').value = y;       
    _closeCalendar();
    _setSearchBoxFormDate(d,m,y,'checkout');
    
    _updateCurrentSelection();     
}    

function _setSearchBoxFormDate(d,m,y,type)
{
   var year_target = (type == 'checkin') ? 'search_from_year' : 'search_to_year';
   var month_target = (type == 'checkin') ? 'search_from_month' : 'search_to_month'; 
   var day_target = (type == 'checkin') ? 'search_from_day' : 'search_to_day'; 
   year_target_obj = document.getElementById(year_target);
   month_target_obj = document.getElementById(month_target);
   day_target_obj = document.getElementById(day_target);
   
   var year_is_valid = false;
   for(i = 0; i < year_target_obj.options.length; i++)
   {
      if(year_target_obj.options[i].value == y)
      {
         year_is_valid = true;
      }
   }
   if(year_is_valid)
   {
      year_target_obj.value = y;
      month_target_obj.value = m;
      adjustDays(month_target,day_target,year_target);
      day_target_obj.value = d;
   }
   else
   {
      alert("Date cannot be selected as it is too far in the future");
      return;
   }
}    

function _resetArea(region,from_slider,no_search)
{
   var obj = document.getElementById('search_region_'+region+'_div');
   var els = obj.getElementsByTagName('input');
   for(var i = 0; i < els.length; i++)
   {
      if(els[i].checked)
      {
         _useOption('area',els[i].value,true,from_slider,no_search);   
      }    
   }
}  

function _resetRegion(country,from_slider,no_search)
{
   var obj = document.getElementById('search_country_'+country+'_div');
   var els = obj.getElementsByTagName('input');
   for(var i = 0; i < els.length; i++)
   {
      if(els[i].checked)
      {
         if(els[i].id.indexOf("area") == -1)
         {
            _useOption('region',els[i].value,true,from_slider,no_search);
         }
      }    
   }
}    

function VertScaleLocationDiv($WhichDiv, $EndHeight) 
{
   var $StartHeight = parseInt(document.getElementById($WhichDiv).offsetHeight);
   for( var i = 0 ; i <= 50 ; i++ ) 
   {
	     (function(h)
	     {
	        setTimeout(function() { setHeight($WhichDiv, h); } , 8 * i);
		 })(($StartHeight - ((($StartHeight - $EndHeight) / 50) * (i-1))));          
   }
}
    
var v_scale_orig = 0;

function setLocationDivVScaleStart()
{
   v_scale_orig = document.getElementById('master_areas_div').offsetHeight;      
}

function _useOption(search_by,value,set_value,from_slider,no_search)
{
   // SET THE VALUE
   if(set_value == true) 
   {
      document.getElementById(search_by+'_rb_'+value).checked = !document.getElementById(search_by+'_rb_'+value).checked;    
   }
   document.getElementById('option_'+search_by+'_'+value+'_link').className = (document.getElementById(search_by+'_rb_'+value).checked) ? 'use_search_option_selected' : 'use_search_option_normal';
   
   if(search_by == 'country' || search_by == 'region')
   {
       
       if(search_by == 'country')
       {
          bMasterAreasChecked = false;
          var len = (typeof document.forms['search_box_form'].country_rb.length != 'undefined') ? document.forms['search_box_form'].country_rb.length : 1;
          for(var i = 0; i < len; i++)
          {
             var obj = (len == 1) ? document.forms['search_box_form'].country_rb : document.forms['search_box_form'].country_rb[i];
             if(obj.checked)
             {
                bMasterAreasChecked = true;    
             }
          }
          
          if(bMasterAreasChecked)
          {
             if(document.getElementById('master_areas_div').className = 'auto_mode')
             {
                VertScaleLocationDiv('master_areas_div',200);  
                setTimeout(function() { document.getElementById('master_areas_div').className = 'fixed_mode'; },51*8);
             }
          }
          else
          {
             if(document.getElementById('master_areas_div').className == 'fixed_mode')
             {
                VertScaleLocationDiv('master_areas_div',v_scale_orig);
                setTimeout("document.getElementById('master_areas_div').className = 'auto_mode';",51*8);
             }
          }
       }
       
       // SHOW/HIDE THE SUB-DIV
       document.getElementById('search_'+search_by+'_'+value+'_div').style.display = (document.getElementById(search_by+'_rb_'+value).checked) ? '' : 'none';
       
       // If country, enable region, disable area
       enableOption('region',true);
       enableOption('area',false);
       
       if(document.getElementById('search_'+search_by+'_'+value+'_div').style.display == 'none')
       {
          if(search_by == 'region') 
          {
              _resetArea(value,from_slider,no_search);
          }
          else if(search_by == 'country')
          {
             _resetRegion(value,from_slider,no_search);
          }
       }
   }
   else if(search_by == 'bedrooms' || search_by == 'sleeps' || search_by == 'distance_to_coast' || search_by == 'price' || search_by == 'search_flexibility')
   {
      var els = document.getElementById('search_options_'+search_by+'_div').getElementsByTagName('input');
      for(var i = 0; i < els.length; i++)
      {
         if(!els[i].checked)
         {
            document.getElementById('option_'+els[i].id.replace(/_rb_/,'_')+'_link').className = 'use_search_option_normal';          
         }
      } 
      
      // IF NOT FROM SLIDER, DON'T ATTEMPT TO UPDATE THE SLIDER ITSELF
      if(search_by == 'price' && from_slider != true)
      {
         // OPTION IS CHECKED AND IT'S NUMERIC, MOVE THE SLIDER BUT DON'T UPDATE THE UI
         if((document.getElementById(search_by+'_rb_'+value).checked))
         {
             if(value != 'NULL' && value != 'CUST')
             {
                update_ui = false;
                movePriceSlider(price_range[0],value);    
             } 
             else
             {
                // OVERRIDE THE UI
                if(value == 'NULL')
                {
                   update_ui = false; 
                   slider.setValues(0,range);                 
                   info.innerHTML = "Any price per night";
                   demo_bg.title  = "Any price per night";
                }
                else if(value == 'CUST')
                {
                   snap_to_option = false;
                   update_ui = true;
                   updateUI();
                }           
             }
         }
         else
         {
            if(value != 'NULL')
            {
                _useOption('price','NULL',true);
            }
         }
      }
   }
   
   if(search_by == 'region' || search_by == 'area')
   {
      var bCountryChecked = false;    
      var len = (typeof document.forms['search_box_form'].country_rb.length != 'undefined') ? document.forms['search_box_form'].country_rb.length : 1;
      for(var i = 0; i < len; i++)
      {
         // IF THIS COUNTRY CHECKED
         var obj = (len == 1) ? document.forms['search_box_form'].country_rb : document.forms['search_box_form'].country_rb[i];
         if(obj.checked)
         {
            bCountryChecked = true;
            var bRegionChecked = false;  
            
            var region_els = document.getElementById('search_country_'+obj.value+'_div').getElementsByTagName('input');
            for(var j = 0; j < region_els.length; j++)
            {
               if(region_els[j].id.indexOf('region_rb') == -1) continue;
               
               // IF THIS REGION CHECKED
               if(region_els[j].checked)
               {
                  bRegionChecked = true; 
                  var bAreaChecked = false;  
                  var area_els = document.getElementById('search_region_'+region_els[j].value+'_div').getElementsByTagName('input');
                  for(var k = 0; k < area_els.length; k++)
                  {    
                       // IF THIS AREA CHECKED
                       if(area_els[k].checked)
                       {
                          bAreaChecked = true;    
                       }
                  }
                  document.getElementById('option_'+region_els[j].id.replace(/_rb_/,'_')+'_link').className = (bAreaChecked) ? 'use_search_option_sub_selected' : 'use_search_option_selected';                    
               }
               else
               {
                  document.getElementById('option_'+region_els[j].id.replace(/_rb_/,'_')+'_link').className = 'use_search_option_normal'; 
               }   
            }
            document.getElementById('option_'+obj.id.replace(/_rb_/,'_')+'_link').className = (bRegionChecked) ? 'use_search_option_sub_selected' : 'use_search_option_selected';                    
         }
         else
         {
            document.getElementById('option_'+obj.id.replace(/_rb_/,'_')+'_link').className = 'use_search_option_normal'; 
         }               
      }    
   }
   
   if(search_by == 'search_flexibility')
   {
      enableSearchBoxFormDates();
   }
   
   if(no_search != true)
   {
      _updateCurrentSelection();
   }
}

var qs = '';
function _updateCurrentSelection(no_reset_page)
{
    // SET LOADING VARIABLES
    setLoading('current_selection',true);
    setLoading('search_results',true);
    var scrollY = (getScrollXY()[1]+50);
    var minY = findPosY(document.getElementById('refine_search_results_count_div'));
    if(scrollY < minY+100) scrollY = minY+100;
    document.getElementById('search_results_loading_div').style.top = scrollY+'px';    
    
    if(no_reset_page != true)
    {
       // Reset the page number because results will be different
       document.getElementById('results_option_search_page').value = 1;
    }
    
    qs = 'q='+_getQ();
    var url = '/ajax/_search_get_current_selection_text.ajax.php?verbose=1&'+qs;
    ajaxRequest(url, true, '_updateCurrentSelectionResponse');
}

function _setPage(page)
{
   // SET SEARCH RESULTS LOADING
   setLoading('search_results',true);
   var scrollY = (getScrollXY()[1]+50);
   var minY = findPosY(document.getElementById('refine_search_results_count_div'));
   if(scrollY < minY+100) scrollY = minY+100;
   document.getElementById('search_results_loading_div').style.top = scrollY+'px';   
   
   document.getElementById('results_option_search_page').value = page;
   qs = 'q='+_getQ();
   _doSearch();
   var idx = this.location.href.indexOf("#");
   this.location.href = (idx==-1) ? this.location.href+"#search" : this.location.href.substring(0,idx)+"#search";
   window.location.href="#q="+qs;
}


function _updateCurrentSelectionResponse()
{
   if (xmlHttp.readyState==4)
   {
      rc = xmlHttp.responseText;
      loadResultsCountFromSource(rc);
      var current_selection_div = document.getElementById('current_selection_div');
      current_selection_div.innerHTML = rc;
      setLoading('current_selection',false);
      _doSearch();
   }
}

function loadResultsCountFromSource(rc)
{
   var total_results = rc.substring(rc.indexOf('RES=')+4,rc.indexOf('.',rc.indexOf('RES=')+4));
   if(total_results == 0) total_results = 'no holiday rentals';
   else if(total_results == 1) total_results = '1 holiday rental';
   else total_results = total_results + ' holiday rentals';
   document.getElementById('refine_search_results_count_div').innerHTML = total_results;   
}

   function _resetAllPriceOptions()
   {
      var els = document.getElementById('search_options_price_div').getElementsByTagName('input');
      for(var i = 0; i < els.length; i++)
      {
         if(els[i].checked)
         {
            els[i].checked = false;
            document.getElementById('option_'+els[i].id.replace(/_rb_/,'_')+'_link').className = 'use_search_option_normal';          
         }
      }   
   }
   
   
function _decodeQ(bNoAddToHistory,bInitialLoad)
{
   var loc = this.location.href;  
   var idx = loc.indexOf("#q=");
   // IF 'Q' VARIABLE IS PRESENT
   qSource = '';
   if(idx != -1) qSource = 'url';
   var blankHash = (loc.indexOf("#") == loc.length - 1) ? true : false;
   
   
   
   if(qSource == 'url')
   {
      // WE ALSO HAVE THE OPTION OF LOADING UP THE DEFAULTS, WE DO THAT IF THERE'S NO Q AND IT'S NOT THE INITIAL LOAD
      var q_parts = base64_decode(loc.substring(idx+3)).split('_');
   }
   else
   {  
      // DEFAULT SEARCH
      if(server_q != '')
      {
         q_parts = base64_decode(server_q).split('_');
         qSource = (!blankHash) ? 'server' : 'default';
	  }
      else
      {
          q_parts = ('_NULL__0_0_NULL_0,NULL___any__20_no_default_DESC_1').split('_');
          qSource = 'default';
      }
   }
   
      
      
      var vars = [ 'area_ids',
                   'distance_to_coast',
                   'property_type',
                   'bedrooms',
                   'sleeps',
                   'price',
                   'min_max_price',
                   'property_features',
                   'location_features',
                   'search_flexibility',
                   'dates',
                   'results_to_display',
                   'display_map',
                   'sort_by',
                   'sort_type',
                   'search_page' ];
                   
      // VALIDATE
      if(q_parts.length != vars.length) 
      {
         return;
	  }
      
      for(var i = 0; i < vars.length; i++)
      {
          
         var val = q_parts[i];
         
         // LOCATION
         if(vars[i] == 'area_ids')
         {
            val = val.split(',');
            var els = document.getElementById('master_areas_div').getElementsByTagName('input');    
            
            // RESET ALL
            for(var k = 0; k < els.length; k++)
            {
               if(els[k].checked)
               {
                  var el_part = els[k].id.split('_');    
                  _useOption(el_part[0],el_part[2],true,false,true); // SET VALUE, NOT FROM SLIDER, DON'T SEARCH (MORE VALUES TO SET)
			   }
		    }
		    
            for(var j = 0; j < val.length; j++)
            {
                if(!isNaN(val[j]))
                {
                   for(var k = 0; k < els.length; k++)
                   {
                      if(els[k].value == val[j])
                      {
                         var el_part = els[k].id.split('_');
                         if(el_part.length == 3)
                         {
                            // ENABLE THE PARENT OPTIONS FIRST
                            if(els[k].parentNode.id.indexOf('country') != -1)
                            {
                               var parent_el_part = els[k].parentNode.id.split('_');
                               if(parent_el_part.length == 4)
                               {
                                  if(!document.getElementById('country_rb_'+parent_el_part[2]).checked)
                                  {   
                                     _useOption(parent_el_part[1],parent_el_part[2],true,false,true);    
								  }
                               }
                            }
                            else if(els[k].parentNode.id.indexOf('region') != -1)
                            {
                               var parent_el_part = els[k].parentNode.id.split('_');
                               if(parent_el_part.length == 4)
                               {
                                   var parent_parent_el_part = els[k].parentNode.parentNode.id.split('_');
                                   if(parent_parent_el_part.length == 4)
                                   {
                                      if(!document.getElementById('country_rb_'+parent_parent_el_part[2]).checked) 
                                      {    
                                         _useOption(parent_parent_el_part[1],parent_parent_el_part[2],true,false,true);    
									  }
                                   }
                                   if(!document.getElementById('region_rb_'+parent_el_part[2]).checked) 
                                   {               
                                      _useOption(parent_el_part[1],parent_el_part[2],true,false,true);    
								   }
                               }
                            }
                            _useOption(el_part[0],el_part[2],true,false,true); // SET VALUE, NOT FROM SLIDER, DON'T SEARCH (MORE VALUES TO SET)
                         }
                      }    
                   }
                }
            }
         }
         
         
         // DISTANCE TO COAST, BEDROOMS, SLEEPS
         if(vars[i] == 'distance_to_coast' ||
            vars[i] == 'bedrooms' ||
            vars[i] == 'sleeps' ||
            vars[i] == 'search_flexibility')
         {    
            if(val != '')
            {
               if(!document.getElementById(vars[i]+'_rb_'+val).checked)
               {
                  _useOption(vars[i],val,true,false,true);
			   }
            }
         }
         
         
         // PROPERTY TYPE, FEATURES
         if(vars[i] == 'property_type' ||
            vars[i] == 'location_features' ||
            vars[i] == 'property_features')
         {
            val = val.split(',');
            for(var j = 0; j < val.length; j++)   
            {
               if(val[j] != '' && !isNaN(val[j]))
               {
                  if(!document.getElementById(vars[i]+'_rb_'+val[j]).checked)
                  {               
                     _useOption(vars[i],val[j],true,false,true);
				  }
			   }
            } 
         }
         
         // PRICE
         if(vars[i] == 'min_max_price')
         {
            // IF ANY PRICE IS SPECIFIED
            if(q_parts[5] == 'NULL' || q_parts[5] == '')
            {
               if(!document.getElementById('price_rb_NULL').checked)
               {            
                  _useOption('price','NULL',true,false,true);    
			   }
            }
            else
            {
               val = val.split(',');
               if(val.length == 2)
               {
                  val[0] = parseInt(val[0]);
                  val[1] = parseInt(val[1]);
                  
                 // IF SLID TO ONE OF THE PRE-DEFINED OPTIONS
                 if(Math.round(val[0]) == price_range[0] && 
                   (Math.round(val[1]) == 100 ||
                    Math.round(val[1]) == 200 ||
                    Math.round(val[1]) == 300 ||
                    Math.round(val[1]) == 500 ||
                    Math.round(val[1]) == 1000))
                 {
                   if(!document.getElementById('price_rb_'+val[1]).checked)
                   {   
                       _useOption('price',val[1],true,false,true);       
				   }
                 }
                 else
                 {
                    if(!document.getElementById('price_rb_CUST').checked)
                    {
                       _useOption('price','CUST',true,false,true);    
                    }
                 }                  
                 movePriceSlider(parseInt(val[0]),parseInt(val[1]));
                  
               }
            }
         }
         
         // DATES
         if(vars[i] == 'dates')
         {
            var flexibility = q_parts[9];
            setSearchFlexibilityValue(flexibility);
            enableSearchBoxFormDates();            
            if(flexibility != 'any')
            {
               var val = val.split(',');
               var from_date = new Date();
               var to_date = new Date();
               from_date.setTime(parseFloat(val[0])*1000);
               to_date.setTime(parseFloat(val[1])*1000);
               _setSearchBoxFormDate(from_date.getDate(),parseInt(from_date.getMonth())+1,from_date.getFullYear(),'checkin');     
               _setSearchBoxFormDate(to_date.getDate(),parseInt(to_date.getMonth())+1,to_date.getFullYear(),'checkout');
            }
         }
         
         
         
         // RESULTS OPTIONS
         if(vars[i] == 'results_to_display' ||
            vars[i] == 'display_map' ||
            vars[i] == 'sort_by' ||
            vars[i] == 'sort_type' ||
            vars[i] == 'search_page')
         {
            document.getElementById('results_option_'+vars[i]).value = val;   
         }
      }
      
      if(qSource == 'url' || qSource == 'default')
      {
         g_no_add_to_history = bNoAddToHistory;
         _updateCurrentSelection(true);
      }
      if(bInitialLoad)
      {
         // IF INITIAL LOAD, AFTER SETTING ALL OF THE VALUES, RE-SUBSCRIBE TO CHANGE EVENTS
         // SUBSCRIBE TO THE DUAL THUMB SLIDER'S CHANGE AND READY EVENTS TO
         // REPORT THE STATE.       
         slider.subscribe('change', updateUI);
      }
}

function sliderIsReady()
{
   _decodeQ(true,true);
}
   
function _getQ()
{
    var qs = '';

    var len = (typeof document.forms['search_box_form'].country_rb.length != 'undefined') ? document.forms['search_box_form'].country_rb.length : 1;
    for(var i = 0; i < len; i++)
    {
      // IF THIS COUNTRY CHECKED
     var obj = (len == 1) ? document.forms['search_box_form'].country_rb : document.forms['search_box_form'].country_rb[i];
     if(obj.checked)
     {
        bCountryChecked = true;
        var bRegionChecked = false;  
        
        var region_els = document.getElementById('search_country_'+obj.value+'_div').getElementsByTagName('input');
        for(var j = 0; j < region_els.length; j++)
        {
           if(region_els[j].id.indexOf('region_rb') == -1) continue;
           
           // IF THIS REGION CHECKED
           if(region_els[j].checked)
           {
              bRegionChecked = true; 
              var bAreaChecked = false;  
              var area_els = document.getElementById('search_region_'+region_els[j].value+'_div').getElementsByTagName('input');
              for(var k = 0; k < area_els.length; k++)
              {    
                   // IF THIS AREA CHECKED
                   if(area_els[k].checked)
                   {
                      bAreaChecked = true;
                      
                      // ADD AREA
                      qs += area_els[k].value+',';   
                   }
              }
              
              if(!bAreaChecked) qs += region_els[j].value+',';
           }
        }
        if(!bRegionChecked) qs += obj.value+',';
     }
    }   
    
    if(qs.length > 0) qs = qs.substring(0,qs.length-1);
    qs += '_' + getRadioCheckboxValue(document.forms['search_box_form'].distance_to_coast_rb);
    qs += '_' + getRadioCheckboxValue(document.forms['search_box_form'].property_type_rb);  
    qs += '_' + getRadioCheckboxValue(document.forms['search_box_form'].bedrooms_rb);       
    qs += '_' + getRadioCheckboxValue(document.forms['search_box_form'].sleeps_rb);     
    qs += '_' + getRadioCheckboxValue(document.forms['search_box_form'].price_rb);    
    qs += '_' + document.getElementById('min_price_rb').value+','+document.getElementById('max_price_rb').value;
    qs += '_' + getRadioCheckboxValue(document.forms['search_box_form'].property_features_rb);       
    qs += '_' + getRadioCheckboxValue(document.forms['search_box_form'].location_features_rb); 
    var search_flexibility_val = getSearchFlexibilityValue();
    qs += '_' +  search_flexibility_val;
    if(search_flexibility_val != 'any')
    {
       var fd = Date.UTC(parseInt(document.getElementById('search_from_year').value),parseInt(document.getElementById('search_from_month').value)-1,parseInt(document.getElementById('search_from_day').value))/1000;  
       var td = Date.UTC(parseInt(document.getElementById('search_to_year').value),parseInt(document.getElementById('search_to_month').value)-1,parseInt(document.getElementById('search_to_day').value))/1000;
       if(td > fd)
       {
          qs += '_' + fd + ',' + td;    
       }
       else
       {
          qs += '_';   
       }
    }
    else
    {
       qs += '_';    
    }
    var vars = [];
    vars[0] = 'results_to_display';
    vars[1] = 'display_map';
    vars[2] = 'sort_by';
    vars[3] = 'sort_type';
    vars[4] = 'search_page';
    for(var i = 0; i < vars.length; i++)
    {
        var val = document.getElementById('results_option_'+vars[i]).value;
        qs += '_' + val;
    }
    return base64_encode(qs);
}   

function getRadioCheckboxValue(el)
{
   var vals = '';
   for(var i = 0; i < el.length; i++)
   {
      if (el[i].checked)
      {
         vals += el[i].value+',';
      }
   }
   if(vals.length > 0) vals = vals.substring(0,vals.length-1);
   return vals;
}

function getScrollXY() 
{
  var scrOfX = 0, scrOfY = 0;
  if( typeof( window.pageYOffset ) == 'number' ) {
    //Netscape compliant
    scrOfY = window.pageYOffset;
    scrOfX = window.pageXOffset;
  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
    //DOM compliant
    scrOfY = document.body.scrollTop;
    scrOfX = document.body.scrollLeft;
  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
    //IE6 standards compliant mode
    scrOfY = document.documentElement.scrollTop;
    scrOfX = document.documentElement.scrollLeft;
  }
  return [ scrOfX, scrOfY ];
}

function findPosY(obj)
{
 var curtop = 0;
 if(obj.offsetParent)
     while(1)
     {
       curtop += obj.offsetTop;
       if(!obj.offsetParent)
         break;
       obj = obj.offsetParent;
     }
 else if(obj.y)
     curtop += obj.y;
 return curtop;
}

function _doSearch()
{
    if(g_no_add_to_history != true)
    {
        addHistoryEvent("#"+qs,null);
    }
    else
    {
       // Reset variable so events continue to be added to the history unless explicitly stated otherwise
       g_no_add_to_history = false;
    }
    unloadMap();
    // APPEND SHORTLIST SESSION
    qs += "&shortlist_session="+server_shortlist_session+"&post_load_images="+server_post_load_images;  
    var url = '/ajax/_search_get_results.ajax.php?'+qs;
    ajaxRequest(url, true, 'doSearchResponse');
}
