// Dynamic Location
var SelBrochure = '';
var SelLocation = '';
var SelAirport = '';
var SelCountry = '';
var SelDest = '';
var SelResort = '';
var SelAccomm = '';
var SelResortAccom = '';
var SelDuration = '';

PreviousDateInvalid = false;

//Cruise related variables
var SelCruiseType='';
var SelDepartureMonth='';
var SelShipOrShipArea='';
var SelShip='';
var SelCruiseArea='';
var SelItinerary='';
var SelDepartureAirport='';
var SelDeparturePoint='';

var pageOnload = true;

function SelectOptionByValue(select, value) {
  for (var i = select.length; i--; ) {
    if (select.options[i].value == value) {
      select.selectedIndex = i;
      return true;
    }
  }
  return false;
}

// Update dropdowns with selected value if date/departure airport changed
function ShowSelection(elementid,noupdate)
{
  switch(elementid)
  {
  // Location
  case 'destinationCode':
    if (SelLocation != 'Any')
    {
      SelectOptionByValue($('destinationCode'), SelLocation);
      if (!noupdate) {DynamicUpdate(elementid,'change', 1) }
    }
  break;

  case 'countryDestCode':
    if (SelLocation != 'Any')
    {
      SelectOptionByValue($('countryDestCode'), SelLocation);
      if (!noupdate) {DynamicUpdate(elementid,'change', 1) }
    }
  break;

  // Resort
  case 'resortCode':
    if (SelResort != 'Any')
    {
      SelectOptionByValue($('resortCode'), SelResort);
      if (!noupdate) {DynamicUpdate(elementid,'change', 1) }
    }
  break;

  case 'resortAccomCode':
    if (SelResortAccom != 'Any')
    {
      if ($('countryDestCode').value.indexOf('|')>-1)
      {
        SelectOptionByValue($('resortCode'), SelResort);
        if (!noupdate) { DynamicUpdate(elementid,'change', 1) }
      }
      else
      {
        if ($('countryDestCode').options[$('countryDestCode').selectedIndex+1] && $('countryDestCode').options[$('countryDestCode').selectedIndex+1].value.indexOf('|')!=-1)
        {
          $('resortAccomCode').disabled=true;
        }
      }
    }
  break;

  case 'accommodationCode':
    if (SelAccomm != 'Any')
    {
      SelectOptionByValue($('accommodationCode'), SelAccomm);
      if (!noupdate) { DynamicUpdate(elementid,'change', 1) }
    }
  break;
  }
}

function updateDestCodes()
{
  if ($("countryDestCode").selectedIndex == 0)
  {
    $("countryCode").value = "";
    $("destinationCode").value = "";
    $("resortCode").value = "";
    $("accommodationCode").value = "";
    $("resortAccomCode").selectedIndex = 0;
    $("resortAccomCode").disabled = true;
  }
  else
  {
    var countryDestCode = $("countryDestCode").value;
    var codeArray  = countryDestCode.split("|");
    $("countryCode").value = codeArray[0];
    $("destinationCode").value = codeArray[1];

    if (codeArray[1])
    {
    DynamicUpdate('destinationCode','change',1);
    }
    else if (codeArray[0] && !codeArray[1])
    {
     countryDestCode = $("countryDestCode").value;
     var codeArray  = countryDestCode.split("|");
     $("countryCode").value = codeArray[0];
     $("destinationCode").value = codeArray[1];
     DynamicUpdate('destinationCode', "change", 1);
    }
  }
}


function updateResortAccomCodes()
{
  var resortAccomCode = $("resortAccomCode").value;
  var codeArray  = resortAccomCode.split("|");
  $("resortCode").value = codeArray[0];
  if (codeArray[1])
  {
    $("accommodationCode").value = codeArray[1];
  }
  else
  {
     $("accommodationCode").value = ""
  }
  if ($("resortAccomCode").selectedIndex == 0)
  {
     $("accommodationCode").value = ""
    $("resortCode").value = ""
  }
}


// Save current selection
function SaveSelection()
{
  SelLocation = $('destinationCode').value;
  SelResort = $('resortCode').value;
  SelAccomm = $('accommodationCode').value;
}

/**
* This function fetches the cruise type from
* the radio buttons. If the cruise type drop
* down exists, then it fetches the cruise type
* from the drop down. This is done since the alternate
* search panel still uses the cruise type drop down.
*/
function selectedCruiseType() {
  if ($('cruiseType')) {
    return $F('cruiseType');
  }
  var elements = (document.forms.searchForm || document.forms[0]).elements;
  for (var i = 0; i < elements.length; i++) {
    var element = elements[i];
    if (element.type == "radio" && element.checked) {
      return element.value;
    }
  }
}

