// Dynamic Location
var SelBrochure = '';
var SelLocation = '';
var SelAirport = '';
var SelCountry = '';
var SelDest = '';
var SelResort = '';
var SelAccomm = '';
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,form)
{
   switch(elementid)
   {
      // Location
     case 'countryCode':
        if (SelCountry != 'Any')
        {
		   if(document.getElementById('countryCode')){
           SelectOptionByValue(document.getElementById('countryCode'), SelCountry);
           if (!noupdate) { DynamicUpdate(elementid,'change', 1, form) }
		   }
		   else{
                ShowSelection("destinationCode",'',form);
		   }
        }
        break;
     case 'destinationCode':
        if (SelLocation != 'Any')
        {
           SelectOptionByValue(document.getElementById('destinationCode'), SelLocation);
           if (!noupdate) { DynamicUpdate(elementid,'change', 1, form) }
        }
        break;

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

	 case 'resortAccomCode':

		if (SelResort != 'Any')
		{
			if (document.getElementById('departure').value == '')
			{
				if (SelAccomm != 'Any' && SelAccomm != '')
				{
					var resortAccommodationCode = SelResort+"|"+SelAccomm;
					SelectOptionByValue(document.getElementById('resortAccomCode'), resortAccommodationCode);
				}
				else
	      {
					SelectOptionByValue(document.getElementById('resortAccomCode'), SelResort);
				}
           if (!noupdate) { DynamicUpdate(elementid,'change', 1, form) }
		  }
		}
		   break;

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

         case 'departureAirportCode':
        if (SelAccomm != 'Any')
        {
           SelectOptionByValue(document.getElementById('departureAirportCode'), SelAirport);
           if (!noupdate) {     (elementid,'change', 1) }
        }
        break;
   }
}

