var searchMoreOptions = {};
var searchConfig      = {};

searchMoreOptions["scuResort"] = {
  description: "resort",
  expandCollapse: "expandCollapse1",
  expandCollapseDiv: "scuResortSelect",
  isExpanded: false
};

searchMoreOptions["scuAccommodation"] = {
  description: "accommodation type",
  expandCollapse: "expandCollapse2",
  expandCollapseDiv: "scuAccommodationSelect",
  isExpanded: false
};

searchMoreOptions["scuRating"] = {
  description: "rating",
  expandCollapse: "expandCollapse3",
  expandCollapseDiv: "scuRatingSelect",
  isExpanded: false
};

searchMoreOptions["scuFeatures"] = {
  description: "features",
  expandCollapse: "expandCollapse4",
  expandCollapseDiv: "scuFeaturesOptions",
  isExpanded: false
};

var throbFadePanelNotAllowed = false;

searchConfig.application                    = 'fcfalcon';
searchConfig.updateSearchPanelAction        = '/' + searchConfig.application + '/page/common/search/searchpanelupdate.page';
searchConfig.updateRefinedSearchPanelAction = '/' + searchConfig.application + '/page/common/search/refinedsearchpanelupdate.page';
searchConfig.isDayTripApplicable            = false;
searchConfig.showRooms                      = false;
searchConfig.showAccommodationType          = true;
searchConfig.showRating                     = true;
searchConfig.showHolidayFeatures            = true;
searchConfig.isRefinedSearchPanel           = false;
searchConfig.maxNumberOfPassengers          = 9;
searchConfig.maxNumberOfChildren            = 8;
searchConfig.maxNumberOfRooms               = 5;

function updateSearchPanel(action)
{
  var isRefinedSearchPanel = searchConfig.isRefinedSearchPanel;
  var updateAction         = searchConfig.updateSearchPanelAction;

  if( isRefinedSearchPanel )
  {
    updateAction = searchConfig.updateRefinedSearchPanelAction;
  }

  searchPanelRequester(action, updateAction, isRefinedSearchPanel);
}

function updateRefinedSearchPanel(action)
{
  searchPanelRequester(action, searchConfig.updateRefinedSearchPanelAction, true);
}

function setIsDayTripApplicable( isApplicable )
{
  searchConfig.isDayTripApplicable = isApplicable;
}

function setSearchPanelApplication( application )
{
  searchConfig.application = application;
}

function setSearchPanelIsRefined( isRefined )
{
  searchConfig.isRefinedSearchPanel = isRefined;
}

// Clear all options in Selection
function clearDropDown(id, text, flag)
{
  var select = $(id);

  if ( select.options != null )
  {
    select.options.length = 0;
  }

  if ( text )
  {
    select.disabled = true;
  }

  if( flag == "true" )
  {
    addOption(select, "Loading...", '');
  }
  else
  {
    addOption(select, "Loading...", '', true, true);
  }
}

/*
 * Reset the identified drop down to the first value in the list.
 */
function resetSearchPanelDropDown( dropDown )
{
  var dropDown = $( dropDown );

  if( dropDown )
  {
    dropDown.selectedIndex = 0;
  }
}

// Add an option to a <select> element
function addOption(select, text, value, defaultSelected, selected)
{
   var option = (select.ownerDocument || select.document).createElement('option');
   option.text = text;
   option.value = value;
   option.defaultSelected = !!defaultSelected;
   option.selected = !!selected;

   if (select.options != null)
   {
      select.options[select.length] = option;
   }

   if (!!selected && select.type == 'select-one')
   {
      select.selectedIndex = select.length - 1;
   }
}

function validateSearchPanelSelect(id, value, errorMessages)
{
  var select = $(id + "Select");

  if ( select )
  {
    if ( value != "" && value != select[select.selectedIndex].value )
    {
      var scuAirportSelect = $('scuAirportSelect');

      if( scuAirportSelect[scuAirportSelect.selectedIndex].value == "000" )
      {
        scuAirportSelect.disabled = true;

        var scuResortSelect = $('scuResortSelect');

        if ( scuResortSelect != null )
        {
           scuResortSelect.disabled = true;
        }
      }
      else
      {
        if( value != "000" )
        {
          Element.addClassName( id, "errorState" );
          showElement( id + "ErrorMessage" );

          if( id == "scuResort" )
          {
            //this needs to execute only when an error is found on scuResort
            searchMoreOptionExpand(id);
          }

          $(id + "ErrorMessage").innerHTML = errorMessages.prev_selection_notavailable;
          throbFadePanel(id + "Fade");
        }
      }
    }
    else if ( Element.hasClassName( id, "errorState" ) )
    {
      Element.removeClassName( id, "errorState" );
      $(id + "ErrorMessage").innerHTML = "";
      hideElement( id + "ErrorMessage" );
    }
  }
}

function containerUpdater(container, url, evalJs)
{
  if (!Ajax.Updater) return;
  if (!evalJs) evalJs = false;

  new Ajax.Updater(container,url,{method:'post',evalScripts:evalJs,
  onSuccess: function(transport) {
      checkResponseForError(transport.responseText);
  },
  onFailure: onFailureSearchPanel
  });
  return;
}

// This checks the response for specific text errorPageText.  If present the document will reload the
// location, essentially reloading the page.
function checkResponseForError(response)
{
  var error = false;
   // Lets check to see if we have any errorText in the meta tag.
   if (response.indexOf('errorPageText') != -1)
   {
      error = true;
      // We want to reload the page so that we can see the proper error page.
      document.location.reload();
   }

   return error;
}

//
//Search Panel Updater Ajax function
//
// @param  action  Is the type of action we are performing
// @param  actionURL  Is the url we will be using to perform the AJAX call.  (The server side component)
// @param  isRefinedPanel  Is a flag that determines if the redefined search panel (AKA, the horizontal search panel)
//
function searchPanelRequester(action, actionURL, isRefinedPanel)
{
   var sUrl = actionURL;

   sUrl += '?' + buildSearchPanelQuery(action, isRefinedPanel);

  new Ajax.Request(sUrl, {
    method: 'post',
    onSuccess: onSuccessSearchPanel,
    onFailure: onFailureSearchPanel
  });
}

function onSuccessSearchPanel(transport)
{
   var searchPanelResponseText = transport.responseText;

   if (checkResponseForError(searchPanelResponseText) == false)
   {
      searchPanelLoader( searchPanelResponseText );
   }
}

function onFailureSearchPanel(transport)
{
   // We want to reload the page so that we can a proper error page.
   document.location.reload();
}