function DynamicUpdate(ElementID,ElementEvent,SaveFlag)
{
  // Identify if current search selection codes should be saved
  var SaveCodes = (SaveFlag != 1);

  if (ElementID)
  {
    ElementEvent = ElementID + '_' + ElementEvent
  }
  switch(ElementEvent)
  {
    case 'date_keyup':
    case 'date_change':
      if (validateCheckInDate())
      {
        FieldObjDay1 = $('calendar_day')
        FieldObjMonthYear1 = $('calendar_month_year')
        var arrDateSplit = FieldObjMonthYear1.value.split('/')
        dateVar = arrDateSplit[0] + "/" + FieldObjDay1.options[FieldObjDay1.selectedIndex].value + "/" + arrDateSplit[1];
        var subtypeArr = getSelectedSubtype().split("|");
        SaveSelection();
        Params = 'subtype='+subtypeArr[0]+'&subtypeId='+subtypeArr[1]+'&selectedDate='+dateVar;
      }
      break;

    // Location - Selection changed / Key Up
    case 'moreDestinations_keyup':
    case 'moreDestinations_change':
      if (validateCheckInDate())
      {
        Params = 'moreDestinations=true';
        document.searchForm.moreDestinations.value = "true";
        if (!PageLoad) { LoadDropDown(Params,'ShowSelection("destinationCode"),changeDropdownStyle("destinationCode","10")','destinationCode') }
        DynamicUpdate('destinationCode','change',1)
      }
      break;
    case 'nominalDestinations_keyup':
    case 'nominalDestinations_change':
      if (validateCheckInDate())
      {
        Params = 'moreDestinations=false';
        document.searchForm.moreDestinations.value = "false";
        if (!PageLoad) { LoadDropDown(Params,'ShowSelection("destinationCode"),changeDropdownStyle("destinationCode","1")','destinationCode') }
        DynamicUpdate('destinationCode','change',1)
      }
      break;
    case 'moreResorts_keyup':
    case 'moreResorts_change':
      if (validateCheckInDate())
      {
        if ($("destinationCode").value!="")
        {
          document.searchForm.moreResorts.value = "true";
          Params = 'moreResorts=true&destinationCode='+getValidDestinationCode($("destinationCode").value);
          if (!PageLoad) { LoadDropDown(Params,'ShowSelection("resortAccomCode"),changeDropdownStyle("resortCode","10")','resortCode') }
          DynamicUpdate('resortCode','change',1)
        }
      }
      break;
    case 'nominalResorts_keyup':
    case 'nominalResorts_change':
      if (validateCheckInDate())
      {
        if ($("destinationCode").value!="")
        {
          Params = 'moreResorts=false';
          document.searchForm.moreResorts.value = "false";
          if (!PageLoad) { LoadDropDown(Params,'ShowSelection("resortCode"),changeDropdownStyle("resortCode","1")','resortCode') }
          DynamicUpdate('resortCode','change',1)
        }
      }
      break;
    // Location - Selection changed / Key Up
    case 'subtype_keyup':
    case 'subtype_change':
    if ( suggestionElement.style.display == 'inline')
    {
      suggestionElement.style.display = 'none';
      $("departure").value = '';
    }
      if (validateCheckInDate())
      {
        var subtypeArr = getSelectedSubtype().split("|");
        if(subtypeArr[0]=='CITY')
        {
        	$("destinationCode").value = $("countryCode").value;
        }
        Params = 'subtype='+subtypeArr[0]+'&subtypeId='+subtypeArr[1]+'&countryCode='+$("countryCode").value+'&destinationCode='+$("destinationCode").value+'&resortCode='+$("resortCode").value+'&accommodationCode='+$("accommodationCode").value;
        if (!PageLoad) { LoadDropDown(Params,'ShowSelection("destinationCode")','countryDestCode') }
        DynamicUpdate('countryDestCode','change',1);
      }
      break;

    case 'countryDestCode_keyup':
    case 'countryDestCode_change':
      if (validateCheckInDate())
      {
        if ($("countryDestCode").selectedIndex == 0)
        {
          ElementAction('resortAccomCode','showany')
          $("countryCode").value="";
          $("destinationCode").value="";
          $("resortCode").value="";
          $("accommodationCode").value="";
        }
        else
        {
          var country = $("countryDestCode").value.split("|");
          var index = $("countryDestCode").selectedIndex;
          if (typeof(country[1]) == "undefined")
          {
             var nextIndex = index + 1
             if ($("countryDestCode").options[nextIndex])
             {
            //$("countryDestCode").selectedIndex = nextIndex;
             }
          }
          var subtypeArr = getSelectedSubtype().split("|");
          if ($("countryCode").value=="")
          {
          	$("countryCode").value = country[0];
          }
           if ($("destinationCode").value=="")
          {
          	$("destinationCode").value = country[1];
          }
          if ($("destinationCode").value=="undefined")
          {
            $("destinationCode").value = $("countryCode").value;
          }
          if (!PageLoad) { LoadDropDown(Params,'ShowSelection("resortAccomCode"),changeDropdownStyle("resortAccomCode","1")','resortAccomCode') }
        }
        if (document.searchForm.moreResorts.value=="true")
        {
          //updateListWithLocations('moreResortsLink','nominalResortsLink', 'moreResorts');
        }else{
          DynamicUpdate('resortAccomCode','change',1)
        }
      }
      break;

    // Location - Selection changed / Key Up
    case 'destinationCode_keyup':
    case 'destinationCode_change':

      if (validateCheckInDate())
      {
        if (isany('destinationCode'))
        {
          ElementAction('resortAccomCode','showany')
        }
        else
        {
          var subtypeArr = getSelectedSubtype().split("|");
          if ($("destinationCode").value=="undefined")
          {
            $("destinationCode").value = $("countryCode").value;
          }
          Params = 'countryCode='+getValidDestinationCode($("countryCode").value)+'&destinationCode='+getValidDestinationCode($("destinationCode").value)+'&subtype='+subtypeArr[0]+'&subtypeId='+subtypeArr[1];
          if (PageLoad) { LoadDropDown(Params,'ShowSelection("resortAccomCode"),changeDropdownStyle("resortAccomCode","1")','resortAccomCode') }
        }
        if (document.searchForm.moreResorts.value=="true")
        {
          //updateListWithLocations('moreResortsLink','nominalResortsLink', 'moreResorts');
        }else{
          DynamicUpdate('resortAccomCode','change',1)
        }
      }
      break;

    // Resort - Selection changed / Key Up
    case 'resortCode_keyup':
    case 'resortCode_change':
      if (validateCheckInDate())
      {
        if (isany('resortCode'))
        {
          ElementAction('accommodationCode','showany')
        }
        else
        {
          Params = 'resortCode='+$("resortCode").value
          if (!PageLoad) { LoadDropDown(Params,'ShowSelection("accommodationCode")','accommodationCode') }
        }
        DynamicUpdate('accommodationCode','change',1)
      }
      break;

    case 'accommodationCode_keyup':
    case 'accommodationCode_change':
      if (validateCheckInDate())
      {
        if (!isany('accommodationCode'))
        {
          //if (!PreviousDateInvalid) {   SaveSelection() }
        }
      }
      break;
  }
}