// Save current selection
function SaveSelection()
{
	if(document.getElementById('countryCode')){
  SelCountry = document.getElementById('countryCode').value;
	}
	else{
		if(document.getElementById('countrySelected'))
		{
		SelCountry = document.getElementById('countrySelected').value;
		}
	}
  SelLocation = document.getElementById('destinationCode').value;
  SelResort = document.getElementById('resortCode').value;
  SelAccomm = document.getElementById('accommodationCode').value;
  SelAirport = document.getElementById('departureAirportCode').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 updateDestCodes(form)
{
	var countryDestCode = getElem("countryDestCode").value;
	var codeArray  = countryDestCode.split("|");
	getElem("countryCode").value = codeArray[0];
	getElem("destinationCode").value = codeArray[1];
	if (codeArray[1] || !isDestinationPresentForCountry())
	{
		if ((typeof(codeArray[1]) == "undefined"))
		{
			getElem("destinationCode").value="";
		}
		//turned off resorts update
		//DynamicUpdate('destinationCode','change',1, form);
	}
	else
	{
		getElem("destinationCode").value="";
		getElem("resortAccomCode").selectedIndex = 0;
		getElem("resortAccomCode").disabled=true;
	}
   getElem("resortCode").value = "";
   getElem("accommodationCode").value = "";
}


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

function DynamicUpdate(ElementID,ElementEvent,SaveFlag, form)
{
   //dynamic calls should be made only if the user has selected
   //a country. This is kill vanilla searches on FHPI.

	//updateDestCodes(getElem("countryCode").value);

   // 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 = getElem('calendar_day')
           FieldObjMonthYear1 = getElem('calendar_month_year')
           var arrDateSplit = FieldObjMonthYear1.value.split('/')
           dateVar = arrDateSplit[0] + "/" + FieldObjDay1.options[FieldObjDay1.selectedIndex].value + "/" + arrDateSplit[1];
           SaveSelection();
		   Params = 'selectedDate='+dateVar;

		   //var updateId = (document.getElementById('countryCode'))?'countryCode':'destinationCode';
            var updateId="countryDestCode";
           /*if (!PageLoad) {
			   if(!document.getElementById(updateId).disabled)
			   LoadDropDown(Params,'ShowSelection("'+updateId+'")',updateId);
		   //DynamicUpdate('countryCode','change',1)
           }*/
         }
         break;

      // Location - Selection changed / Key Up
      case 'moreDestinations_keyup':
      case 'moreDestinations_change':
         if (validateCheckInDate())
         {
            Params = 'moreDestinations=true';
            form.moreDestinations.value = "true";
            if (!PageLoad) { LoadDropDown(Params,'ShowSelection("destinationCode"),changeDropdownStyle("destinationCode","10")','destinationCode') }
              DynamicUpdate('destinationCode','change',1, form)
            }
            break;
      case 'nominalDestinations_keyup':
      case 'nominalDestinations_change':
         if (validateCheckInDate())
         {
            Params = 'moreDestinations=false';
            form.moreDestinations.value = "false";
            if (!PageLoad) { LoadDropDown(Params,'ShowSelection("destinationCode"),changeDropdownStyle("destinationCode","1")','destinationCode') }
              DynamicUpdate('destinationCode','change',1, form)
            }
            break;
      case 'moreResorts_keyup':
      case 'moreResorts_change':
         if (validateCheckInDate())
         {
            if (getElem("destinationCode").value!="")
            {
               form.moreResorts.value = "true";
               Params = 'moreResorts=true&destinationCode='+getValidDestinationCode(getElem("destinationCode").value);
               if (!PageLoad) { LoadDropDown(Params,'ShowSelection("resortAccomCode"),changeDropdownStyle("resortCode","10")','resortCode') }
                  DynamicUpdate('resortCode','change',1, form)
            }
         }
         break;
      case 'nominalResorts_keyup':
      case 'nominalResorts_change':
         if (validateCheckInDate())
         {
         if (getElem("destinationCode").value!="")
         {
            Params = 'moreResorts=false';
            form.moreResorts.value = "false";
            if (!PageLoad) { LoadDropDown(Params,'ShowSelection("resortCode"),changeDropdownStyle("resortCode","1")','resortCode') }
            DynamicUpdate('resortCode','change',1, form)
         }
         }
         break;
      // Location - Selection changed / Key Up
      case 'subtype_keyup':
      case 'subtype_change':
         if (validateCheckInDate())
         {
            Params = '';
            if (!PageLoad) { LoadDropDown(Params,'ShowSelection("countryCode")','countryCode') }
              DynamicUpdate('countryCode','change',1,form)
         }
         break;

      case 'countryCode_keyup':
      case 'countryCode_change':
         if (validateCheckInDate())
         {
            if (isany('countryCode'))
            {
                ElementAction('destinationCode','showany')
            }
            else
            {
               Params = 'countryCode='+getValidDestinationCode(getElem("countryCode").value);
               if (!PageLoad) { LoadDropDown(Params,'ShowSelection("destinationCode"),changeDropdownStyle("destinationCode","1")','destinationCode') }
            }
            if (form.moreResorts.value=="true")
            {
               updateListWithLocations('moreResortsLink','nominalResortsLink', 'moreResorts', form);
            }else{
            DynamicUpdate('destinationCode','change',1,form)
            }
         }
         break;
      // Location - Selection changed / Key Up
      case 'destinationCode_keyup':
      case 'destinationCode_change':
         if (validateCheckInDate())
         {
            if (isany('destinationCode') && isDestinationPresentForCountry())
            {
               ElementAction('resortAccomCode','showany')
            }
            else
            {
               Params = 'countryCode='+getValidDestinationCode(getElem("countryCode").value)+'&destinationCode='+getValidDestinationCode(getElem("destinationCode").value);
              if (!PageLoad) { LoadDropDown(Params,'ShowSelection("resortAccomCode"),changeDropdownStyle("resortAccomCode","1")','resortAccomCode') }
            }
            if (form.moreResorts.value=="true")
            {
                updateListWithLocations('moreResortsLink','nominalResortsLink', 'moreResorts', form);
            }else{
               DynamicUpdate('resortAccomCode','change',1,form)
            }
          }
         break;

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

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

}