function buildSearchPanelQuery(action, isRefinedPanel)
{
   var sDate            = $('scuDaySelect').value + '/' + $('scuMonthYearSelect').value;
   var sDuarion         = $('scuDurationSelect').value;
   var sDeparture       = $('scuAirportSelect').value;
   var sDestination     = $('scuDestinationSelect').value;
   var sResort          = "";
   var clearDuration    = false;
   var clearAirport     = false;
   var clearDestination = false;
   var clearResort      = false;

   if ($('scuResortSelect') && $('scuResortSelect').value != "undefined"
      && $('scuResortSelect').value != "")
   {
      sResort = $('scuResortSelect').value;
   }
   var queryString = '';

   if (action == 'IsuSelectDate')
   {
     if (isRefinedPanel)
     {
        queryString = 'selectedDate=' + sDate;
        queryString += '&selectedDuration=' + sDuarion;
        queryString += '&selectedResortCode=' + sResort;

        var fcFalcon = $('fcFalcon');

        if( fcFalcon )
        {
          queryString += '&fcFalcon=' + fcFalcon.value;
        }

        if ($('scuAirportChanged').value == "true")
        {
          queryString += '&selDep=' + sDeparture;
        }
        clearDuration = true;
        clearAirport  = true;
     }
     else
     {
        queryString = 'selectedDate=' + sDate;
        queryString += '&selectedDuration=' + sDuarion;

        if ($('scuAirportChanged').value == "true")
        {
          queryString += '&selDep=' + sDeparture;
        }
        if ($('scuDestinationChanged').value == "true")
        {
          queryString += '&selDest=' + sDestination;
        }

        queryString += '&selRes=' + sResort;

        clearDuration    = true;
        clearAirport     = true;
        clearDestination = true;
        clearResort      = true;
      }
   }
    if (action == 'IsuSelectDateOnLoad')
   {
     if (isRefinedPanel)
     {
        queryString = 'selectedDate=' + sDate;
        queryString += '&selectedDuration=' + sDuarion;
        queryString += '&selectedResortCode=' + sResort;
        if ($('scuAirportChanged').value == "true")
        {
          queryString += '&selDep=' + sDeparture;
        }
        clearDuration = true;
        clearAirport  = true;
     }
     else
     {
        queryString = 'selectedDate=' + sDate;
        queryString += '&selectedDuration=' + selectedDurationValue.value;

        if ($('scuAirportChanged').value == "true")
        {
          queryString += '&selDep=' + selectedDepartureAirportValue.value;
        }
        if ($('scuDestinationChanged').value == "true")
        {
          queryString += '&selDest=' + selectedDestination.value;
        }

       queryString += '&selRes=' + selectedResort.value;

        clearDuration    = true;
        clearAirport     = true;
        clearDestination = true;
        clearResort      = true;
      }
   }

   else if (action == 'IsuSelectDuration' && $('durationISULoad'))
   {
      $('scuDurationChanged').value = "true";
      $('selectedDurationValue').value = sDuarion;
      queryString = 'selectedDate=' + sDate;
      queryString += '&selectedDuration=' +sDuarion ;
      queryString += '&selDep=' + sDeparture;

      if ($('scuDestinationChanged').value == "true")
      {
        queryString += '&selDest=' + sDestination;
      }

      queryString += '&selRes=' + sResort;

      clearAirport     = true;
      clearDestination = true;
      clearResort      = true;
   }
   else if (action == 'IsuSelectDepart')
   {
      $('scuAirportChanged').value = "true";
      $('selectedDepartureAirport').value = sDeparture;

      if (sDuarion == '1')
      {
         queryString = 'selectedDate=' + sDate;
         queryString += '&selDep=' + sDeparture;
      }
      else
      {
        queryString = 'selDate=' + sDate;
        queryString += '&selectedDepartureAirport=' + sDeparture;
      }

      queryString += '&selectedDuration=' + sDuarion;

      if ($('scuDestinationChanged').value == "true")
      {
        queryString += '&selDest=' + sDestination;
      }
      queryString += '&selRes=' + sResort;

      clearDestination = true;
      clearResort      = true;
   }
    else if (action == 'IsuSelectload')
   {
      $('scuAirportChanged').value = "true";
    //  $('selectedDepartureAirport').value = sDeparture;


      if (selectedDepartureAirportValue .value == '1')
      {
         queryString = 'selectedDate=' + sDate;
         queryString += '&selDep=' + selectedDepartureAirportValue .value;
      }
      else
      {
        queryString = 'selDate=' + sDate;
        queryString += '&selectedDepartureAirport=' + selectedDepartureAirportValue .value;
      }

      queryString += '&selectedDuration=' + selectedDurationValue.value;

      if ($('scuDestinationChanged').value == "true")
      {
        queryString += '&selDest=' + selectedDestination.value;
      }
     if($('scuDurationChanged').value == "true")
      {
        queryString += '&selectedDuration=' + selectedDurationValue.value;
      }
      //queryString += '&selRes=' + sResort;
      if(selectedResort.value)
      {
        queryString += '&selRes=' + selectedResort.value;
      }

      clearDestination = true;
      clearResort      = true;
   }

   else if (action == 'IsuSelectDest')
   {
      $('scuDestinationChanged').value = "true";
      $('selectedDestination').value = sDestination;

      if (sDuarion == '1')
      {
        queryString = 'selectedDate=' + sDate;
        queryString += '&selDest=' + sDestination;
      }
      else
      {
        queryString = 'selDate=' + sDate;
        queryString += '&selectedDestination=' + sDestination;
      }

      queryString += '&selectedDuration=' + sDuarion;
      queryString += '&selDep=' + sDeparture;
      queryString += '&selRes=' + sResort;

      clearResort = true;
   }

   if ( clearDuration )
   {
      clearDropDown('scuDurationSelect', 'Loading...', 'true');
   }

   if ( clearAirport )
   {
       clearDropDown('scuAirportSelect', 'Loading...', 'true');
   }

   if ( clearDestination )
   {
      clearDropDown('scuDestinationSelect', 'Loading...', 'true');
   }

   if ( clearResort )
   {
      clearDropDown('scuResortSelect', 'Loading...', 'true');
   }

   return queryString;
}

function searchPanelLoader( searchPanelResponseText )
{
  var line = 'beforeEvalScripts';
   try
   {
      $('overlayUpdater').innerHTML = searchPanelResponseText.stripScripts();
      searchPanelResponseText.evalScripts();
      line = 'afterEvalScripts';
      $('overlayUpdater').innerHTML = '';
      postUpdaterProcessing();
      line = 'afterPostUpdaterProcessing';
   }
   catch(ex)
   {
      alert('Search Panel load failed with exception:'+ex.description+'\nname: '+ex.name + '\nmessage:' +
            ex.message + '\nline:' + line);
   }
}

// This function performs post updater processing for the search panel.
function postUpdaterProcessing()
{
  var scuAirportSelect     = $('scuAirportSelect');
  var scuDestinationSelect = $('scuDestinationSelect');
  var scuResortSelect      = $('scuResortSelect');

   if( scuAirportSelect && parseInt(scuAirportSelect.value) == 0 && scuDestinationSelect )
   {
      scuAirportSelect.disabled = true;

      if ( scuDestinationSelect.options != null )
      {
         scuDestinationSelect.options.length = 0;
      }

      addOption( scuDestinationSelect, "No Data Available", '' );
      scuDestinationSelect.disabled =  true;

      if ( scuResortSelect.options != null)
      {
         scuResortSelect.options.length = 0;
      }

      addOption( scuResortSelect, "No Data Available", '' );

      scuResortSelect.disabled =  true;
   }
   else if ( scuDestinationSelect )
   {
      scuDestinationSelect.disabled =  false;
      scuResortSelect.disabled      =  false;
   }

   renderSearchPanel( searchConfig );
}

/*
 * Is the current search panel selection a day trip?
 *
 * @param searchConfig - Holds searchPanel configuration properties.
 *
 * @return true or false
 */
