
// Shows/Hides Children Ages and FREE child place option
function RedrawChildren() {
   //if (!checkPartySize()) return;
   if (getElem('NoChildren')) {
   no_of_children = parseInt(getElem('NoChildren').value);
   // No children selected > 0
  if (no_of_children > 0) {
      strHTML = '<div id="childdiv">';
      getElem('childagesrow').style.display = 'block';
      // Loop round all children
   for (i=1;i<no_of_children+1;i++) {
         var childage = parseInt(document.getElementsByName("searchCriteria.childAges["+(i-1)+"]")[0].value,10)
         strHTML += '<div class="childage">Child '+ i +'<select id="child'+ (i-1) +'" name="child'+ (i-1) +'">'
      // Generate Options for Dropdowns - select current age
     for (age=2;age<13;age++) {
       strHTML += '<option '
       if (childage == age) strHTML += ' selected '
          strHTML += ' value="'+age+'">'+age+'</option>'
     }
   strHTML += '</select></div>\n'
   }
      strHTML += '</div>'
      getElem('childages').innerHTML = strHTML
   } else {
     // No children selected is 0
     getElem('childagesrow').style.display = 'none'
  }
   }
}

// Checks for Maximum party size and no. of adults >= no. of infants
function CheckPassengerQty() {
   NoAdults   = parseInt(getElem('NoAdults').value,10)
   NoChildren = parseInt(getElem('NoChildren').value,10)
   NoInfants  = parseInt(getElem('NoInfants').value,10)
   if ((NoAdults + NoChildren) > 9 ) {
      alert('Your total party size must be 9 passengers or fewer')
      return false;
   }
   tooManyInfants = false;
   if (NoInfants > NoAdults) {
     grownUps = NoAdults
     no_of_children = parseInt(getElem('NoChildren').value)
     if( no_of_children > 0 ) {
       for (i=1; i < no_of_children+1;i++) {
          age = parseInt(getElem('child' + (i-1)).value)
          if( age > 11 ) {
             grownUps++
          }
       }
     }
     tooManyInfants = ( grownUps < NoInfants )
   }
   if( tooManyInfants ) {
      alert('There must be at least one passenger aged 12 or over for each infant travelling')
      return false;
   }
   return true;
}

// Checks for Maximum party size and no. of adults >= no. of infants
function CheckPassengerQtyARA(obj) {
   var tempPax;
   if(obj) { tempPax = obj.name.substring(obj.name.indexOf("].")+2,obj.name.length); }
   else { tempPax = 'adults'; }

   for(i=0;i<document.forms[0].elements["searchCriteria.roomConfigurationFormBean.numberOfRooms"].value;i++) {
   if (document.forms[0].elements["searchCriteria.roomConfigurationFormBean.rooms[" + i + "].adults"]) {
      NoAdults   = parseInt(document.forms[0].elements["searchCriteria.roomConfigurationFormBean.rooms[" + i + "].adults"].value,10);
      NoChildren = parseInt(document.forms[0].elements["searchCriteria.roomConfigurationFormBean.rooms[" + i + "].children"].value,10);
      NoInfants  = parseInt(document.forms[0].elements["searchCriteria.roomConfigurationFormBean.rooms[" + i + "].infants"].value,10);

      if ((NoAdults + NoChildren) > 9 ) {
         alert('Your total party size must be 9 passengers or fewer for Room '+ (i+1));
         if(tempPax == 'adults') tempSel = 9-NoChildren-1;
         if(tempPax == 'children') tempSel = 9-NoAdults;
         document.forms[0].elements["searchCriteria.roomConfigurationFormBean.rooms[" + i + "]."+tempPax].selectedIndex = tempSel;
         if(tempPax == 'children')
            redrawChildAges(document.forms[0].elements["searchCriteria.roomConfigurationFormBean.rooms[" + i + "]."+tempPax]);
         return;
      }

        tooManyInfants = false;
        childAgesDrawn = true;
        if (NoInfants > NoAdults) {
           grownUps = NoAdults;
           no_of_children = parseInt(document.forms[0].elements["searchCriteria.roomConfigurationFormBean.rooms[" + i + "].children"].value);
           if( no_of_children > 0 ) {
              for (j=0; j < no_of_children;j++) {
               if(document.forms[0].elements["searchCriteria.roomConfigurationFormBean.rooms[" + i + "].childAge[" + j + "]"])
               {
                 age = parseInt(document.forms[0].elements["searchCriteria.childAges[" + j + "]"].value)
                 if( age > 11 ) {
                    grownUps++;
                 }
              }
              else
              {
                 childAgesDrawn = false;
              }
              }
           }
           tooManyInfants = ( grownUps < NoInfants );
        }
        if( tooManyInfants && childAgesDrawn) {
         return SetFocus('There must be at least one passenger aged 12 or over for each infant travelling', document.forms[0].elements["searchCriteria.roomConfigurationFormBean.rooms[" + i + "].adults"]);
        }
     }
   }
   return true;
}