function validateCheckInDate()
{
   FieldObjDay1 = getElem('calendar_day');
   FieldObjMonthYear1 = getElem('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;
   }

//moved this function to general.js wherein the check is
// done upon onclick of Search Button >> Bug# 18834
/*
   if (checkinDay.before(currentDateObj))
   {
      resetCheckInDate(currentDate);
   }
*/
   return true;
}

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

function getSelectedSubtype(form)
{
   for(var i=0;i<form.subtype.length;i++)
   {
      if (form.subtype[i].checked)
      {
         //return document.forms.frmSearchPanel.subtype[i].value;
         return
      }
   }
}

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

function DynamicUpdateInit(form)
{
   SaveSelection();
   if (form.moreDestinations.value=="true")
   {
      updateListWithLocations('moreDestinationsLink','nominalDestinationsLink', 'moreDestinations', form);
   }else{
    if(document.getElementById("countryCode"))
	   {
	  DynamicUpdate('countryCode','change','',form);
	 }
	 else
	   {
		   if(SelCountry=="")
		   {
			 // ElementAction('destinationCode','showany');
			  ElementAction('resortAccomCode','showany');
		   }
		   else{
			  DynamicUpdate('destinationCode','change','',form);
		   }
	   }
   }
   UpdateDayOfWeek();
  // ShowSelection("resortCode");
  // ShowSelection("accommodationCode");
   ShowSelection("departureAirportCode",'',form);
}

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

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

function updateCheckoutDate()
{
   var dateWrapper = Dates;
   var calendarDay = document.getElementById("calendar_day").value;
   var calendarMonthYear = document.getElementById("calendar_month_year").value;
   var numberOfNights = document.getElementById("duration").value;

   if(numberOfNights==''|| numberOfNights==null)
   {
      document.getElementById("duration").value=7;
      numberOfNights=7;
   }

   var date = (calendarDay+"/"+calendarMonthYear).split('/');
   var monthYear = calendarMonthYear.split('/');
   var departureDate = new Date(date[2], date[1]-1, date[0]);
   document.getElementById("departureDate").value=monthYear[1]+"-"+monthYear[0]+"-"+calendarDay;

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

   document.getElementById("checkOutDaySpan").innerHTML =  dateWrapper.shortDays[arrivalDate.getDay()] ;
   document.getElementById("checkOutDateSpan").innerHTML =  arrivalDate.getDate() ;
   document.getElementById("checkOutMonthYearSpan").innerHTML =  dateWrapper.shortMonths[arrivalDate.getMonth()] + " " + arrivalDate.getFullYear() ;

   document.getElementById("checkOutDisplayDay").value = arrivalDate.getDate() ;
   document.getElementById("checkOutDisplayMonth").value = dateWrapper.shortMonths[arrivalDate.getMonth()];
   var returnYear = ""+arrivalDate.getFullYear();

   document.getElementById("checkOutDisplayYear").value = returnYear.substring(2);
   document.getElementById("checkOutDay").value = arrivalDate.getDate();
   document.getElementById("checkOutMonthYear").value = (arrivalDate.getMonth()+1) + "/" + arrivalDate.getFullYear();

}


function updateALTCheckoutDate()
{
  var dateWrapper = Dates;
   var calendarDay = document.getElementById("calendar_day").value;
   var calendarMonthYear = document.getElementById("calendar_month_year").value;
   var numberOfNights = document.getElementById("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);
   }
   var durationInMS = numberOfNights * 86400000 + (timezoneOffset * 3600000);
   var arrivalDate = new Date(departureDate.getTime() + durationInMS);

   document.getElementById("checkOutDaySpan").innerHTML =  dateWrapper.shortDays[arrivalDate.getDay()] ;
   document.getElementById("checkOutDateSpan").innerHTML =  arrivalDate.getDate() ;
   document.getElementById("checkOutMonthYearSpan").innerHTML =  dateWrapper.shortMonths[arrivalDate.getMonth()] + " " + arrivalDate.getFullYear() ;

   document.getElementById("checkOutDisplayDay").value = arrivalDate.getDate() ;
   document.getElementById("checkOutDisplayMonth").value = dateWrapper.shortMonths[arrivalDate.getMonth()];
   var returnYear = ""+arrivalDate.getFullYear();

   document.getElementById("checkOutDisplayYear").value = returnYear.substring(2);
   document.getElementById("checkOutDay").value = arrivalDate.getDate();
   document.getElementById("checkOutMonthYear").value = (arrivalDate.getMonth()+1) + "/" + arrivalDate.getFullYear();
   // The below line seems unnecessary hence commenting it.
   // document.getElementById("duration").value = numberOfNights;
}