function isDayTrip( searchConfig )
{
  var dayTrip           = false;
  var scuDurationSelect = $( "scuDurationSelect" );

  if( searchConfig.isDayTripApplicable && scuDurationSelect && scuDurationSelect.value == "1" )
  {
    dayTrip = true;
  }

  return dayTrip;
}

/*
 * Renders the search panel options
 *
 * @param searchConfig - - Holds searchPanel configuration properties.
 */
function renderSearchPanel( searchConfig )
{
  var dayTrip = isDayTrip( searchConfig );

  searchConfig.showRooms             = !dayTrip && isShowRoom();
  searchConfig.showAccommodationType = !dayTrip;
  searchConfig.showRating            = !dayTrip;
  searchConfig.showHolidayFeatures   = !dayTrip;

  var scuRoom          = $( "scuRoom" );
  var numberOfRooms    = $( "numberOfRooms" );
  var whosgoingHeading = $( "whosgoingHeading" );
  var roomTextBlock1   = $( "roomTextBlock1" );
  var scuAccommodation = $( "scuAccommodation" );
  var scuRating        = $( "scuRating" );
  var scuFeatures      = $( "scuFeatures" );

  if( scuRoom )
  {
    if( searchConfig.showRooms )
    {
      scuRoom.show();
    }
    else
    {
      scuRoom.hide();

      if( numberOfRooms )
      {
        numberOfRooms.selectedIndex = 0;
      }
    }

    updateRoom();
  }

  if( whosgoingHeading )
  {
    if( searchConfig.showRooms )
    {
      whosgoingHeading.hide();
    }
    else
    {
      whosgoingHeading.show();
    }
  }

  if( roomTextBlock1 )
  {
    if( searchConfig.showRooms )
    {
      roomTextBlock1.show();
    }
    else
    {
      roomTextBlock1.hide();
    }
  }

  if( scuAccommodation )
  {
    if( searchConfig.showAccommodationType )
    {
      scuAccommodation.show();
    }
    else
    {
      scuAccommodation.hide();
      resetSearchPanelDropDown( "scuAccommodationSelect" );
    }
  }

  if( scuRating )
  {
    if( searchConfig.showRating )
    {
      scuRating.show();
    }
    else
    {
      scuRating.hide();
      resetSearchPanelDropDown( "scuRatingSelect" );
    }
  }

  if( scuFeatures )
  {
    if( searchConfig.showHolidayFeatures )
    {
      scuFeatures.show();
    }
    else
    {
      scuFeatures.hide();
      resetAllHolidayFeatures();
    }
  }
}

function configureIsuFeatures(isHolFeaturesVisible)
{
  renderSearchPanel( searchConfig );

  if (isHolFeaturesVisible)
  {
    configureHolidayFeatures();
  }

  var scuWhoChildrenSelect = $("scuWhoChildrenSelect");

  if( scuWhoChildrenSelect )
  {
    var numberOfChildren = scuWhoChildrenSelect.selectedIndex;
    var childAgesBlock   = $("childAgesBlock");

    if( numberOfChildren == 0)
    {
      // hide the whole child ages container
      childAgesBlock.hide();
    }
    else
    {
      // display the whole child ages container
      childAgesBlock.show();

      var childAge = $( "childAge" + (i+1) );

      for( var i = 0; i < searchConfig.maxNumberOfChildren; i++ )
      {
        if( i < numberOfChildren )
        {
          // display number of child age drop downs to match the number of children selected
          childAge.show();
        }
        else
        {
          // hide all other child age blocks
          childAge.hide();
        }
      }
    }
  }
}

function resetAllHolidayFeatures()
{
  resetHolidayFeature( "KID" );
  resetHolidayFeature( "FML" );
  resetHolidayFeature( "ADU" );
  resetHolidayFeature( "ALL" );
  resetHolidayFeature( "PRM" );
  resetHolidayFeature( "CLB" );
  resetHolidayFeature( "CNL" );
  resetHolidayFeature( "YNL" );
}

function resetHolidayFeature( feature )
{
  var feature = $( feature );

  if( feature )
  {
    feature.checked = false;

    updateRelevantHiddenField( feature );
  }
}

function functionsPanelOverlay( unit, show, isHolFeaturesVisible )
{
  // make sure our arguments are nodes, not just IDs
  var unit = $( unit );
  //Only run this if the unit is who is going
  if ( unit.id == 'scuWho' )
  {
    childConf(unit, isHolFeaturesVisible);
  }
  else if (unit.id == 'scuDestination')
  {
    if ( hasSelectLoaded( "scuResortSelect" ) == false )
    {
      return ;
    }
  }

  if( show == "yes" )
  {
    // checking whether the unit is having the relevant dropdown
    // this is to avoid displaying the overlay when data is loading
    var unitSel = $( unit.id + 'Select' );
    if (unitSel)
    {
      // check whether the the dropdown is having more than one option.
      if (unitSel.disabled == false)
      {
        showOverlay( unit );
      }
      else
      {
        // nothing
      }
    }
    else
    {
      showOverlay( unit );
    }
  }
  else if( show == "hide" )
  {
    hideOverlay( unit );
  }
}

function childConf(unit, isHolFeaturesVisible)
{
  //children selector does not exist on eg clubbing pages
  var scuWhoChildrenSelect = $("scuWhoChildrenSelect")

  if( scuWhoChildrenSelect )
  {
    var numberOfChildren = scuWhoChildrenSelect.selectedIndex;

    if( unit.id == "scuWho" )
    {
      var childAgesBlock = $("childAgesBlock");

      if( numberOfChildren == 0)
      {
        childAgesBlock.hide();

        for( var i = 1; i <= searchConfig.maxNumberOfChildren; i++ )
        {
          var scuWhoChildAgeSelect = $("scuWhoChildAgeSelect"+i);

          scuWhoChildAgeSelect[scuWhoChildAgeSelect.selectedIndex].value = "";
        }
      }
      else
      {
        childAgesBlock.show();

        for( var i = 1; i <= numberOfChildren; i++ )
        {
          var childAge = $("childAge"+i);
          childAge.show();
        }

        for( var i = (numberOfChildren + 1); i <= searchConfig.maxNumberOfChildren; i++ )
        {
          var scuWhoChildAgeSelect = $("scuWhoChildAgeSelect"+i);

          scuWhoChildAgeSelect[scuWhoChildAgeSelect.selectedIndex].value = "";
          $("childAge"+i).hide();
        }
      }

      configureIsuFeatures( isHolFeaturesVisible );
    }
  }
}

function configureHolidayFeatures()
{
  var numberOfAdults  = 0;
  var numberOfSeniors  = 0;
  var numberOfChildren = 0;
  var numberOfInfants  = 0;

  if($("scuWhoAdultsSelect"))
  {
    numberOfAdults = $("scuWhoAdultsSelect").selectedIndex;
  }

  if($("scuWhoSeniorsSelect"))
  {
    numberOfSeniors = $("scuWhoSeniorsSelect").selectedIndex;
  }

  if($("scuWhoChildrenSelect"))
  {
    numberOfChildren = $("scuWhoChildrenSelect").selectedIndex;
  }

  if($("scuWhoInfantsSelect"))
  {
    numberOfInfants = $("scuWhoInfantsSelect").selectedIndex;
  }
}