// Checks departure date is within specified limits
function CheckDepartureDate() {
  SearchSelectedDate = getElem('calendar_day').value + '/' + getElem('calendar_month_year').value

  if (!CheckValidDate(SearchSelectedDate)) return false;

     if (!CheckValidDepartureDate()) {

        if (DateValue(SearchSelectedDate) < DateValue(dteMinDeparture)) {

           if(DateValue(SearchSelectedDate) < DateValue(periodStartDate)) {

              alert('Please select a departure date on or after ' + periodStartDate)
              SetDepartureDate(periodStartDate)
              DynamicUpdate('calendar_day','change');
              return false
            } else {

               alert('Please select a departure date on or after ' + dteMinDeparture)
               // Set Minimum Date in fields
               SetDepartureDate(dteMinDeparture)
               DynamicUpdate('calendar_day','change');
               return false
            }

        } else {

            var count = 0;
            if(DateValue(SearchSelectedDate) < DateValue(periodStartDate)) {
               alert('Please select a departure date on or after ' + periodStartDate)
               SetDepartureDate(periodStartDate)
               DynamicUpdate('calendar_day','change');
               return false
            } else {

               for(i=0;i<periodArray.length;i++) {

                  if (DateValue(SearchSelectedDate)<DateValue(periodArray[i])){
                     alert('There is no availability between ' + periodArray[i-1] + ' and ' +periodArray[i]+'.  The departure date will show the first date available');
                     // Set Minimum Date in fields
                     SetDepartureDate(periodArray[i])
                     DynamicUpdate('calendar_day','change');
                     count++;
                     return false
                     break;
                  }
              }
           }

       }
       if (count==0){
          alert("Please select a departure date on or before " + periodArray[periodArray.length-1])
          // Set Minimum Date in fields
          SetDepartureDate(periodArray[periodArray.length-1])
          DynamicUpdate('calendar_day','change');
          return false;
       }
   }
   return true
}

function SetDepartureDate(DateIn) {
   var arrMinDateSplit = DateIn.split('/')
   NewDay = arrMinDateSplit[0]
   NewMonth = arrMinDateSplit[1]
   NewYear = arrMinDateSplit[2]
   FieldObjDay1 = getElem('calendar_day')
   FieldObjMonthYear1 = getElem('calendar_month_year')
   FieldObjDay1.options[NewDay-1].selected = true
   for (i=0;i<FieldObjMonthYear1.options.length;i++) {
      if (FieldObjMonthYear1.options[i].value == (NewMonth + '/' + NewYear)) {
         FieldObjMonthYear1.options[i].selected = true
      }
   }
}

function CheckValidDepartureDate() {
SearchSelectedDate = getElem('calendar_day').value + '/' + getElem('calendar_month_year').value
if (!CheckValidDate(SearchSelectedDate)) { return false; }
if (DateValue(SearchSelectedDate) < DateValue(dteMinDeparture)) { return false; }
var counter = 1;
for(var i=0;i<periodArray.length;i=i+2){
   if(((DateValue(SearchSelectedDate))>=(DateValue(periodArray[i]))) && ((DateValue(SearchSelectedDate))<=(DateValue(periodArray[(i+1)])))){
      counter++;
   }
}
if (counter%2!=0){ return false; }
return true;
}

// Check date is valid (e.g. Not 30/02/2003)
function CheckValidDate(datein) {
   var datePat = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{4})$/;
   var FieldObjDay1 = getElem('calendar_day')
   var matchArray = datein.match(datePat);
   if (matchArray == null) {
      alert('Please select a valid departure date')
      return false;
   } else {
      day = matchArray[1];
      month = matchArray[3];
      year = matchArray[4];
      if ((month==4 || month==6 || month==9 || month==11) && day==31) {
         // Set maximum day for this month
         FieldObjDay1.options[29].selected = true;
         return true
      }
      if (month == 2) {
         var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
         if (day>29 || (day==29 && !isleap)) {
         // Set maximum day for this month
         if (isleap) { FieldObjDay1.options[28].selected = true; }
         if (!isleap) { FieldObjDay1.options[27].selected = true; }
            return true;
         }
      }
   }
   return true;
}