function setSubtypeId()
{
  $("subtypeId").value = getSelectedSubtype().split("|")[0];
}

function getSelectedSubtype()
{
  if (document.searchForm.subtype.type=="hidden")
  {
    return document.searchForm.subtype.value;
  } else {
    for(var i=0;i<document.searchForm.subtype.length;i++)
    {
      if (document.searchForm.subtype[i].checked)
      {
        return document.searchForm.subtype[i].value;
      }
    }
  }
}

function getValidDestinationCode(destinationCode)
{
  if (destinationCode.indexOf("|")>-1)
  {
    codeArr = destinationCode.split("|");
    return codeArr[0];
  }
  return destinationCode;
}

function DynamicUpdateInit()
{
  if (document.searchForm.moreDestinations.value!="true")
  {
    DynamicUpdate('countryDestCode','change');
  }
  UpdateDayOfWeek();
  pageOnload = false;
}

function UpdateDayOfWeek() {
  var days_of_week = new Array('Sun','Mon','Tue','Wed','Thu','Fri','Sat');

  FieldObjDay1 = $('calendar_day');
  FieldObjMonthYear1 = $('calendar_month_year');

  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())
  {
    $('calendar_dow').innerHTML = days_of_week[Calendar.getDay()];
  }
  else
  {
    FieldObjDay1.selectedIndex = FieldObjDay1.selectedIndex - 1;
    if(Calendar.getMonth() == 2)
    {
      UpdateDayOfWeek();
    }
  }
}