function highlightWhosGoing()
{
  var searchUnit = $( "scuWho" );
  var fadePanel  = $( "scuWhoFade" );

  // make sure the fade panel is the same size as the unit it's supposed to cover
  fadePanel.style.width = Element.getWidth( searchUnit ) + "px";
  fadePanel.style.height = Element.getHeight( searchUnit ) + "px";

  fadePanel.style.display = "block";
// new Rico.Effect.FadeTo( fadePanel, 1, 0, 1 );
// new Rico.Effect.FadeTo( fadePanel, 1, 500, 1 );
// new Rico.Effect.FadeTo( fadePanel, 0, 1000, 20 );

  // define the fades, in reverse order so that we can chain them together
  var fade3 = function(){ new Rico.Effect.FadeTo( fadePanel, 0, 500, 10 ); };
  var fade2 = function(){ new Rico.Effect.FadeTo( fadePanel, 1, 500, 1, { complete: fade3 } ); };
  var fade1 = function(){ new Rico.Effect.FadeTo( fadePanel, 1, 0, 1, { complete: fade2 } ); };

  // trigger the first fade in the sequence
  fade1();
}

function checkWhoType(checkWho)
{
  switch(checkWho)
  {
    case 'adult' :
      $("adultAgeInfo").style.display = "block";
      $("childAgeInfo").style.display = "none";
      $("infantWarning").style.display = "none";
      $("childUnaccompaniedWarning").style.display = "none";
      isGlobal = false;
      break;
    case 'child' :
      $("adultAgeInfo").style.display = "none";
      $("childAgeInfo").style.display = "block";
      $("infantWarning").style.display = "none";
      $("childUnaccompaniedWarning").style.display = "none";
      isGlobal = false;
      break;
    case 'global' :
      $("adultAgeInfo").style.display = "block";
      $("childAgeInfo").style.display = "none";
      $("infantWarning").style.display = "none";
      $("childUnaccompaniedWarning").style.display = "none";
      break;
    default :
      $("infantWarning").style.display = "none";
      $("childUnaccompaniedWarning").style.display = "none";
      $("adultAgeInfo").style.display = "none";
      $("childAgeInfo").style.display = "none";
  }
}

// MOVED from functions.js
//show warning in scuWho overlay if children selected
function checkChildren(action, id)
{
  var fromRoom = id.charAt(id.length-1);
  var numberOfAdults = $("scuWhoAdultsSelect"+fromRoom).selectedIndex;
  var numberOfSeniors = $("scuWhoSeniorsSelect"+fromRoom).selectedIndex;
  var numberOfChildren = $("scuWhoChildrenSelect"+fromRoom).selectedIndex;
  var checkChildAgeInfo = $("childAgeInfo");
  var checkAdultAgeInfo = $("adultAgeInfo");

  if(((numberOfAdults + numberOfSeniors) == 0) && (numberOfChildren > 0))
  {
    if(action == "hide")
    {
      $("childUnaccompaniedWarning").style.display = "none";
    }
    else if(action == "show")
    {
      $("childUnaccompaniedWarning").style.display = "block";
    }
  }
  else
  {
    $("childUnaccompaniedWarning").style.display = "none";
  }
}

//show warning in scuWho overlay if Infants selected
function checkInfant(action, id)
{
  var fromRoom = id.charAt(id.length-1);
  var numberOfAdults = $("scuWhoAdultsSelect"+fromRoom).selectedIndex;
  var numberOfSeniors = $("scuWhoSeniorsSelect"+fromRoom).selectedIndex;
  var checkChildAgeInfo = $("childAgeInfo");
  var checkAdultAgeInfo = $("adultAgeInfo");

  if ((numberOfAdults + numberOfSeniors) == 0)
  {
    if(action == "hide")
    {
      $("infantWarning").style.display = "none";
    }
    else if(action == "show")
    {
      $("infantWarning").style.display = "block";
    }
  }
  else
  {
    $("infantWarning").style.display = "block";
  }
}

// MOVED from functions.js
//updates the child ages and allInOneRoom option.
function updateChildAges()
{
  var numberOfChildren = $("scuWhoChildrenSelect").selectedIndex;

  for( var i = numberOfChildren + 1; i <= searchConfig.maxNumberOfChildren; i++)
  {
    var scuWhoChildAgeSelect = $("scuWhoChildAgeSelect"+i);

    if( scuWhoChildAgeSelect )
    {
      scuWhoChildAgeSelect.selectedindex = 0;
      scuWhoChildAgeSelect.value         = "";
    }
  }
}

//MOUSEOVER HIGHLIGHTING FUNCTIONS ////////////////////////////////////

/* event handler to highlight option rows/cells on mouseover */
function optionMouseOver( event, element ){
  /* because IE doesn't support multiple classes in CSS selectors,
     we have to explicitly test the element state and set the class */

  if( Element.hasClassName( element, "selected" ) )
  {
    Element.addClassName( element, "mouseOverSelected" );
  }
  else if( Element.hasClassName( element, "warning" ) )
  {
    Element.addClassName( element, "mouseOverWarning" );
  }
  else
  {
    Element.addClassName( element, "mouseOver" );
  }
}

/* event handler to clear option row/cell highlighting when mouse leaves */
function optionMouseOut( event, element )
{
  optionClearMouseOver( element )
}

/* remove any mouseover highlighting from an option row/cell */
function optionClearMouseOver( element )
{
  Element.removeClassName( element, "mouseOver" );
  Element.removeClassName( element, "mouseOverSelected" );
  Element.removeClassName( element, "mouseOverWarning" );
}

function isShowRoom()
{
  var fieldObjDay1         = $( "scuDaySelect" );
  var fieldObjMonthYear1   = $( "scuMonthYearSelect" );
  var arrDateSplit         = fieldObjMonthYear1.value.split('/');
  var selectedDate         = arrDateSplit[0] + "/" + fieldObjDay1.options[fieldObjDay1.selectedIndex].value + "/" + arrDateSplit[1];

  return ( new Date(selectedDate) >= new Date("2009","4","1") );
}