// just for the availability search form
function SearchValidate() {
   // Check Departure Date
   if (!CheckDepartureDate()) { return; }

   var isDefaultConfig = document.forms[0].elements["searchCriteria.defaultRoomConfiguration"].value;
    if (isDefaultConfig == "false") {
      if (!CheckTotalPartySize() || !CheckOneAdultforRoom() || !CheckOneAdultacrossRooms() || !CheckAdultandInfant()) return;
   } else if(document.forms[0].elements["searchCriteria.roomConfigurationFormBean.numberOfRooms"]) {
   if(!CheckRoomAdultsQty()) return;
   if(!CheckPassengerQty()) return;
   }

   // Set Fixed Departure Date priority (in the priority dropdown) if Exactly option selected
   //if (getElem('departureDateExactly').checked) { getElem('searchCriteria.priority').options[1].selected = true; }
   // Copy children ages into hidden fields
   if(getElem('NoChildren')) {
      no_of_children = parseInt(getElem('NoChildren').value,10)
      for (var i=0; i < no_of_children; i++) {
         var age=document.getElementById("child"+i).selectedIndex+2
         document.getElementsByName("searchCriteria.childAges["+i+"]")[0].value=age
      }
   }
   // Enable Location dropdowns
   ElementAction('SearchResort','enable');
   ElementAction('SearchAccommodation','enable');

   var dynamicFrameName = 'dynamicFrameARA';
   var url = '/st/sun/autoRoomAllocation.do';
   var adultsnum = 0;
   var childnum =0; 
   var infantnum =0;

    // Do this only when default config validation is true and ARA is enabled.
    if(isDefaultConfig == "true" && (document.forms[0].elements["searchCriteria.roomConfigurationFormBean.numberOfRooms"]))
    {
      adultsnum   = parseInt(getElem('NoAdults').value,10)
      childnum = parseInt(getElem('NoChildren').value,10)
      infantnum  = parseInt(getElem('NoInfants').value,10)
   var numberOfRooms = document.forms[0].elements["searchCriteria.roomConfigurationFormBean.numberOfRooms"].value;
   url += '?adults=' + adultsnum + '&children=' + childnum + '&infants=' + infantnum + '&numberOfRooms=' + numberOfRooms;
   try {
      window[dynamicFrameName].document.location.replace(url);
   } catch (e) {
      window[dynamicFrameName].location = url;
   }
   } else {
      document.forms[0].action = '/st/sun/initialiseSearchInstruction.do';
      document.forms[0].submit();
   }
}

function CheckRoomAdultsQty() {
   var numAdults = +$F('NoAdults');
   var errorNumRooms = false;
   if(document.forms[0].elements["searchCriteria.roomConfigurationFormBean.numberOfRooms"]) {
      var numberOfRooms = document.forms[0].elements["searchCriteria.roomConfigurationFormBean.numberOfRooms"].value;
      if (numberOfRooms> numAdults ) {
         errorNumRooms = 'Number of rooms entered cannot be greater than the number of adults in your party. Please\nre-enter your required number of rooms and the party configuration in the search panel';
      }
      if (errorNumRooms) {
         window.alert(errorNumRooms);
         document.forms[0].elements["searchCriteria.roomConfigurationFormBean.numberOfRooms"].selectedIndex = 0;
         $('NoAdults').selectedIndex = 1;
         $('NoChildren').selectedIndex = 0;
         $('NoInfants').selectedIndex = 0;
         RedrawChildren();
      }
      return !errorNumRooms;
   }
}

function checkARAflag(obj) {
   document.forms[0].elements["searchCriteria.defaultRoomConfiguration"].value = obj;
   if(obj == 'true') {
         document.forms[0].action = '/st/sun/initialiseSearchInstruction.do';
         document.forms[0].submit();
         return true;
      } else {
         alert("Please enter the number of passengers in each room.");
         numberOfRooms = document.forms[0].elements["searchCriteria.roomConfigurationFormBean.numberOfRooms"].value;
         redrawRoomConfiguration(numberOfRooms);
         document.getElementById("roomConfigurationIni").style.display="none";
      }
}

function SearchExecute() {
   // Copy children ages into hidden fields
   no_of_children = parseInt(getElem('NoChildren').value,10)
   for (var i=0; i < no_of_children; i++) {
      var age=document.getElementById("child"+i).selectedIndex+2
      document.getElementsByName("searchCriteria.childAges["+i+"]")[0].value=age
   }
   // Enable Location dropdowns
   ElementAction('SearchResort','enable')
   ElementAction('SearchAccommodation','enable')
   if (ns6) {
      getElem('searchcriteria1').style.visibility = 'hidden';
      getElem('searchcriteria1').style.display = 'block';
      getElem('searchcriteria1').style.height = '0px';
      getElem('searchcriteria1').style.overflow = 'none';
   }
   document.forms[0].action = '/st/sun/initialiseSearchInstruction.do';
   document.forms[0].submit();
}

// Set children ages from hidden fields and update free child place field
function ChildrenInit() {
   RedrawChildren();
}

