// Dynamic Location
/* Modifications to this file need to be implemented in the same way
   in the sprocket_dynamic_location.js file. */

var SelBrochure = '';
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 jsCall = (navigator.userAgent.indexOf("MSIE") != -1)? "parent." : "";
var isIE= (navigator.userAgent.indexOf("MSIE") != -1) ? true : false;

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) {
  // Brochure
  case 'SearchBrochure':
   if (SelBrochure != 'Any') {
    SelectOptionByValue($('SearchBrochure'), SelBrochure);
    if (!noupdate) { DynamicUpdate(elementid,'change', 1) }
   }
   break;

  // Airport
  case 'SearchAirport':
   if (SelAirport != 'Any') {
    SelectOptionByValue($('SearchAirport'), SelAirport);
    if (!noupdate) { DynamicUpdate(elementid,'change', 1) }
   }
   break;

  // Location
  case 'SearchLocation':
   if ((SelCountry != 'Any') || (SelDest != 'Any')) {
    objSel = getElem('SearchLocation')
    for (z=0;z<objSel.length;z++) {
     arrThisLocation = objSel.options[z].value.split(',')
     // Check a country code is specified
     if (arrThisLocation.length < 2) {
      arrThisLocation[1] = arrThisLocation[0]
     }
     // Destination
     if (arrThisLocation[1] != null) {
      if (arrThisLocation[1] == SelDest) {
       objSel.selectedIndex = z;
      }
     } else {
      // Country
      if (arrThisLocation[0] == SelCountry) { objSel.selectedIndex = z; }
     }
    }
    if (!noupdate) { DynamicUpdate(elementid,'change', 1) }
   }
   break;

  // Resort
  case 'SearchResort':
   if (SelResort != 'Any') {
    SelectOptionByValue($('SearchResort'), SelResort);
    if (!noupdate) { DynamicUpdate(elementid,'change', 1) }
   }
   break;

  // Accommodation
  case 'SearchAccommodation':
   if (SelAccomm != 'Any') {
    SelectOptionByValue($('SearchAccommodation'), SelAccomm);
   }
   break;

  // Duration
  case 'SearchDuration':
     if (SelDuration != 'Any') {
        SelectOptionByValue($('SearchDuration'), SelDuration);
        if (!noupdate) { DynamicUpdate(elementid,'change', 1) }
     }
    break;

/* Cruise related case statement start here */
  case 'departureMonth':
   SelectOptionByValue($('departureMonth'), SelDepartureMonth);
   if (!noupdate) { DynamicUpdate(elementid,'change', 1) }
   break;

  case 'shipOrShipArea':
   if (SelShipOrShipArea != 'Any') {
    SelectOptionByValue($('shipOrShipArea'), SelShipOrShipArea);
    if (!noupdate) { DynamicUpdate(elementid,'change', 1) }
   }
   break;

  case 'itinerary':
   if (SelItinerary != 'Any') {
    SelectOptionByValue($('itinerary'), SelItinerary);
    if (!noupdate) { DynamicUpdate(elementid,'change',1) }
   }
   break;

  case 'departureAirport':
   if (SelDepartureAirport != 'Any') {
    SelectOptionByValue($('departureAirport'), SelDepartureAirport);
   }
   break;

  case 'departurePoint':
   if (SelDeparturePoint != 'Any') {
    SelectOptionByValue($('departurePoint'), SelDeparturePoint);
   }
   break;

  case 'duration':
   if (SelDuration != 'Any') {
    SelectOptionByValue($('duration'), SelDuration);
   }
   break;
 }
}

// Save current selection
function SaveSelection(productType) {
 if (productType == 'CRUISE') {
  if (selectedCruiseType() != 'Any') { SelCruiseType = selectedCruiseType() }
  if ($F('departureMonth') != 'Any') { SelDepartureMonth = $F('departureMonth') }
  if ($F('duration') != 'Any') { SelDuration = $F('duration') }
  if ($F('shipOrShipArea') != 'Any') { SelShipOrShipArea = $F('shipOrShipArea') }
  if ($F('itinerary') != 'Any') { SelItinerary = $F('itinerary') }
 } else {
  SelBrochure = $F('SearchBrochure');
  SelResort = $F('SearchResort');
  SelAccomm = $F('SearchAccommodation');
  SelDuration = $F('SearchDuration');
  SelAirport = $F('SearchAirport');
  var countryDest = $F('SearchLocation').split(',');
  // Check a country code is specified
  if (countryDest.length < 2) {
   SelCountry = '';
   SelDest = countryDest[0]
  } else {
   SelCountry = countryDest[0]
   SelDest = (!countryDest[1]) ? '' : countryDest[1]
  }
 }
}