function updateCheckoutDate()
{
  var dateWrapper = Dates;
  var calendarDay = $("calendar_day").value;
  var calendarMonthYear = $("calendar_month_year").value;
  var numberOfNights = $("duration").value;
  var date = (calendarDay+"/"+calendarMonthYear).split('/');
  var departureDate = new Date(date[2], (date[1]-1), date[0]);

  // adjust for time zone
  var timezoneOffset = 0;
  if (departureDate.getTimezoneOffset() != '0')
  {
    timezoneOffset = -((departureDate.getTimezoneOffset())/60);
  }
  if(timezoneOffset<0)
  {
    timezoneOffset = -(timezoneOffset);
  }
  var durationInMS = numberOfNights * 86400000 + (timezoneOffset * 3600000);
  var arrivalDate = new Date(departureDate.getTime() + durationInMS);

  $("checkOutDaySpan").innerHTML = dateWrapper.shortDays[arrivalDate.getDay()];
  $("checkOutDateSpan").innerHTML = arrivalDate.getDate();
  $("checkOutMonthYearSpan").innerHTML = dateWrapper.shortMonths[arrivalDate.getMonth()] + " " + arrivalDate.getFullYear();
  $("checkOutDay").value = arrivalDate.getDate();
  $("checkOutMonthYear").value = (arrivalDate.getMonth()+1) + "/" + arrivalDate.getFullYear();
}

function setHoliday()
{
  var selProductType = $('productType');
  for(i=0;selProductType && i<selProductType.length;i++)
  {
    if (selProductType.options[i].value == holiday_type && document.location.href.indexOf('initialisePortalSearchPanel.do')==-1)
    {
      selProductType.options[i].selected = true;
      break;
    }
  }
}

// Reset briochure code to Any when the holiday type is not
// villas and location href is not viewAlternateSearchPanel
function setBrochure() {
  var holidayType = $F('productType') || '';
  if ($F('SearchBrochure') == '' && holidayType != 'villa' && holidayType.indexOf('showVillaHomePage.do') == -1) {
    $("SearchBrochure").selectedIndex = 0;
  }
}

// When search panel retains the brochure name for e.g. if you come back from brochure browse,
// durations must be updated according to the retained brochure code.
function updateDurations()
{
  Params = 'BrochureCode='+ $F('SearchBrochure');
  LoadDropDown(Params,'ShowSelection("SearchDuration");','','','SearchDuration');
  SelDuration = $F('SearchDuration');
}

function validateCheckInDate()
{
  FieldObjDay1 = $('calendar_day');
  FieldObjMonthYear1 = $('calendar_month_year');

  var arrDateSplit = FieldObjMonthYear1.value.split('/');
  dateVar = arrDateSplit[0] + "/" + FieldObjDay1.options[FieldObjDay1.selectedIndex].value + "/" + arrDateSplit[1];
  var Calendar = new Date(dateVar);
  var checkinDay=new Date(dateVar);
  var currentDateObj=new Date(currentDate);
  var maxDate = new Date(maxSeasonDate);
  var minDate = new Date(minSeasonDate);

  if (pageOnload)
  {
    if (Calendar.before(minDate))
    {
      resetCheckInDate(minSeasonDate);
      return true;
    }
  }

  if (checkinDay.after(maxDate))
  {
    alert("Please select a date on or before "+maxDate.getDate()+"/"+(maxDate.getMonth()+1)+"/"+maxDate.getFullYear());
    resetCheckInDate(maxSeasonDate);
    return false;
  }
  if (checkinDay.before(minDate))
  {
    if (checkinDay.before(currentDateObj))
    {
      alert("Please select a date on or after "+currentDateObj.getDate()+"/"+(currentDateObj.getMonth()+1)+"/"+currentDateObj.getFullYear());
      resetCheckInDate(currentDate);
    }else{
      alert("Please select a date on or after "+minDate.getDate()+"/"+(minDate.getMonth()+1)+"/"+minDate.getFullYear());
      resetCheckInDate(minSeasonDate);
    }
    return false;
  }
  /*if (checkinDay.before(currentDateObj))
  {
    alert("Please select a date on or after "+currentDateObj.getDate()+"/"+(currentDateObj.getMonth()+1)+"/"+currentDateObj.getFullYear());
    resetCheckInDate(currentDate);
    return false;
  }*/
  return true;
}

function resetCheckInDate(selectedDate)
{
  var dateObj = new Date(selectedDate);
  $('calendar_day').selectedIndex = dateObj.getDate()-1;
  for(var i=0;i<$('calendar_month_year').options.length;i++)
  {
    if ($('calendar_month_year').options[i].value==((dateObj.getMonth()+1)+"/"+dateObj.getFullYear()))
    {
      $('calendar_month_year').selectedIndex = i;
      break;
    }
  }
  UpdateDayOfWeek();
  updateCheckoutDate();
  DynamicUpdate('date','change',1);
}