// MOVED from functions.js
function updateRoom()
{
  var numberOfRooms        = $( "numberOfRooms" );
  var whosGoingHeading     = $( "whosgoingHeading" );
  var numberOfRoomsHeading = $( "numberofroomsHeading" );
  var roomBlock            = $( "roomBlock" );
  var roomTextBlock1       = $( "roomTextBlock1" );

  if( isShowRoom() )
  {
    if( searchConfig.isDayTripApplicable )
    {
      whosGoingHeading.show();
    }
    else
    {
      whosGoingHeading.hide();
    }

    numberOfRoomsHeading.show();
    roomBlock.show();
    roomTextBlock1.show();
  }
  else
  {
    whosGoingHeading.show();
    numberOfRoomsHeading.hide();
    roomBlock.hide();
    roomTextBlock1.hide();
    numberOfRooms.value = 1;
  }

  var noOfRooms = parseInt(numberOfRooms.value);

  for(var i = 1; i <= noOfRooms; i++ )
  {
    $("roomBlock"+i).show();

    var scuWhoChildrenSelect = $("scuWhoChildrenSelect"+i);

    if( scuWhoChildrenSelect.value == 0)
    {
      $("childAgesBlock"+i).hide();
    }
    else
    {
      for(var k = 0; k <= searchConfig.maxNumberOfChildren; k++ )
      {
        if( k > scuWhoChildrenSelect.value )
        {
          $("childAge"+i+k).hide();

          var scuWhoChildAgeSelect = $( "scuWhoChildAgeSelect"+i+k);

          scuWhoChildAgeSelect.hide();
          scuWhoChildAgeSelect[scuWhoChildAgeSelect.selectedIndex].value = "";
        }
      }
    }
  }

  if( noOfRooms != searchConfig.maxNumberOfRooms )
  {
    for (var i = noOfRooms + 1; i <= searchConfig.maxNumberOfRooms; i++ )
    {
      $("roomBlock"+i).hide();

      var scuWhoAdultsSelecti   = $( "scuWhoAdultsSelect" + i );
      var scuWhoSeniorsSelecti  = $( "scuWhoSeniorsSelect" + i );
      var scuWhoChildrenSelecti = $( "scuWhoChildrenSelect" + i );
      var scuWhoInfantsSelecti  = $("scuWhoInfantsSelect" + i );

      scuWhoAdultsSelecti[ scuWhoAdultsSelecti.selectedIndex ].value     = "";
      scuWhoSeniorsSelecti[ scuWhoSeniorsSelecti.selectedIndex ].value   = "";
      scuWhoChildrenSelecti[ scuWhoChildrenSelecti.selectedIndex ].value = "";
      scuWhoInfantsSelecti[ scuWhoInfantsSelecti.selectedIndex ].value   = "";

      for( var j = 1; j <= searchConfig.maxNumberOfChildren; j++ )
      {
        var scuWhoChildAgeSelectij = $("scuWhoChildAgeSelect" + i + j );

        if( scuWhoChildAgeSelectij )
        {
          scuWhoChildAgeSelectij[ scuWhoChildAgeSelectij.selectedIndex ].value = "";
        }
      }
    }
  }
}

// MOVED from functions.js
function configChildAgesForRooms(id)
{
  var numberOfChildren = $( id ).value;
  var noOfRooms        = $("numberOfRooms").value;
  var selectedRoom     = id.charAt( id.length - 1 );

  $( "childAgesBlock" + selectedRoom ).show();

  for(var i = 1; i <= searchConfig.maxNumberOfChildren; i++ )
  {
    if( i <= numberOfChildren )
    {
      $("childAge"+selectedRoom+i).style.display = "block";
      $( "scuWhoChildAgeSelect"+selectedRoom+i).style.display = "block";
    }
    else
    {
      $("childAge"+selectedRoom+i).style.display = "none";
      $( "scuWhoChildAgeSelect"+selectedRoom+i).style.display = "none";
    }
  }
}

// MOVED from functions.js
function validateRooms()
{
  var noOfRooms = $("numberOfRooms").value;

  for( var i = 1; i <= noOfRooms; i++ )
  {
    var scuWhoChildrenSelect = $("scuWhoChildrenSelect"+i);

    for( var j = 1 ; j <= 8 ; j++)
    {
      if( j > scuWhoChildrenSelect.value )
      {
        var scuWhoChildAgeSelectij = $("scuWhoChildAgeSelect" + i + j);

        scuWhoChildAgeSelectij[ scuWhoChildAgeSelectij.selectedIndex ].value = "";
      }
    }
  }
}

// MOVED from functions.js
function clearRefineErrorMessage()
{
  Element.removeClassName( "scuAirport", "errorState" );

  $("scuAirportErrorMessage").hide();
}

// MOVED from functions.js
function clearMessage()
{
   Element.removeClassName( "scuDuration", "errorState" );
   $("scuDurationErrorMessage").style.display = "none";
}

// MOVED from functions.js
/* Updating the Day of the week*/
function updateDayOfWeek()
{
  var days_of_week       = new Array('Sun','Mon','Tue','Wed','Thu','Fri','Sat');
  var fieldObjDay1       = $( "scuDaySelect" )
  var fieldObjMonthYear1 = $( "scuMonthYearSelect" )
  var arrDateSplit       = fieldObjMonthYear1.value.split('/')

  dateVar = arrDateSplit[0] + "/" + fieldObjDay1.options[fieldObjDay1.selectedIndex].value + "/" + arrDateSplit[1];

  var calendar = new Date(dateVar);

  calendar.setMonth(arrDateSplit[0]-1);
  calendar.setYear(arrDateSplit[1]);
  calendar.setDate(fieldObjDay1.options[fieldObjDay1.selectedIndex].value);

  if (fieldObjDay1.options[ fieldObjDay1.selectedIndex ].value == calendar.getDate())
  {
    $("scuDay").innerHTML = days_of_week[calendar.getDay()]
  }
  else
  {
    fieldObjDay1.selectedIndex = fieldObjDay1.selectedIndex - 1;

    if( calendar.getMonth() == 2 )
    {
      updateDayOfWeek();
    }
  }
}

function updateDepartureAirportSelection()
{
  $('scuAirportChanged').value = "true";
}

function updateResortSelection()
{
  $('scuResortChanged').value = "true";
  $('selectedResort').value = $('scuResortSelect').value;
}

function updateRefinedDurationSelection()
{
  $('scuDurationChanged').value = "true";
}

/* Returns the visible overlay on the home page */
function getActiveOverlay() {

  // Get overlay elements
  var dateOverlay        = $(scuDa.id + "Overlay");
  var durationOverlay    = $(scuDur.id + "Overlay");
  var airportOverlay     = $(scuAport.id + "Overlay");
  var destinationOverlay = $(scuDest.id + "Overlay");
  var whoOverlay         = $(scuWh.id + "Overlay");
  var resortOverlay      = $(scuRes.id + "Overlay");
  var accommOverlay      = $(scuAcc.id + "Overlay");
  var ratingOverlay      = $(scuRate.id + "Overlay");
  var featuresOverlay    = $(scuFeat.id + "Overlay");

  // Return the active overlay. If none are active, return null
  if((dateOverlay != null) && (dateOverlay.style.display == "block"))
    return scuDa;
  else if((durationOverlay != null) && (durationOverlay.style.display == "block"))
    return scuDur;
  else if((airportOverlay != null) && (airportOverlay.style.display == "block"))
    return scuAport;
  else if((destinationOverlay != null) && (destinationOverlay.style.display == "block"))
    return scuDest;
  else if((whoOverlay != null) && (whoOverlay.style.display == "block"))
    return scuWh;
  else if((resortOverlay != null) && (resortOverlay.style.display == "block"))
    return scuRes;
  else if((accommOverlay != null) && (accommOverlay.style.display == "block"))
    return scuAcc;
  else if((ratingOverlay != null) && (ratingOverlay.style.display == "block"))
    return scuRate;
  else if((featuresOverlay != null) && (featuresOverlay.style.display == "block"))
    return scuFeat;
  else
    return null;
}