// Get the value of a date
function DateValue(objval) {
   dateval = new Date()
   var Pat1 = /^(\d{1,2})(\/|-)(\d{1,2})\2(\d{2,4})$/;
   if (Pat1.test(objval)) {
      var dateArray = objval.match(Pat1); // is the format ok?
      dateval.setDate(dateArray[1])
      dateval.setMonth(dateArray[3]-1)
      dateval.setYear(dateArray[4])
      dateval.setHours(0)
      dateval.setMinutes(0)
      dateval.setSeconds(0)
      dateval.setMilliseconds(0)
      return dateval.getTime()
   } else {
      return 0
   }
}

function validateHolidayTypePref(ElementID)//New function added for populating dropdown on clicking +/-7 cbox
{
   if (getElem('departureDateExactly').checked) { getElem('priority').options[1].selected = true;}
   if (getElem('departureDateFlexible').checked){ getElem('priority').options[0].selected = true;}
}

function checkAdults(id) {
   if($F(id) == '9+') {
      if (document.all) { alert($('adultmessage').innerText); }
      else              { alert($('adultmessage').textContent); }
      $(id).selectedIndex=1;
      $(id).focus();
   }
}

function redrawRoomConfiguration(numberOfRooms) {
   var roomConfig = "<table cellpadding=\"1\" cellspacing=\"0\" border=\"0\" class=\"roomConfiguration\"><tr><td width=\"25%\"><p>Room</p></td><td width=\"25%\"><p align=\"center\">Adults</p></td><td nowrap=\"nowrap\" width=\"25%\"><p align=\"center\">Children<br/>Ages 2-12</p></td><td nowrap=\"nowrap\" width=\"25%\"><p align=\"center\">Infants<br/>Under 2</p></td></tr>";
   if (numberOfRooms>=2) {
      for(i=0;i<numberOfRooms;i++) {
         roomConfig+= createSingleRoomConfiguration(i);
      }
   } else {
      roomConfig+= createSingleRoomConfiguration(0);
   }
   roomConfig+= "</table>";
   getElem("roomConfiguration").innerHTML = roomConfig;
   getElem("roomConfiguration").style.display="block";
}

function redrawOriginalRoomConfiguration(numberOfRooms) {
   getElem("roomConfiguration").innerHTML = "";
   getElem("roomConfiguration").style.display="none";
   getElem("roomConfigurationIni").style.display="block";
   document.forms[0].elements["searchCriteria.defaultRoomConfiguration"].value = true;
}

function createSingleRoomConfiguration(roomNumber)
{
   var roomConfigRow = "<tr><td align=\"center\" valign=\"top\"><p style=\"position:auto;border:1px solid #2b0097;text-align:center;color:#fff;background:#c6c6fa;width:17px;height:15px;font-size:10px;margin:1px 0px 0px 14px;\">" + ( roomNumber + 1 ) + "</p></td>";
   roomConfigRow+= "<td align=\"center\" valign=\"top\">" + createAdultDropdown(roomNumber) + "</td>";
   roomConfigRow+= "<td align=\"center\" valign=\"top\">" + createChildDropdown(roomNumber) + "</td>";
   roomConfigRow+= "<td align=\"center\" valign=\"top\">" + createInfantDropdown(roomNumber) + "</td></tr>";
   roomConfigRow+= "<tr><td colspan=\"4\" style=\"text-align:center;padding:5px 0px 5px 5px;\" id=\"childAgesRow_"+roomNumber+"\"></td></tr>";
   return roomConfigRow;
}

function createAdultDropdown(roomNumber) {
   var adultDropDown = "<select style=\"width:35px\" name=\"searchCriteria.roomConfigurationFormBean.rooms["+roomNumber+"].adults\" onchange=\"checkPartySize(this);\">";
   for(j=1;j<=9;j++) {
      if(j==1) { //for defaulting 1
         adultDropDown+= "<option value=\"" + j + "\" selected='selected'>" + j + "</option>"; continue;
         }
      adultDropDown+= "<option value=\"" + j + "\">" + j + "</option>";
   }
   adultDropDown+= "</select>";
   return adultDropDown;
}

function createChildDropdown(roomNumber) {
   var childDropDown = "<select style=\"width:35px\" name=\"searchCriteria.roomConfigurationFormBean.rooms[" + roomNumber + "].children\" onchange=\"redrawChildAges(this);\">";
   for(k=0;k<9;k++) {
      childDropDown+= "<option value=\"" + k + "\">" + k + "</option>";
   }
   childDropDown+= "</select>";
   return childDropDown;
}

function createInfantDropdown(roomNumber) {
   var infantDropDown = "<select style=\"width:35px\" name=\"searchCriteria.roomConfigurationFormBean.rooms["+roomNumber+"].infants\">";
   for(l=0;l<=9;l++) {
      infantDropDown+= "<option value=\"" + l + "\">" + l + "</option>";
   }
   infantDropDown+= "</select>";
   return infantDropDown;
}