function setAltSearchCheckoutDate()
{

  var dateWrapper = Dates;
   var calendarDay = document.getElementById("calendar_day").value;
   var calendarMonthYear = document.getElementById("calendar_month_year").value;
   //var numberOfNights = document.getElementById("duration").value;

   var date = (calendarDay+"/"+calendarMonthYear).split('/');

   var departureDate = new Date(date[2], date[1]-1, date[0]);
   var arrivalDate = new Date(departureDate.getTime()+(numberOfNights * 86400000));

   document.getElementById("checkOutDaySpan").innerHTML =  dateWrapper.shortDays[arrivalDate.getDay()] ;
   document.getElementById("checkOutDateSpan").innerHTML =  arrivalDate.getDate() ;
   document.getElementById("checkOutMonthYearSpan").innerHTML =  dateWrapper.shortMonths[arrivalDate.getMonth()] + " " + arrivalDate.getFullYear() ;

   //document.getElementById("duration").value = numberOfNights;
   document.getElementById("checkOutDay").value = arrivalDate.getDate();
   document.getElementById("checkOutMonthYear").value = (arrivalDate.getMonth()+1) + "/" + arrivalDate.getFullYear();
}

function displayDate()
{

  var dateWrapper = Dates;
   var calendarDay = document.getElementById("calendar_day").value;
   var calendarMonthYear = document.getElementById("calendar_month_year").value;
   var numberOfNights = document.getElementById("duration").value;

   findDisplayDate(calendarDay, calendarMonthYear, "leaving")

   var date = (calendarDay+"/"+calendarMonthYear).split('/');

   var departureDate = new Date(date[2], date[1]-1, date[0]);
   var arrivalDate = new Date(departureDate.getTime()+(numberOfNights * 86400000));

   document.getElementById("checkOutDay").value = arrivalDate.getDate();
   document.getElementById("checkOutMonthYear").value = (arrivalDate.getMonth()+1) + "/" + arrivalDate.getFullYear();
   findDisplayDate(document.getElementById("checkOutDay").value, document.getElementById("checkOutMonthYear").value, "returning")
}

function findDisplayDate(calendarDay, calendarMonthYear, cond)
{
   if (calendarDay<10)
   {
      var displayDay = "0"+ calendarDay;
   }
   else
   {
       var displayDay = calendarDay;
   }

    var monthYear = calendarMonthYear.split('/');
    var month = monthYear[0];
    var year = monthYear[1];
    var displayMonth;
    var displayYear;
    if (month == 1)
    {
       displayMonth = "Jan"
    }
    if (month == 2)
    {
       displayMonth = "Feb"
    }
    if (month == 3)
    {
       displayMonth = "Mar"
    }
    if (month == 4)
    {
       displayMonth = "Apr"
    }
    if (month == 5)
    {
       displayMonth = "May"
    }
    if (month == 6)
    {
       displayMonth = "Jun"
    }
    if (month == 7)
    {
       displayMonth = "Jul"
    }
    if (month == 8)
    {
       displayMonth = "Aug"
    }
    if (month == 9)
    {
       displayMonth = "Sep"
    }
    if (month == 10)
    {
       displayMonth = "Oct"
    }
    if (month == 11)
    {
       displayMonth = "Nov"
    }
    if (month == 12)
    {
       displayMonth = "Dec"
    }
    var displayYear = year.substring(2);

    if (cond=="leaving")
    {
       document.getElementById("displayDay").value = displayDay;
       document.getElementById("displayMonth").value = displayMonth;
       document.getElementById("displayYear").value = displayYear;
	   //Departure date set in the format - yyyy-MM-dd as it is the accepted format in other flows like deeplink flow etc.
	   document.getElementById("departureDate").value = year + "-" + month + "-" + displayDay;
    }
    if (cond == "returning")
    {
       document.getElementById("checkOutDisplayDay").value = displayDay;
       document.getElementById("checkOutDisplayMonth").value = displayMonth;
       document.getElementById("checkOutDisplayYear").value = displayYear;
    }
}

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