// MOVED from functions.js
function validateIsu()
{
  var flag               = false;
  var strWhoError        = "";
  var fieldObjDay1       = $( "scuDaySelect" )
  var fieldObjMonthYear1 = $("scuMonthYearSelect")
  var arrDateSplit       = fieldObjMonthYear1.value.split('/');

  dateVar = arrDateSplit[0] + "/" + fieldObjDay1.options[fieldObjDay1.selectedIndex].value + "/" + arrDateSplit[1];

  var checkinDay            = new Date(dateVar);
  var currentDateObj        = new Date();
  var numberOfPassengers    = 0;
  var numberOfAdultsSeniors = 0;
  var numberOfChildren      = 0;
  var numberOfInfants       = 0;
  var roomFlag              = false;
  var ageFlag               = false;
  var childCountFlag        = false;

  validateRooms();

  $( "jsEnabled" ).value = "true";

  if(checkinDay < currentDateObj)
  {
    strWhoError = strWhoError + departuredate_validation_message;
  }

  if( strWhoError != "" )
  {
    // show an error state in the who's going section
    Element.addClassName( "scuDate", "errorState" );
    showElement( "scuDateErrorMessage" );
    $( "scuDateErrorMessage" ).innerHTML = strWhoError;
    throbFadePanel( "scuDateFade" );
    strWhoError = "";
    flag        = true;
  }
  else
  {
    // remove error state in the who's going section
    Element.removeClassName( "scuDate", "errorState" );
    $( "scuDateErrorMessage" ).innerHTML = "";
    hideElement( "scuDateErrorMessage" );
  }

  var numberOfRooms = $("numberOfRooms");

  if( numberOfRooms )
  {
    var numberOfRoomsVal = parseInt(numberOfRooms.value);

    for( var i = 1;  i <= numberOfRoomsVal; i++ )
    {
      var scuWhoAdultsSelect   = $( "scuWhoAdultsSelect"+i);
      var scuWhoSeniorsSelect  = $( "scuWhoSeniorsSelect"+i);
      var scuWhoChildrenSelect = $( "scuWhoChildrenSelect"+i);
      var scuWhoInfantsSelect  = $( "scuWhoInfantsSelect"+i);

      numberOfPassengers += scuWhoAdultsSelect.selectedIndex + scuWhoSeniorsSelect.selectedIndex + scuWhoChildrenSelect.selectedIndex + scuWhoInfantsSelect.selectedIndex;
      numberOfAdultsSeniors += scuWhoAdultsSelect.selectedIndex + scuWhoSeniorsSelect.selectedIndex;
      numberOfChildren += scuWhoChildrenSelect.selectedIndex;
      numberOfInfants += scuWhoInfantsSelect.selectedIndex;

      if( (scuWhoAdultsSelect.selectedIndex + scuWhoSeniorsSelect.selectedIndex + scuWhoChildrenSelect.selectedIndex + scuWhoInfantsSelect.selectedIndex) == 0)
      {
        if( roomFlag == false )
        {
          strWhoError = strWhoError + at_least_one_room_no_passengers;
          flag=true;
          roomFlag = true;
        }
      }

      var scuWhoChildrenSelectIndex = scuWhoChildrenSelect.selectedIndex;

      for( var j = 1; j <= scuWhoChildrenSelectIndex; j++ )
      {
        if($( "scuWhoChildAgeSelect"+i+j).selectedIndex == 0)
        {
          // show an error state in the who's going section
          if(ageFlag == false)
          {
            strWhoError = strWhoError + children_ages;
            flag=true;
            ageFlag = true;
          }
        }
      }

      if( scuWhoInfantsSelect.selectedIndex > (scuWhoAdultsSelect.selectedIndex + scuWhoSeniorsSelect.selectedIndex) )
      {
        if( childCountFlag == false )
        {
          strWhoError = strWhoError + number_infants;
          flag=true;
          childCountFlag = true;
        }
      }
    }
  }

  if( numberOfPassengers > 9 )
  {
    strWhoError = strWhoError + max_passengers;
    flag=true;
  }

  if( numberOfAdultsSeniors == 0 )
  {
    strWhoError = strWhoError + at_least_one;
    flag = true;
  }

  var scuAirportSelect = $( "scuAirportSelect" );

  if( scuAirportSelect[scuAirportSelect.selectedIndex].value == "000" )
  {
    flag = true;
  }

  if( strWhoError != "" )
  {
    // show an error state in the who's going section
    Element.addClassName( "scuWho", "errorState" );
    showElement( "scuWhoErrorMessage" );
    $( "scuWhoErrorMessage" ).innerHTML = "<p>" + strWhoError + "</p>";
    throbFadePanel( "scuWhoFade" );
    flag = true;
  }
  else
  {
    // remove error state in the who's going section
    Element.removeClassName( "scuWho", "errorState" );
    $( "scuWhoErrorMessage" ).innerHTML = "";
    hideElement( "scuWhoErrorMessage" );
  }

  if( flag == true )
  {
    return false;
  }

  var scuDestinationSelect = $('scuDestinationSelect');

  if( scuDestinationSelect )
  {
    $('scuDestinationChanged').value = "true";
    $('selectedDestination').value = scuDestinationSelect.value;
  }

  var scuAirportSelect = $('scuAirportSelect');

  if( scuAirportSelect )
  {
    $('scuAirportChanged').value = "true";
    $('selectedDepartureAirport').value = scuAirportSelect.value;
  }

  interstitial();
}

// MOVED from functions.js
function searchDestinationIsSelected()
{
  return ($( "scuDestinationSelect" ).selectedIndex > 0);
}

function toggleSearchFeatures(show)
{
  if( typeof(expandMoreOptions) == "undefined" )
  {
    if( show == "yes" )
    {
      $("searchOptionsBlock").style.display = "block";
      $("searchOptionsToggle").innerHTML = "<a id=\"searchOptionsBlockLink\" href=\"javascript:toggleSearchFeatures('no');\">More options<img src=\"/images/buttons/arrow_up.gif\" alt=\"Open more options\" width=\"11\" height=\"9\" /></a>";
    }
    else if( show == "no" )
    {
      $("searchOptionsBlock").style.display = "none";
      $("searchOptionsToggle").innerHTML = "<a id=\"searchOptionsBlockLink\" href=\"javascript:toggleSearchFeatures('yes');\">More options<img src=\"/images/buttons/arrow_down.gif\" alt=\"Close more options\" width=\"11\" height=\"9\" /></a>";
    }
  }
}

// MOVED from functions.js
function toggleSearchFeaturesHide()
{
   $("searchOptionsToggle").innerHTML = "<a id=\"searchOptionsBlockLink\" href=\"javascript:toggleSearchFeatures('yes');\">More options<img src=\"/images/buttons/arrow_down.gif\" alt=\"Close more options\" width=\"11\" height=\"9\" /></a>";
}

// MOVED from functions.js
// returns true if all the search "more options" are at their default value
function searchMoreOptionsAreAllDefault()
{
  var allDefault = true;
  var searchOption;

  for( searchOption in searchMoreOptions )
  {
    allDefault &= searchMoreOptionIsDefault( searchOption );
  }

  return allDefault;
}