function redrawChildAges(obj) {
   if (!checkPartySize(obj));
   var numberOfChildren = obj.value;
   var roomNumber = getRoomNumber(obj.name);
   var childAges = "";
   if (numberOfChildren>0) {
      for(childNum=0;childNum<numberOfChildren;childNum++) {
         childAges+= "<div style=\"float:left;font-family:Verdana,Arial;margin:2px 0px 5px 5px !important;padding:0px !important;\">Child " + ( childNum + 1 ) + " <select style=\"width:40px\" name=\"searchCriteria.roomConfigurationFormBean.rooms[" + roomNumber + "].childAge[" + childNum + "]\">";
         for(age=2;age<13;age++) {
            if (document.forms[0].elements["searchCriteria.roomConfigurationFormBean.rooms[" + roomNumber + "].childAge[" + childNum + "]"] && (document.forms[0].elements["searchCriteria.roomConfigurationFormBean.rooms[" + roomNumber + "].childAge[" + childNum + "]"].value>0 && age==document.forms[0].elements["searchCriteria.roomConfigurationFormBean.rooms[" + roomNumber + "].childAge[" + childNum + "]"].value) || age==2) {
               childAges+= "<option value=\"" + age + "\" selected=\"selected\">" + age + "</option>";
            }else{
               childAges+= "<option value=\"" + age + "\">" + age + "</option>";
            }
         }
         childAges+= "</select></div>";
      }
      if(roomNumber == 0) //added to add the caption only once
         childAges = "<p>Please enter ages on date of return for children (2-12)</p>" + childAges;
   }
   getElem("childAgesRow_"+roomNumber).innerHTML = childAges;
}

function getRoomNumber(name) {
   var roomNumber = name.substring(name.indexOf("[")+1,name.indexOf("]."));
   return roomNumber;
}

function displayPartyDetails(event,display,elementId,flag) {
     var detailDiv = "";
   if (document.getElementById(elementId)) {
        detailDiv = document.getElementById(elementId);
     }
     if (display=="show") {
        detailDiv.style.display = "inline";
        positionDiv(event, detailDiv,flag);
     }else{
        detailDiv.style.display = "none";
     }
  }

function displayChildTermsAndConditions(event,display,elementId,flag,minAge, maxAge) {
   var detailDiv = "";
   if (document.getElementById(elementId)) {
      detailDiv = document.getElementById(elementId);
   }
   if (display=="show") {
      detailDiv.style.display = "block";
      getElem("min").innerHTML = minAge;
      getElem("max").innerHTML = maxAge;
      positionDiv(event, detailDiv,flag);
      divSelectHover(); //added to hide the DIV from selectboxes
   } else {
      detailDiv.style.display = "none";
   }
}

function positionDiv(e,obj,flag) {
   var xpos    = findPosX(e);
   var ypos    = findPosY(e);
   var winTop, winLeft;
   var isOpera = (navigator.userAgent.indexOf('Opera') != -1);
   var isIE    = (!isOpera && navigator.userAgent.indexOf('MSIE') != -1);

   winTop  = (ypos + 20);
   if(flag) {
      winLeft = (xpos - 46);
      if (isIE) winLeft =  (xpos- 30);
   } else {
      winLeft = (xpos - 268);
      if (isIE) winLeft =  (xpos - 252);
   }
   obj.style.top = winTop +'px';
   obj.style.left = winLeft +'px';
}


/**
 * This method is used to find the position of the object (Find button).
 *
 * @param obj: It is the find button image object.
 */
function findPosX(obj) {
   var curleft = 0;
   if (obj.offsetParent)
   {
      while (obj.offsetParent)
      {
         curleft += obj.offsetLeft;
         obj = obj.offsetParent;
      }
   }
   else if (obj.x) curleft += obj.x;
   return curleft;
}

/**
 * This method is used to find the position of the object (Find button).
 *
 * @param obj: It is the find button image object.
 */
function findPosY(obj) {
   var curtop = 0;
   if (obj.offsetParent)
   {
      while (obj.offsetParent)
      {
         curtop += obj.offsetTop
         obj = obj.offsetParent;
      }
   }
   else if (obj.y) curtop += obj.y;
   return curtop;
}

/**
 * This method is used to update the selected room's selected value.
 * If the quantity available for this room is zero after the selection then hides the other possible upgrades.
 *
 * @param obj: selected room object
 */