function calculateDateDifference()
{
   FieldObjDay2 = getElem('calendar_day')
   FieldObjMonthYear2 = getElem('calendar_month_year')

   var calendarDay = document.getElementById("calendar_day").value;
   var calendarMonthYear = document.getElementById("calendar_month_year").value;


   var date = (calendarDay+"/"+calendarMonthYear).split('/');
   var deptDate = new Date(date[2], date[1]-1, date[0]);

   var date = (calendarDay+"/"+calendarMonthYear).split('/');
   var returnDate = new Date(date[2], date[1]-1, date[0]);

	//Set 1 day in milliseconds
	//var one_day=1000*60*60*24
	//var no_of_days = Math.ceil((returnDate.getTime()-deptDate.getTime())/(one_day));
	//getElem('long_duration').innerHTML = null;
   //getElem('duration').innerHTML = no_of_days;
   document.getElementById("checkOutDisplayDay").value = calendarDay;
   document.getElementById("checkOutDisplayMonth").value = Dates.shortMonths[date[1]-1];
   document.getElementById("checkOutDisplayYear").value = date[2].substring(2);

   document.getElementById("checkOutDay").value = FieldObjDay2.options[FieldObjDay2.selectedIndex].value;
   document.getElementById("checkOutMonthYear").value = FieldObjMonthYear2.options[FieldObjMonthYear2.selectedIndex].value;
}


function SetWeekDay() {

   var days_of_week = new Array('Sun','Mon','Tue','Wed','Thu','Fri','Sat');
   FieldObjDay2 = getElem('calendar_day')
   FieldObjMonthYear2 = getElem('calendar_month_year')

   var arrDateSplit = FieldObjMonthYear2.value.split('/')
   dateVar = arrDateSplit[0] + "/" + FieldObjDay2.options[FieldObjDay2.selectedIndex].value + "/" + arrDateSplit[1];
   var Calendar = new Date(dateVar);
   Calendar.setMonth(arrDateSplit[0]-1);
   Calendar.setYear(arrDateSplit[1]);
   Calendar.setDate(FieldObjDay2.options[FieldObjDay2.selectedIndex].value);

   if (FieldObjDay2.options[FieldObjDay2.selectedIndex].value==Calendar.getDate())
   {
      getElem('calendar_dow').innerHTML = days_of_week[Calendar.getDay()]
   }
   else
   {
      FieldObjDay2.selectedIndex = FieldObjDay2.selectedIndex - 1;
      if(Calendar.getMonth()==2)
      {
          SetWeekDay();
      }
   }
   document.getElementById("checkOutDay").value = FieldObjDay2.options[FieldObjDay2.selectedIndex].value;
   document.getElementById("checkOutMonthYear").value = FieldObjMonthYear2.options[FieldObjMonthYear2.selectedIndex].value;
}


//Added to fix #6274 - 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');
}

// Date-handling
var Dates = {
  monthsPerYear: 12,
  hoursPerDay: 24,
  minutesPerDay: 24 * 60,
  millisPerDay: 24 * 60 * 60 * 1000,
  millisPerHour: 60 * 60 * 1000,
  millisPerMinute: 60 * 1000,
  millisPerSecond: 1000,
  days: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
  shortDays: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'],
  months: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
  shortMonths: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
  fromISO: function(s) {
    /* y-m-d h:m:s format (iso-8601) */
    var a = s.split(' ');
    var ymd = a[0].split('-');
    var y = +ymd[0];
    var mon = ymd.length > 1 ? +ymd[1] : 1;
    var d = ymd.length > 2 ? +ymd[2] : 1;
    if (a.length == 1) {
      return new Date(y, mon - 1, d);
    } else {
      var hms = a[1].split(':');
      var h = +hms[0];
      var min = hms.length > 1 ? +hms[1] : 0;
      var sec = hms.length > 2 ? +hms[2] : 0;
      return new Date(y, mon - 1, d, h, min, sec);
    }
  },
  fromSlashed: function(s) {
    /* d/m/y format */
    var a = s.split('/');
    var y = +a[2];
    var m = +a[1];
    var d = +a[0];
    return (a.length == 3) ? new Date(y < 1900 ? y + 1900 : y, m - 1, d) : null;
  },
  date: function(o) {
    var date = null;
    if (o instanceof Date) { date = o }
    else if (typeof o == 'number') { date = new Date(o) }
    else if (typeof o == 'string') {
      if (o.indexOf('/') > 0) {
        date = this.fromSlashed(o);
      } else {
        date = this.fromISO(o);
      }
    }
    return date;
  },
  ord: function(date, precision) {
    date = this.date(date);
    precision = precision || 3;
    var tz = date.getTimezoneOffset() * this.millisPerMinute;
    switch (precision) {
      case 1: return date.getFullYear();
      case 2: return date.getFullYear() * this.monthsPerYear + date.getMonth();
      case 3: return Math.floor((date.getTime() - tz) / this.millisPerDay);;
      case 4: return Math.floor((date.getTime() - tz) / this.millisPerHour);
      case 5: return Math.floor((date.getTime() - tz) / this.millisPerMinute);
      case 6: return Math.floor((date.getTime() - tz) / this.millisPerSecond);
      default: return date.getTime();
    }
  },
  diff: function(from, to, precision) {
    return this.ord(to, precision) - this.ord(from, precision);
  },
  millis: function(o) {
    return this.date(o).getTime();
  },
  day: function(o) {
    return this.ord(o);
  },
  dayName: function(o, length) {
    return this.days[this.date(o).getDay()].substr(0, length || 3);
  },
  monthName: function(o, length) {
    return this.months[this.date(o).getMonth()].substr(0, length || 3);
  },
  monthStart: function(date) {
    date = this.date(date);
    return new Date(date.getFullYear(), date.getMonth(), 1);
  },
  monthEnd: function(date) {
    date = this.date(date);
    return new Date(date.getFullYear(), date.getMonth() + 1, 0);
  },
  iso: function(date, fields) {
    function nn(n) {
      return (n < 0 || n > 9) ? String(n) : '0' + String(n);
    }
    fields = fields || 3;
    date = this.date(date);
    var s = nn(date.getFullYear());
    if (--fields > 0) s += '-' + nn(date.getMonth() + 1);
    if (--fields > 0) s += '-' + nn(date.getDate());
    if (--fields > 0) s += ' ' + nn(date.getHours());
    if (--fields > 0) s += ':' + nn(date.getMinutes());
    if (--fields > 0) s += ':' + nn(date.getSeconds());
    return s;
  },
  inRange: function(date, start, end) {
    return this.day(date) < this.day(start) ? -1 :
      this.day(date) > this.day(end) ? 1 :
      0;
  }
};
Date.prototype.before = function(that, precision) { return Dates.diff(this, that, precision) > 0 }
Date.prototype.after  = function(that, precision) { return Dates.diff(this, that, precision) < 0 }
Date.prototype.within  = function(start, end) { return Dates.inRange(this, start, end) == 0 }
String.prototype.before = function(that, precision) { return Dates.date(String(this)).before(that, precision) }
String.prototype.after  = function(that, precision) { return Dates.date(String(this)).after(that, precision) }
String.prototype.within  = function(start, end) { return Dates.inRange(String(this), start, end) == 0 }

function isDestinationPresentForCountry()
{
   var currentCount = document.getElementById("countryDestCode").selectedIndex;
   if (currentCount == 0)
   {
	   return true;
   }
   currentCount = currentCount + 1;
	var nextComboValue = "";
	if(document.getElementById("countryDestCode").options[currentCount])
	{
		nextComboValue = document.getElementById("countryDestCode").options[currentCount].value;
	}
    var checkDestination = nextComboValue.split("|");
	var flag = true;
	if (typeof(checkDestination[1]) == "undefined")
	{
		flag = false;
	}
	return flag;
}