// returns true if a particular search "more options" option is at its default value
function searchMoreOptionIsDefault( optionDiv )
{
  // make sure our arguments are nodes, not just IDs
  var optionDiv = $( optionDiv );

  // if a search option does not appear on the page then consider it to be at its
  // default value
  if( optionDiv == null ){ return true; }

  var isDefault = true;

  switch( optionDiv.id )
  {
    case "scuResort" :
      isDefault = ($( "scuResortSelect" ).selectedIndex == 0);
      break;

    case "scuAccommodation" :
      isDefault = ($( "scuAccommodationSelect" ).selectedIndex == 0);
      break;

    case "scuRating" :
      isDefault = ($( "scuRatingSelect" ).selectedIndex == 0);
      break;

    case "scuFeatures" :
      // find all the checkboxes within the features search option
      var featuresDiv = $( "scuFeaturesOptions" );
      var features = $A( featuresDiv.getElementsByTagName( "input" ) );

      // assume they're all default (ie. unchecked)
      isDefault = true;
      for( var i = 0, len = features.length; i < len; ++i )
      {
        // but if any of them are checked then mark as non-default
        if( features[i].checked )
        {
          isDefault = false;
          break;
        }
      }

      break;
  }

  return isDefault;
}

// show or hide the expand/collapse button for a particular search "more options" option
function searchMoreOptionSetExpandCollapseVisibility( optionDiv, visible )
{
  // don't do anything if the search option doesn't appear on this page
  if( $( optionDiv ) == null ){ return; }

  var image = searchMoreOptionGetExpandCollapseImage( optionDiv );

  if( typeof( image ) != "undefined" ){
    // set the visibility of the image
    if( visible ){
      Element.show( image );
    } else {
      Element.hide( image );
    }
  }
}

// MOVED from functions.js
function searchMoreOptionGetExpandCollapseImage( optionDiv )
{
  // make sure our arguments are nodes, not just IDs
  var optionDiv = $( optionDiv );

  var expandCollapse = getSearchMoreOptionProperty(optionDiv.id, "expandCollapse", false);

  // get hold of the expand/collapse DIV for this option
  expandCollapse = $( expandCollapse );

  // find the image tag within the expand/collapse DIV
  var images = expandCollapse.getElementsByTagName( "IMG" );

  if( images.length > 0 )
  {
    return $( images[0] );
  }
}

function searchMoreOptionResortErrorHide()
{
  // if the message isn't visible then we don't need to hide it
  if( (typeof( window.searchMoreOptionResortErrorVisible ) != "undefined") && !(window.searchMoreOptionResortErrorVisible) )
  {
    return;
  }

  // remove any error state on the resort and destination panel and make
  // sure the resort dropdown is visible
  Element.removeClassName( "scuResort", "errorState" );
  hideElement( "scuResortErrorMessage" );
  showElement( "scuResortSelect" );

  // clear the highlight on the destination panel
  $( "scuDestinationFade" ).style.display = "none";

  // make a note of the error state
  window.searchMoreOptionResortErrorVisible = false;
}

// MOVED from functions.js
function searchMoreOptionResortErrorShow()
{
  // if the message is already visible then we don't need to show it
  if( (typeof( window.searchMoreOptionResortErrorVisible ) != "undefined") && window.searchMoreOptionResortErrorVisible )
  {
    return;
  }

  // show an error state in the resort section and hide the resort drop-down
  Element.addClassName( "scuResort", "errorState" );
  showElement( "scuResortErrorMessage" );
  hideElement( "scuResortSelect" );

  // throb the destination panel to draw attention to it
  throbFadePanelToHighlight( "scuDestinationFade" );

  // make a note of the error state
  window.searchMoreOptionResortErrorVisible = true;
}

// MOVED from functions.js
// update the expand/collapse visibility for a particular search "more options" option
// based on whether the option is at its default value or not
function searchMoreOptionUpdate( optionDiv )
{
  // make sure we have the actual node
  var optionDiv = $( optionDiv );

  // don't do anything if the search option is missing on this page
  if( optionDiv == null ){ return; }

  // deal with special case for resort drop-down when the destination
  // hasn't been chosen yet
  if( (optionDiv.id == "scuResort") && ($("scuResort") != null) ){

    // if there's no destination selected, then we must reset the resort dropdown
    // if( !searchDestinationIsSelected() ){
      // $( "scuResortSelect" ).selectedIndex = 0;
    // }
    // only show the resort error when resort is expanded and no destination selected
    // var showResortError = (searchMoreOptionIsExpanded( "scuResort" ));

    // if( showResortError){
      // searchMoreOptionResortErrorShow();
    // } else {
      // searchMoreOptionResortErrorHide();
    // }
  }

  // see if this option is set to its default
  var isDefault = searchMoreOptionIsDefault( optionDiv );

  if( isDefault )
  {
    // allow the option to be collapsed
    searchMoreOptionSetExpandCollapseVisibility( optionDiv, true );

    var isExpanded = getSearchMoreOptionProperty( optionDiv.id, "isExpanded", false );

    if( isExpanded )
    {
      if( !searchMoreOptionIsExpanded( optionDiv ) )
      {
        searchMoreOptionExpand( optionDiv );
      }
    }
  }
  else
  {
    // make sure that the option is expanded
    if( !searchMoreOptionIsExpanded( optionDiv ) )
    {
      searchMoreOptionExpand( optionDiv );
    }

    // prevent the option from being collapsed
    searchMoreOptionSetExpandCollapseVisibility( optionDiv, false );
  }
}

// MOVED from functions.js
// update the display of the search "more options" panel
function searchMoreOptionsUpdateAll()
{
  // if the search panel doesn't have the "More options" section then don't try updating it!
  if( $( "searchOptionUnits" ) == null ){ return; }

  var allCollapsed = true;
  var isExpanded   = false;
  var searchOption;

  // update all the individual options
  for( searchOption in searchMoreOptions )
  {
    searchMoreOptionUpdate( searchOption );

    isExpanded = getSearchMoreOptionProperty( searchOption, "isExpanded", false );

    if( isExpanded )
    {
      allCollapsed = false;
    }
  }

  // see if all the options are at their default
  var allDefault = searchMoreOptionsAreAllDefault();

  if( $('searchOptionsToggle') != null)
  {
    if( allDefault || allCollapsed )
    {
      Element.show( "searchOptionsToggle" );
    }
    else
    {
      // make sure the user can't hide the extra options
      Element.hide( "searchOptionsToggle" );
      // make sure the extra options panel is expanded
      toggleSearchFeatures( "yes" );
    }
  }
}

// MOVED from functions.js
// check to see whether a search more options panel is expanded or not
function searchMoreOptionIsExpanded( optionDiv )
{
  var optionDiv = $( optionDiv );

  // can't do anything if it doesn't exist
  if( optionDiv == null ){ return; }

  var optionMetadata = searchMoreOptions[optionDiv.id];

  var divDisplay = $( optionMetadata.expandCollapseDiv ).style.display;

  // the block is expanded if the relevant DIV has display block or inline
  return (divDisplay == "block" || divDisplay == "inline");
}

// MOVED from functions.js
function searchMoreOptionExpandHandler( event, optionDiv )
{
  // stop the event propagating any further
  stopEventBubbling( event );
  // expand the option DIV
  searchMoreOptionExpand( optionDiv );
}

function searchMoreOptionExpand( optionDiv )
{
  var optionDiv = $( optionDiv );

  // we can't expand the panel if it doesn't exist
  if( optionDiv == null ){ return; }

  var optionMetadata = searchMoreOptions[optionDiv.id];

  showElement( optionMetadata.expandCollapseDiv );

  var image = searchMoreOptionGetExpandCollapseImage( optionDiv );

  image.src =  "/images/buttons/form/collapse.gif";
  image.alt = "Collapse";
  image.title = "click to collapse the " + optionMetadata.description + " option";
  image.onclick = function( event2 )
  {
    searchMoreOptionCollapseHandler( event2, optionDiv );
  };

  // make sure that the option display is up to date
  searchMoreOptionUpdate( optionDiv );

  searchMoreOptions[optionDiv.id].isExpanded = true;
}

// MOVED from functions.js
function searchMoreOptionCollapseHandler( event, optionDiv )
{
  // stop the event propagating any further
  stopEventBubbling( event );
  // collapse the option DIV
  searchMoreOptionCollapse( optionDiv );
}

// MOVED from functions.js
function searchMoreOptionCollapse( optionDiv )
{
  // make sure our arguments are nodes, not just IDs
  var optionDiv      = $( optionDiv );
  var optionMetadata = searchMoreOptions[optionDiv.id];

  //db - clear highlight on destination when resort option is collapsed
  //$( "scuDestinationFade" ).style.display = "none";
  hideElement( optionMetadata.expandCollapseDiv );

  var image = searchMoreOptionGetExpandCollapseImage( optionDiv );

  image.src =  "/images/buttons/form/expand.gif";
  image.alt = "Expand";
  image.title = "click to expand the " + optionMetadata.description + " option"

  image.onclick = function( event2 )
  {
    searchMoreOptionExpandHandler( event2, optionDiv );
  };
  functionsPanelOverlay(optionDiv.id, 'hide', true);
  // make sure that the option display is up to date
  searchMoreOptionUpdate( optionDiv );

  searchMoreOptions[optionDiv.id].isExpanded = false;
}

// MOVED from function.js
function throbFadePanelToHighlight( fadePanel )
{
  // make sure our arguments are nodes, not just IDs
  var fadePanel = $( fadePanel );

  var searchUnit = fadePanel.up();

  // don't do anything if any of the elements can't be found, eg. during loading
  if( (searchUnit == null) || (fadePanel == null) ){ return; }

  fadePanel.style.display = "block";
  fadePanel.style.width = Element.getWidth( searchUnit ) + "px";
  fadePanel.style.height = Element.getHeight( searchUnit ) + "px";

  // define the fades, in reverse order so that we can chain them together
  var fade3 = function(){ new Rico.Effect.FadeTo( fadePanel, 1, 500, 10 ); };
  var fade2 = function(){ new Rico.Effect.FadeTo( fadePanel, 0, 500, 10, { complete: fade3 } ); };
  var fade1 = function(){ new Rico.Effect.FadeTo( fadePanel, 1, 0, 1, { complete: fade2 } ); };

  // trigger the first fade in the sequence
  fade1();
}

// MOVED from function.js
// called when an option is selected on one of the search overlay panels
function toggleEffect(fadePanel, selectedInput, optionID)
{

  // hide the current overlay if there is one
  if(overlayLocked != "no")
  {
    hideOverlay( overlayLocked );
  }

  // throb the relevant section of the search panel
  throbFadePanel( fadePanel );

  //alert(fadePanel + "--2--" + selectedInput + "---" + optionID);

  // update the drop-down box to the chosen option
  var selectBox       = $(selectedInput);
  var numberOfOptions = $(selectedInput).options.length;

  for( var i = 0; i < numberOfOptions; i++ )
  {
    if( (selectBox.options[i].id == optionID) || (selectBox.options[i].value == optionID) )
    {
      $(selectedInput).selectedIndex = i;
    }
  }


  // if it's set one of the options on the search "more options" panel
  if( selectedInput == "scuDestinationSelect" ||
    selectedInput == "scuResortSelect" ||
    selectedInput == "scuAccommodationSelect" ||
    selectedInput == "scuRatingSelect" )
  {
    // then update all the expand/collapse visibility, etc.
    searchMoreOptionsUpdateAll();
  }
}

// MOVED from function.js
function hasSelectLoaded(select)
{
   var loaded = false;
   var select = $(select);

   if ( select != null )
   {
      if ( select[0].value != 'Loading...' )
      {
         loaded = true;
      }
   }

   return loaded;
}

// MOVED from functions.js
// click handler for the option links on the search unit overlays
function searchUnitOverlayOptionClicked( event )
{
  // make sure we've got hold of the event in IE
  if( !event ){ event = window.event; }

  // find out which link was clicked
  var clickedOption = Event.element( event );

  // use the link's ID to work out which search dropdown and option it corresponds to
  var optionIdPieces = clickedOption.id.split( "_" );

  // bail out if there's a problem parsing the link ID
  if( (length[optionIdPieces] < 3) || (optionIdPieces[2] != "overlay") ){ return; }

  var relatedSearchUnit = optionIdPieces[0];
  var selectedOption = optionIdPieces[0] + "_" + optionIdPieces[1];
  toggleEffect( relatedSearchUnit + "Fade", relatedSearchUnit + "Select", selectedOption );
  firefoxForceRerender();
}


// MOVED from functions.js
// update a search unit overlay so that the selected option is highlighted
function searchUnitOverlayUpdate( searchUnitId )
{
  var highlightableOverlays = $A( ["scuDuration", "scuAirport", "scuDestination", "scuResort", "scuAccommodation", "scuRating"] );

  // don't try to do anything if our search unit isn't in the list
  if( highlightableOverlays.indexOf( searchUnitId ) < 0 )
  {
    if (searchUnitId == "scuDate")
    {
       updateCalWithSelectedValues();
    }

    return;
  }

  // find which option is currently selected for the unit
  var dropdown = $( searchUnitId + "Select" );

  //LDM: Use Id rather than value
  //var selectedOption = $F( dropdown );
  var selectedOption = dropdown.options[dropdown.selectedIndex].id;

  // get hold of the search unit's overlay, and all the links in the overlay
  var overlay = $( searchUnitId + "Overlay" );
  var links = overlay.getElementsByTagName( "A" );

  // make some regular expressions for testing the link IDs
  var optionLinkTest = new RegExp( "^" + searchUnitId + "_.*_overlay$" );
  var selectedOptionLinkTest = new RegExp( "^" + selectedOption + "_overlay$" );

  // run through all the links in the overlay
  for( var i = 0; i < links.length; i++ )
  {
    var link = links[i];

    // if this link is an option link, then we have select or deselect it
    if( link.id.match( optionLinkTest ) )
    {
      // if it's the link for the selected option then highlight it
      if( link.id.match( selectedOptionLinkTest ) )
      {
        Element.addClassName( link, "selected" );
      }
      else
      {
        //otherwise remove any existing highlight
        Element.removeClassName( link, "selected" );
      }
    }
  }

  firefoxForceRerender();
}

// MOVED from functions.js
// if user checks/unchecks update the relevant hidden field.
function updateRelevantHiddenField(checkbox)
{
  var field = $( "selectedAccommodationAttributes_" + checkbox.id );

  if( checkbox.checked )
  {
    field.value = checkbox.value;
  }
  else
  {
    field.value = "";
  }
}

// extract an option property as defined in the array at the top of the page
function getSearchMoreOptionProperty( optionID, propertyName, defaultValue )
{
  return objectGetProperty( searchMoreOptions[optionID], propertyName, defaultValue );
}