function updateSelectedRoom(obj) {
   var objName = obj.name;
   var selIndex = -1;
   for(i=0;i<roomConfigNum;i++) {
      for(k=0;k<document.forms[0].elements["roomConfigurationFormBeans["+i+"].selected"].length;k++) {
         if (document.forms[0].elements["roomConfigurationFormBeans["+i+"].selected"][k].checked) {
            document.forms[0].elements["roomConfigurationFormBeans["+i+"].availableRoomDetailsFormBeans["+k+"].selected"].value = "true";
            document.forms[0].elements["roomConfigurationFormBeans["+i+"].selected"][k].value = "true";
            if(objName == "roomConfigurationFormBeans["+i+"].selected")
           {
            hideSimilarRooms(i , k );
            }
         } else {
            document.forms[0].elements["roomConfigurationFormBeans["+i+"].availableRoomDetailsFormBeans["+k+"].selected"].value = "false";
            document.forms[0].elements["roomConfigurationFormBeans["+i+"].selected"][k].value = "false";
            unHideRooms( i , k );
         }
      }
   }
}

/**
 * This method is used to update the selected room's selected value.
 * If the quantity available for this room is zero after the selection then hides the other possible upgrades.
 *
 * @param obj: selected room object
 */
function hideRoomsWithNotEnoughQty()
{
   for(i=0;i<roomConfigNum;i++) {
      for(k=0;k<document.forms[0].elements["roomConfigurationFormBeans["+i+"].selected"].length;k++) 
      {
            if (document.forms[0].elements["roomConfigurationFormBeans["+i+"].selected"][k].checked) {
            hideSimilarRooms(i , k );
            }
      }
   }
}

function getRemainingRoomQuantityForSelectedRoom(selectedRoomCode, selectedRoomQty)
{
	var remRoomQty = selectedRoomQty;
   for(var  j=0 ; j <roomsNum.length  ; j++ )
   {
      for(var l=0; l <roomsNum[j]; l++)
      {
        currRoomCode = document.forms[0].elements["roomConfigurationFormBeans["+j+"].availableRoomDetailsFormBeans["+l+"].roomDetail.roomCode"].value;
        if (currRoomCode == selectedRoomCode
            && document.forms[0].elements["roomConfigurationFormBeans["+j+"].selected"][l] != null
            && document.forms[0].elements["roomConfigurationFormBeans["+j+"].selected"][l].type == "radio"
            && document.forms[0].elements["roomConfigurationFormBeans["+j+"].selected"][l].checked)
         {
				--remRoomQty;
         }
      }
   }

   return remRoomQty;
}


/**
 * This method is used to hide all upgrade rooms where quantity available for the selected room is less than
 * ZERO for the passed in room group index and the current index
 *
 */
function hideSimilarRooms(  currRoomGroupIndex, currRoomIndex )
{
   var selectedRoomCode = document.forms[0].elements["roomConfigurationFormBeans["+currRoomGroupIndex+"].availableRoomDetailsFormBeans["+currRoomIndex+"].roomDetail.roomCode"].value;
   var selectedRoomQty = document.forms[0].elements["roomConfigurationFormBeans["+currRoomGroupIndex+"].availableRoomDetailsFormBeans["+currRoomIndex+"].roomDetail.quantityAvailable"].value
  selectedRoomQty = getRemainingRoomQuantityForSelectedRoom(selectedRoomCode, selectedRoomQty);

  var theRows = document.getElementById("roomUpsellTable").rows

   for(var j=roomsNum.length -1 ; j >= 0 ; j -- )
   {
      for( var l=0; l <roomsNum[j]; l++)
      {
         var currRoomCode = document.forms[0].elements["roomConfigurationFormBeans["+j+"].availableRoomDetailsFormBeans["+l+"].roomDetail.roomCode"].value;

         if(currRoomCode == selectedRoomCode && j != currRoomGroupIndex )
         {
            if( (( --selectedRoomQty) < 0 )  && document.forms[0].elements["roomConfigurationFormBeans["+j+"].availableRoomDetailsFormBeans["+l+"].selected"].value == "false")
            {
               var regExp = new RegExp("Room_"+l+"_"+j);
               for (var rowNum=0;rowNum<theRows.length;rowNum++) 
               { 
                  if (regExp.test(theRows[rowNum].id)) { 		
					  theRows[rowNum].style.display="none";
                 showRoomDescription(j);
                 }
               }
            }
         }
      }
   }
}


function showRoomDescription(currRoomGroupIndex)
{
   //If the first room in the group is hidden
   if(document.getElementById("Room_0_"+currRoomGroupIndex).style.display=="none")
   {
      // Iterate through the rest of the rooms..
      for(var l=1; l <roomsNum[currRoomGroupIndex]; l++)
      {
         // For the room which is not hidden..
         if(document.getElementById("Room_"+l+"_"+currRoomGroupIndex).style.display=="")
         {
            document.getElementById("RoomDesc_"+l+"_"+currRoomGroupIndex).style.display="";
            break;
         }
      }
   }
}

function hideRoomDescription(currRoomGroupIndex)
{
   //If the first room in the group is enabled...
   if(document.getElementById("Room_0_"+currRoomGroupIndex).style.display=="")
   {
      // Iterate through the rest of the rooms..
      for(var l=1; l <roomsNum[currRoomGroupIndex]; l++)
      {
            document.getElementById("RoomDesc_"+l+"_"+currRoomGroupIndex).style.display="none";
      }
   }
}


/**
 * This method unhides any rooms which were previously hidden due to lack of quantity available.
 *
 */
function unHideRooms( currRoomGroupIndex, currRoomIndex )
{
   var selectedRoomCode = document.forms[0].elements["roomConfigurationFormBeans["+currRoomGroupIndex+"].availableRoomDetailsFormBeans["+currRoomIndex+"].roomDetail.roomCode"].value;

   var selectedRoomQty= -99;
   var theRows = document.getElementById("roomUpsellTable").rows

    var currRoomCode ="";
   for(var  j=0 ; j <roomsNum.length  ; j++ )
   {
      for(var l=0; l <roomsNum[j]; l++)
      {
        currRoomCode = document.forms[0].elements["roomConfigurationFormBeans["+j+"].availableRoomDetailsFormBeans["+l+"].roomDetail.roomCode"].value;
        if (currRoomCode == selectedRoomCode
            && document.forms[0].elements["roomConfigurationFormBeans["+j+"].selected"][l] != null
            && document.forms[0].elements["roomConfigurationFormBeans["+j+"].selected"][l].type == "radio"
            && document.forms[0].elements["roomConfigurationFormBeans["+j+"].selected"][l].checked)
         {
            selectedRoomQty = document.forms[0].elements["roomConfigurationFormBeans["+j+"].availableRoomDetailsFormBeans["+l+"].roomDetail.quantityAvailable"].value
            selectedRoomQty = getRemainingRoomQuantityForSelectedRoom(selectedRoomCode, selectedRoomQty);
         }
      }
   }


   for(var  j=0 ; j < roomsNum.length  ; j ++ )
   {
      for(var l=0; l <roomsNum[j]; l++)
      {
         var currRoomCode = document.forms[0].elements["roomConfigurationFormBeans["+j+"].availableRoomDetailsFormBeans["+l+"].roomDetail.roomCode"].value;
         if(currRoomCode == selectedRoomCode && j != currRoomGroupIndex  )
         {
            var regExp = new RegExp("Room_"+l+"_"+j);
	        for (var rowNum=0;rowNum<theRows.length;rowNum++) 
           	{ 
          	   if (regExp.test(theRows[rowNum].id) ) {
                if( selectedRoomQty== -99 || selectedRoomQty > 0) 
                {                
                      theRows[rowNum].style.display="";
                      					   hideRoomDescription(j);
                } 
              }
            }
         }
      }
   }
}


// Set Focus to field and show message
function SetFocus(alertmess,obj1) {
alert(alertmess)
obj1.focus();
return;
}

function updateRoomPriceAndGetTotalPartyPrice(obj) {
   var objName = obj.name;
   for(i=0;i<roomConfigNum;i++) {
      for(k=0;k<document.forms[0].elements["roomConfigurationFormBeans["+i+"].selected"].length;k++) {
         if (document.forms[0].elements["roomConfigurationFormBeans["+i+"].selected"][k].checked) {
            document.forms[0].elements["roomConfigurationFormBeans["+i+"].availableRoomDetailsFormBeans["+k+"].selected"].value = "true";
            document.forms[0].elements["roomConfigurationFormBeans["+i+"].selected"][k].value = "true";
            var elem = "totalPrice_1_"+k;
            var totalPartyPrice = document.forms[0].elements['totalPrice_1_'+k].value
            document.getElementById('totalPartyPara').innerHTML = "&pound;" + totalPartyPrice;
         } else {
            document.forms[0].elements["roomConfigurationFormBeans["+i+"].availableRoomDetailsFormBeans["+k+"].selected"].value = "false";
            document.forms[0].elements["roomConfigurationFormBeans["+i+"].selected"][k].value = "false";
         }
      }
   }
}

function checkPartySize(obj) {
   var isDefaultConfig = document.forms[0].elements["searchCriteria.defaultRoomConfiguration"].value;
   if (isDefaultConfig == "false" && !CheckPassengerQtyARA(obj)) return;
   else if (isDefaultConfig == "true" && !CheckPassengerQty()) return;
   else return true;
}

function CheckTotalPartySize() {
   var NumAdults =0;
   var NumChildren = 0;
   for(i=0;i<document.forms[0].elements["searchCriteria.roomConfigurationFormBean.numberOfRooms"].value;i++) {
      NumAdults = NumAdults + parseInt(document.forms[0].elements["searchCriteria.roomConfigurationFormBean.rooms[" + i + "].adults"].value,10);
      NumChildren = NumChildren + parseInt(document.forms[0].elements["searchCriteria.roomConfigurationFormBean.rooms[" + i + "].children"].value,10);
      if ((NumAdults + NumChildren) > 9) {
         return SetFocus('Your total party size must be 9 passengers or fewer ',document.forms[0].elements["searchCriteria.roomConfigurationFormBean.rooms[0].adults"]);
      }
   }
   return true;
}

function CheckOneAdultforRoom() {
   for(var i=0;i<document.forms[0].elements["searchCriteria.roomConfigurationFormBean.numberOfRooms"].value;i++) {
      if(parseInt(document.forms[0].elements["searchCriteria.roomConfigurationFormBean.rooms[" + i + "].adults"].value,10) < 1) {
         return SetFocus('You must select atleast one adult passenger across room '+ (i+1),document.forms[0].elements["searchCriteria.roomConfigurationFormBean.rooms["+ i +"].adults"]);
      }
   }
   return true;
}

function CheckOneAdultacrossRooms() {
   var NumAdults =0;
   for(i=0;i<document.forms[0].elements["searchCriteria.roomConfigurationFormBean.numberOfRooms"].value;i++) {
      NumAdults = NumAdults + parseInt(document.forms[0].elements["searchCriteria.roomConfigurationFormBean.rooms[" + i + "].adults"].value,10);
   }
   if (NumAdults < 1) {
      return SetFocus('You must select atleast one adult passenger across all rooms',document.forms[0].elements["searchCriteria.roomConfigurationFormBean.rooms[0].adults"]);
   }
   return true;
}

function CheckAdultandInfant() {
   var NoAdults, NoChildren, NoInfants, tooManyInfants, grownUps;
   childAgesDrawn = true;
   for(i=0;i<document.forms[0].elements["searchCriteria.roomConfigurationFormBean.numberOfRooms"].value;i++) {
     if (document.forms[0].elements["searchCriteria.roomConfigurationFormBean.rooms[" + i + "].adults"]) {
        NoAdults   = parseInt(document.forms[0].elements["searchCriteria.roomConfigurationFormBean.rooms[" + i + "].adults"].value,10);
        NoChildren = parseInt(document.forms[0].elements["searchCriteria.roomConfigurationFormBean.rooms[" + i + "].children"].value,10);
        NoInfants  = parseInt(document.forms[0].elements["searchCriteria.roomConfigurationFormBean.rooms[" + i + "].infants"].value,10);
        tooManyInfants = false;
        if (NoInfants > NoAdults) {
           grownUps = NoAdults;
           no_of_children = parseInt(document.forms[0].elements["searchCriteria.roomConfigurationFormBean.rooms[" + i + "].children"].value);
           if( no_of_children > 0 ) {
              for (j=0; j < no_of_children;j++) {
                 if(document.forms[0].elements["searchCriteria.roomConfigurationFormBean.rooms[" + i + "].childAge[" + j + "]"])
                 {
                    age = parseInt(document.forms[0].elements["searchCriteria.roomConfigurationFormBean.rooms[" + i + "].childAge[" + j + "]"].value)
                 if( age > 11 ) {
                    grownUps++;
                 }
              }
              else
                 {
                    childAgesDrawn = false;
                 }
              }
           }
           tooManyInfants = ( grownUps < NoInfants );
        }
        if( tooManyInfants && childAgesDrawn) {
         return SetFocus('There must be at least one passenger aged 12 or over for each infant travelling',document.forms[0].elements["searchCriteria.roomConfigurationFormBean.rooms[" + i + "].adults"]);
        }
     }
   }
   return true;
}

//Function to hide select boxes when hovered in child ages under room upsell/selection page
divSelectHover = function() {
   var ieDivs = document.getElementsByTagName('div');
   for(i=0; i<ieDivs.length; i++) {
      var ieDiv = ieDivs[i];
      if(ieDiv.id == "terms") // Check if the DIV is of ID term and send it ahead.
         setHover(ieDiv);
   }
}

function setHover(nav) {
   if (navigator.appVersion.substr(22,3)!="5.0") {
      // IE script to cover <select> elements with <iframe>s
      nav.innerHTML = ('<iframe src="about:blank" scrolling="no" frameborder="0" style="position:absolute;filter: progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0);"></iframe>' + nav.innerHTML);
      var ieMat = nav.firstChild;
      ieMat.style.width= nav.offsetWidth + "px";
      ieMat.style.height= nav.offsetHeight + "px";
      ieMat.style.display = "inline";
      ieMat.style.zIndex="-1";
      nav.style.zIndex="101";
   }
}