/**
 * 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) {
 if (!PageLoad) {
 	// Start: Bug-32115 /Remedy-328768 :This variable and condition is added to disable the selection of children on Cruise for the
// ship type as The Calypso which allows only adults
 	if(window.productType == 'CRUISE'){
 	if(ElementID == "shipOrShipArea")
	{
 		var tempShip = document.getElementById(ElementID).value.split(",");
	}
 	if (ElementID == "itinerary" && (tempShip[1] == '150005'))
   	{
   		document.getElementById("NoChildren").disabled = true;
   		document.getElementById("NoInfants").disabled = true;
   		document.getElementById("popupImage").style.display = "block";
   		return false;
   	}
   	 else if (ElementID == "departureAirport" && (tempShip[1] == '150005'))
   	{
   		document.getElementById("NoChildren").disabled = true;
   		document.getElementById("NoInfants").disabled = true;
   		document.getElementById("popupImage").style.display = "block";
   		return false;
   	}

   	 else if (ElementID == "duration" && (tempShip[1] == '150005'))
   	{
   		document.getElementById("NoChildren").disabled = true;
   		document.getElementById("NoInfants").disabled = true;
   		document.getElementById("popupImage").style.display = "block";
   		return false;
   	}
 	 else if (ElementID == "shipOrShipArea" && (tempShip[1] == '150005'))
   	{
   		document.getElementById("NoChildren").value = 0;
   		document.getElementById("NoInfants").value = 0;
   		document.getElementById("childagesrow").style.display = "none";
   		document.getElementById("NoChildren").disabled = true;
   		document.getElementById("NoInfants").disabled = true;
   		document.getElementById("popupImage").style.display = "block";
   		if (document.getElementById("infants") != undefined)
   		{
   			document.getElementById("infants").style.marginLeft= "-25px";
   			document.getElementById("popupImage").style.marginLeft = "5px";
   		}
   		return false;
   	}

   	else
   	{
   		document.getElementById("NoChildren").disabled = false;
   		document.getElementById("NoInfants").disabled = false;
   		document.getElementById("popupImage").style.display = "none";
   		document.getElementById("infoPopup").style.display = "none";
   		if (document.getElementById("infants") != undefined)
   		{
   			document.getElementById("infants").style.marginLeft= "4px";
   			document.getElementById("popupImage").style.marginLeft = "5px";
   		}
   	}
}
//End: Bug-32115 /Remedy-328768

  if (window.productType == 'BEACH') {
   // when search panel retains its brochure code
   if ($F('SearchBrochure') =='ANY') {
    if ($F('productType') == '0') {
     alert('Please select the type of holiday you wish to find before searching');
     if (ElementID == 'calendar_day') {
      $(ElementID).selectedIndex = Calendar.getDate();
     } else {
      ElementAction(ElementID, 'selectany');
     }
     return;
    }
   }
  }
 }

 // Identify if current search selection codes should be saved
 var SaveCodes = (SaveFlag != 1);

 if (ElementID) {
  ElementEvent = ElementID + '_' + ElementEvent
 }

    switch(ElementEvent) {
     case 'calendar_day_keyup':
     case 'calendar_day_change':
     case 'calendar_month_year_keyup':
     case 'calendar_month_year_change':
        if (!PageLoad) {
		     if (CheckValidDepartureDate()) {
                    if (SaveCodes && !PreviousDateInvalid) { SaveSelection() }
                    PreviousDateInvalid = false;
          Params = 'Date='+getElem("calendar_day").value + "/" + getElem("calendar_month_year").value
          LoadDropDown(Params,'ShowSelection("SearchAirport",true);ShowSelection("SearchBrochure");','SearchBrochure','SearchAirport')
              } else {
		    ElementAction('SearchLocation','showdatemessage')
            ElementAction('SearchResort','showany')
            ElementAction('SearchAccommodation','showany')
                    PreviousDateInvalid = true;
                }
          } else {
		    DynamicUpdate('SearchBrochure','change',1)
            }
         break;

     case 'SearchAirport_keyup':
     case 'SearchAirport_change':
     case 'SearchBrochure_keyup':
     case 'SearchBrochure_change':
        if (!PageLoad) {
                if (CheckValidDepartureDate()) {
                    if (SaveCodes && !PreviousDateInvalid) { SaveSelection() }
                    PreviousDateInvalid = false;
          Params = 'Airport='+getElem("SearchAirport").value+'&BrochureCode='+ getElem("SearchBrochure").value +'&SearchDuration='+getElem("SearchDuration").value;
          if (ElementID == 'SearchBrochure') {
              // Load durations
                        LoadDropDown(Params,'ShowSelection("SearchDuration");ShowSelection("SearchLocation");','','SearchLocation','SearchDuration')
                        } else {
                        // dont load durations
                        LoadDropDown(Params,'ShowSelection("SearchLocation")','','SearchLocation')
                        }
              } else {
            ElementAction('SearchLocation','showdatemessage')
            ElementAction('SearchResort','showany')
            ElementAction('SearchAccommodation','showany')
                    PreviousDateInvalid = true;
                }
          } else {
        DynamicUpdate('SearchLocation','change',1)
            }
     break;

     // Location - Selection changed / Key Up
     case 'SearchLocation_keyup':
     case 'SearchLocation_change':

        if (isany('SearchLocation'))
        {
        ElementAction('SearchResort','showany')
        getElem('SearchCountry').value = 'Any';
        getElem('SearchDestination').value = 'Any';
        }
        else
        {
                    if (SaveCodes && !PreviousDateInvalid) { SaveSelection() }
          var codes = getElem("SearchLocation").value.split(',')

                if (codes.length == 1)
          {
              getElem('SearchCountry').value = codes[0]
              getElem('SearchDestination').value = 'Any'
          }
          else
          {
              getElem('SearchCountry').value = codes[0]
              getElem('SearchDestination').value = codes[1]
          }

          Params = 'Country='+getElem("SearchCountry").value

           if (getElem("SearchDestination").value != '')
           {
              Params += "&Destination=" + getElem("SearchDestination").value
           }

            if (!PageLoad) { LoadDropDown(Params,'ShowSelection("SearchResort")','SearchResort') }
        }
      DynamicUpdate('SearchResort','change',1)
      break;

     // Resort - Selection changed / Key Up
     case 'SearchResort_keyup':
     case 'SearchResort_change':
        if (isany('SearchResort')) {
        ElementAction('SearchAccommodation','showany')
         } else {
          Params = 'Resort='+getElem("SearchResort").value
            if (!PageLoad) { LoadDropDown(Params,'ShowSelection("SearchAccommodation")','SearchAccommodation') }
         }
      DynamicUpdate('SearchAccommodation','change',1)
     break;

     case 'SearchAccommodation_keyup':
     case 'SearchAccommodation_change':
            if (!isany('SearchAccommodation')) {
                //if (!PreviousDateInvalid) {   SaveSelection() }
}
     break;

//cruise related case statements
     //cruise related code
     case 'cruiseType_keyup':
     case 'cruiseType_change':
        splitShipShipArea();
        Params = 'cruiseType='+selectedCruiseType()+'&selected=cruiseType';
        if (!PageLoad){
            LoadDropDown(Params, 'ShowSelection("departureMonth",false)','departureMonth');
        }
    SaveSelection("CRUISE");
    break;

     case 'departureMonth_keyup':
     case 'departureMonth_change':
        SelShipOrShipArea = "";
        shipId = "Any";
        cruiseAreaId = "Any";
        convertDepatureDate();
        splitShipShipArea();
        Params = 'departureDay='+getElem("day").value+'&departureMonth='+getElem("departureMonth").value+'&cruiseType='+selectedCruiseType()+'&selected=departureMonth';

        if (!PageLoad){
            if (CheckCruiseDepartureDate("load") && checkForPeriodGaps())
            {
                getElem("duration").disabled = false;
                LoadDropDown(Params, 'ShowSelection("shipOrShipArea",false);','shipOrShipArea');
            }
            else
            {
               if (!CheckCruiseDepartureDate("load"))
               {
                   ElementAction('shipOrShipArea','showdatemessage');
               }else if (!checkForPeriodGaps()){
                   ElementAction('shipOrShipArea','shownoavailabilitymessage');
               }
               getElem("duration").disabled = true;
               ElementAction('itinerary','showany')
               ElementAction('departureAirport','showany')
               ElementAction('departurePoint','showany')

            }
        }
    SaveSelection("CRUISE");
    break;

     case 'duration_keyup':
     case 'duration_change':
        splitShipShipArea();
        Params = 'cruiseType='+selectedCruiseType()+'&departureMonth='+getElem("departureMonth").value+'&duration='+getElem("duration").value+'&shipCode='+getElem("shipId").value+'&areaId='+getElem("cruiseAreaId").value+'&selected=duration';
        if (!PageLoad){
            LoadDropDown(Params, 'ShowSelection("itinerary",false)','itinerary');
        }
    SaveSelection("CRUISE");
    break;

     case 'shipOrShipArea_keyup':
     case 'shipOrShipArea_change':
        SelItinerary = "";
        SelDepartureAirport = "";
        SelDeparturePoint = "";
        splitShipShipArea();
        Params = 'cruiseType='+selectedCruiseType()+'&departureMonth='+getElem("departureMonth").value+'&duration='+getElem("duration").value+'&shipCode='+getElem("shipId").value+'&areaId='+getElem("cruiseAreaId").value+'&selected=shipOrShipArea';
        if (!PageLoad){
            LoadDropDown(Params, 'ShowSelection("itinerary",false);','itinerary');
        }
    SaveSelection("CRUISE");
    break;

     case 'itinerary_keyup':
     case 'itinerary_change':
        SelDepartureAirport = "";
        SelDeparturePoint = "";
        splitShipShipArea();
        Params = 'cruiseType='+selectedCruiseType()+'&departureMonth='+getElem("departureMonth").value+'&duration='+getElem("duration").value+'&shipCode='+getElem("shipId").value+'&areaId='+getElem("cruiseAreaId").value+'&itinerary='+getElem("itinerary").value+'&selected=itinerary';
        if (!PageLoad){

            if (selectedCruiseType()=="CRF"){
                LoadDropDown(Params, 'ShowSelection("departureAirport",true);','departureAirport');
            }else{
                LoadDropDown(Params, 'ShowSelection("departurePoint",true);','departurePoint');
            }
        }
    SaveSelection("CRUISE");
    break;
     }
        if ((ElementID == 'calendar_day') || (ElementID == 'calendar_month_year')) {
         if (CheckValidDepartureDate()) { UpdateDayOfWeek() }
         }
}

function DynamicUpdateInit(searchType) {
// Start: Bug-32115 /Remedy-328768 :To disable the child menu on search result page for ship type Calypso
//as it is an adult only ship
 if (window.productType=="CRUISE")
 {
	var shipCode=document.getElementById("shipOrShipArea").value.split(",");
	if(shipCode[1]=='150005')
	{
		document.getElementById("NoChildren").disabled = true;
		document.getElementById("NoInfants").disabled = true;
   		document.getElementById("popupImage").style.display = "block";
		if (document.getElementById("infants") != undefined)
			document.getElementById("infants").style.marginLeft= "-20px";
		return false;
	}
	if (document.getElementById("infants") != undefined)
		document.getElementById("infants").style.marginLeft= "4px";
 }
 // End: Bug-32115 /Remedy-328768

 PageLoad = true;
 if (window.productType=="BEACH")
 {
   //If search type is Content Search, Sun Holidays is selected by default as Holiday Type
   if (searchType=="CONTENT")
   {
   objSel = $('productType');
   for (z=0;objSel && z<objSel.length;z++)
   {
     if (objSel.options[z].value.indexOf('home|getHomePage') != -1)
           {
            objSel.selectedIndex = z;
           }
        }
   }
   if (document.location.search.indexOf ('tvp=true') != -1)
   {
   //checks if the selected option contains the word 'showVillaHomePage' which reflects VILLAS
      objSel = $('productType');
      for (z=0;objSel && z<objSel.length;z++)
      {
         if (objSel.options[z].value.indexOf('showVillaHomePage') != -1)
         {
           objSel.selectedIndex = z;
         }
         }
      }
      else
      {
         setHoliday();
         setBrochure();
      }
      DynamicUpdate('SearchLocation','change');
      UpdateDayOfWeek();
}
 else
 {
    PageLoad = false;
    if(periodArray.length>0)
    {
        if (searchType!="ALTSEARCH")
        {
           hideDepartureAirportOption();
        }

        if (getElem("departureAirport").length<=1 && selectedCruiseType()=="CRF")
        {
            DynamicUpdate('departureMonth','change',1);
        }

        if ( (getElem("departurePoint").length==1) && (getElem("departurePoint").value=='Any') && (selectedCruiseType()=="CRU" || selectedCruiseType()=="XUK"))
        {
            DynamicUpdate('departureMonth','change',1);
        }

        SelDepartureMonth = getElem("departureMonth").value;

            if (!(CheckCruiseDepartureDate("load") && checkForPeriodGaps()))
            {
               if (!CheckCruiseDepartureDate("load"))
               {
                   ElementAction('shipOrShipArea','showdatemessage');
               }else if (!checkForPeriodGaps()){
                   ElementAction('shipOrShipArea','shownoavailabilitymessage');
               }
               getElem("duration").disabled = true;
               ElementAction('itinerary','showany')
               ElementAction('departureAirport','showany')
               ElementAction('departurePoint','showany')
            }
      }
}
   PageLoad = false;
}

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()]
   }
   else
   {
      FieldObjDay1.selectedIndex = FieldObjDay1.selectedIndex - 1;
   }
}

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;
       }
     }
 }

//Added to fix #6274 - reset brochure 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');
}

//Bug 32115 start:
function showInfoPopup(value)
{
	var popupText = '<div class="rowDiv leftAln" style="width:136px;">&nbsp;</div><div class="colDiv">&nbsp;</div><div class="colDiv ritaln" onclick="'+jsCall+'closePopup();" style="padding-top:5px;"><a href="javascript:void(0);" onclick="'+jsCall+'closePopup();"><img src="/th/common/images/icons/close.gif" border="0" onclick="'+jsCall+'closePopup();"/></a></div><br /><div class="rowDiv leftAln normalText" style="padding:3px;">The Calypso is reserved exclusively for adults. Children 16yrs and under are not accepted.</div>';
	document.getElementById("infoPopup").style.display = "block";
	if (isIE)
	{
		document.getElementById("infoPopup").innerHTML='<iframe id=\'popupframe\' name=\'popupframe\' src=\'javascript:"dynamic_location"\' scrolling=\'no\' marginheight=\'0\' marginwidth=\'0\' frameborder=\'0\'></iframe>';
		calCSS = "<link rel='STYLESHEET' type='text/css' href='"+document.getElementById("searchPanelCSS").href+"' />";
		o_califrame = document.getElementById("popupframe");
		popupframe.document.open();
		popupframe.document.write("<html><head>"+calCSS+"</head><body id='infoPopup'></body></html>");
		popupframe.document.close();
	}
	calBody = (isIE) ? popupframe.document.getElementById("infoPopup") : document.getElementById("infoPopup");
	calBody.innerHTML = popupText;
	var posX = 0;
	var posY = 0;
	if (value == "search")
	{
		posX = findPosX(document.getElementById("childColumn"));
		posY = findPosY(document.getElementById("childColumn"));
		document.getElementById("infoPopup").style.left = (posX-51)+"px";
		document.getElementById("infoPopup").style.top = (posY+40)+"px";
	}
	else
	{
		posX = findPosX(document.getElementById("children"));
		posY = findPosY(document.getElementById("children"));
		document.getElementById("infoPopup").style.left = (posX-24)+"px";
		document.getElementById("infoPopup").style.top = (posY+50)+"px";
	}
}

function closePopup()
{
	document.getElementById("infoPopup").style.display = "none";
}

function findPosX(obj)
{
	var curleft = 0;
	if(obj.offsetParent)
		while(1)
		{
			curleft += obj.offsetLeft;
			if(!obj.offsetParent)
			break;
			obj = obj.offsetParent;
		}
	else if(obj.x)
		curleft += obj.x;
	return curleft;
}

function findPosY(obj)
{
	var curtop = 0;
	if(obj.offsetParent)
		while(1)
		{
			curtop += obj.offsetTop;
			if(!obj.offsetParent)
			break;
			obj = obj.offsetParent;
		}
	else if(obj.y)
		curtop += obj.y;
	return curtop;
}
//Bug 32115 End: