var displayPropertiesFlag = false;
var ns4 = (document.layers);
var ie4 = (document.all && !document.getElementById);
var ie5 = (document.all && document.getElementById);
var ie6 = (navigator.userAgent.indexOf("MSIE 6.0")!=-1);
var ns6 = (!document.all && document.getElementById);
var mac = (navigator.userAgent.indexOf("Mac") != -1);
var moz = (navigator.userAgent.indexOf("Netscape") == -1);
var popupWin = '';

function getElem(elemname) {
   if(ie4) {
      return document.all[elemname]
   }
   else if(ie5 || ns6) {
      return document.getElementById(elemname)
   }
}

function getElemName(elemname) {
   return document.getElementsByName(elemname)
}

function Popup(popURL,popW,popH,attr){
   if (!popH) { popH = 350 }
   if (!popW) { popW = 600 }
   var winLeft = (screen.width-popW)/2;
   var winTop = (screen.height-popH-30)/2;
   var winProp='width='+popW+',height='+popH+',left='+parseInt(winLeft)+',top='+winTop+','+attr;
if (parent.window.name == "popupWindow")
  {
     windowName = "popupWindow1";
  }
  else
  {
     windowName = "popupWindow";
   }
  popupWin=window.open('/static/blank.html',windowName,"\'"+winProp+"\'");
  popupWin.close()
  popupWin=window.open(popURL,windowName,winProp)
     popupWin.window.focus()
}

function pagecall(url1,params,bkmark) {
   newurl =  url1 + '?p=' + popup
   if (params) { if (params != '') { newurl += '&' + params } }
   if (bkmark) { if (bkmark != '') { newurl += '#' + bkmark } }
   document.location.href = newurl
}

function FormFocus() {
   document.forms.frmSearchPanel.elements[0].focus()
}

function ButtonPressed(thisbutton) {
   thisbutton.style.borderRight = 'solid #444477 1px';
   thisbutton.style.borderBottom = 'solid #444477 1px';
   thisbutton.style.borderTop = 'solid #444477 2px';
   thisbutton.style.borderLeft= 'solid #444477 2px';
   thisbutton.style.color = '#77bBd6'
}

function PopupCheck(urlforward) {
   if ((window.opener) && (window.name == 'popupWindow')) {
      window.opener.location.href = urlforward
      window.close()
   }
}

function AlertErrorsWarnings() {
   if (getElem('errorwarnings')) {
      alert(getElem('errorwarnings').innerHTML)
   }
}
var tmpIndex = new Array();
//Function to find unique elements in an array
function unique(a) {
   tmp = new Array(0);
   for(i=0;i<a.length;i++) {
      if(!contains(tmp, a[i])) {
         tmp.length+=1;
         tmp[tmp.length-1]=a[i];
         tmpIndex.length+=1;
         tmpIndex[tmpIndex.length-1]=i;
      }
   }
   return tmp;
}

//Helper function of unique() which finds unique elements in an array
function contains(a, e) {
   for(j=0;j<a.length;j++)
   if(a[j]==e)return true;
   return false;
}

function addOnload(fn) {
   if (window.addEventListener) {
      window.addEventListener('load', fn, false)
   } else {
      window.attachEvent('onload', fn);
   }
}

var roomConfigurationArray = new Array();

function Room(roomNumber,numAdults,numChildren,numInfants,childAges)
{
   this.roomNumber = roomNumber;
   this.numAdults = numAdults;
   this.numChildren = numChildren;
   this.numInfants = numInfants;
   this.childAges = childAges;
}

function createRoomConfigurationFromForm(form, productCode) {
   roomConfigurationArray = new Array();
   var roomConfigFromForm = form.partyRoomConfiguration.value;
   var numberOfRooms = form.numberOfRooms.value;
   if (roomConfigFromForm!="") {
      var roomConfigFromFormArr = roomConfigFromForm.split("/");
      for(var i=0;i<roomConfigFromFormArr.length;i++) {
         var room = roomConfigFromFormArr[i].split("|");
         var childAges = null;
         if (room.length>3) {
            childAges = room[3].split("-");
         }
         var roomObj = new Room();
         roomObj.numberOfRooms = i;
         numberOfRooms = roomObj.numberOfRooms;
         roomObj.numAdults = room[1];
         roomObj.numChildren = room[2];
         roomObj.childAges = childAges;
         roomConfigurationArray[roomConfigurationArray.length] = roomObj;
      }
   }
   form.numberOfRooms.value = numberOfRooms;
   /*if (obj == "alternate")
      redrawAlternateRoomConfiguration(document.forms[0].numberOfRooms.value)
     /*~~~~~~~~~~LD Room Configuration~~~~~~~~~~~~*/

   if (form.name == "lateSearchPanel")
	{
      redrawLDRoomConfiguration(form);
	}
   else if(form.name=="searchLateForm")
	{
   		redrawLDRoomConfiguration(form);
    }
   else
	{
      redrawRoomConfiguration(form, productCode);
	}
}

function redrawRoomConfiguration(form, productCode) {
   var roomConfig = "";
   var numberOfRooms = form.numberOfRooms.value;
   if (numberOfRooms>0) {
      roomConfig += "<span>";
      roomConfig += "<div>";
      roomConfig += "<div class=\"col1\">&nbsp;</div>";
      roomConfig += "<div class=\"col2\">"+roomConfigAdultsCaption+"</div>";
      roomConfig += "<div class=\"col3\"";
	  if(form.name == "frmLightboxSearch" && (productCode == 'FTW' || productCode =='CFS'))
	  {
          roomConfig += "style=\"display:none\"";
	  }
      roomConfig += ">"+roomConfigChildrenCaption+"</div>";

      roomConfig += "</div>";
      roomConfig += "</span>";
      for(var i=0;i<numberOfRooms;i++) {
         roomConfig+= createSingleRoomConfiguration(i, productCode, form);
      }
   }
   if(form.name == "frmLightboxSearch")
   {
	   getElem("roominfo1").innerHTML = roomConfig;
   }
   else
   {
	   getElem("roominfo").innerHTML = roomConfig;
   }
   for(var i=0;i<numberOfRooms;i++) {
      redrawChildAges(form.elements["roomConfigurationFormBean.room[" + i + "].children"], form);
   }
   populateRoomConfigArray(form);
}

/*~~~~~~~~~~~~~~~~~ LD ~~~~~~~~~~~~~~~~~~~~~~*/
function redrawLDRoomConfiguration(form) {
   var roomConfig = "";
   var numberOfRooms = form.numberOfRooms.value;
   if (numberOfRooms>0)
   {
       for(var i=0;i<numberOfRooms;i++)
       {
           roomConfig += createLDSingleRoomConfiguration(i, form);
       }
   }
   getElem("roominfo").innerHTML = roomConfig;
   for(var i=0;i<numberOfRooms;i++) {
      redrawLDChildAges(form.elements["roomConfigurationFormBean.room[" + i + "].children"], form);
   }
   populateRoomConfigArray(form);
}
/*~~~~~~~~~~~~~~~~~ LD ~~~~~~~~~~~~~~~~~~~~~~*/


function populateRoomConfigArray(form) {
   roomConfigurationArray = new Array();
   for(var i=0;i<=form.elements["numberOfRooms"].value;i++) {
     if (form.elements["roomConfigurationFormBean.room[" + i + "].adult"]) {
        var numAdults = form.elements["roomConfigurationFormBean.room[" + i + "].adult"].value;
        var numChildren = form.elements["roomConfigurationFormBean.room[" + i + "].children"].value;
        var childAges = new Array();
        if (numChildren>0) {
           for(var j=1;j<=numChildren;j++) {
              if (form.elements["roomConfigurationFormBean.room[" + i + "].childAge[" + (j-1) + "]"]) {
                 childAges[j-1] = form.elements["roomConfigurationFormBean.room[" + i + "].childAge[" + (j-1) + "]"].value;
              }
           }
        }
        roomConfigurationArray[roomConfigurationArray.length] = new Room((i+1),numAdults,numChildren,0,childAges);
     }
   }
   // getElem('showcaption').style.display = "block";
   if((form.name == 'frmLightboxSearch' && getElem('showcaption1'))||(getElem('showcaption')))
   { showHideCaption(form.elements["numberOfRooms"].value, form);}
   return roomConfigurationArray;
}

function createSingleRoomConfiguration(roomNumber, productCode,form) {
   var roomConfigRow = "<span>";
   roomConfigRow += "<div style='height:22px;'>";
   roomConfigRow += "<div class=\"col1\">Room " + ( roomNumber + 1 ) + "</div>";
   roomConfigRow += "<div class=\"col2\">" + createAdultDropdown(roomNumber) + "</div>";
   roomConfigRow += "<div class=\"col3\"";
   if(form.name == "frmLightboxSearch" && (productCode == 'FTW' || productCode =='CFS'))
   {
       roomConfigRow += "style=\"display:none\"";
   }
   roomConfigRow +=  ">" +createChildDropdown(roomNumber) + "</div>";
   roomConfigRow += "</div>";
   roomConfigRow += "</span>";
   if(form.name == "frmLightboxSearch" && (productCode == 'FTW' || productCode =='CFS'))
   {
   }
   else
   {
       roomConfigRow += "<span id=\"room" + roomNumber + "_childrows\"></span>";
   }
   return roomConfigRow;
}

/*~~~~~~~~~~~~~~~~~ LD ~~~~~~~~~~~~~~~~~~~~~~*/
function createLDSingleRoomConfiguration(roomNumber, form) {
   var roomConfigRow = "";
   roomConfigRow += "<div id=\"roominfo" + roomNumber + "\" class=\"maincol2\" >";
   if(roomNumber >0)
   {
       roomConfigRow += "<div class=\"col1\"> &nbsp; </div>";
   }
   roomConfigRow += "<div class=\"col2\"> <span class=\"label\">Room" + ( roomNumber + 1 ) + "</span>";
   roomConfigRow +=  "<span> <label>"  + roomConfigAdultsCaption +  "</label>" + createAdultDropdown(roomNumber, form) + " </span> ";
   roomConfigRow +=  "  <span> <label>" + roomConfigChildrenCaption+ "</label>" + createChildDropdown(roomNumber,'latedeals') + " </span> </div>";
   roomConfigRow += "<span class='col3' id='agecols"+ roomNumber + "'></span> </div>";
   return roomConfigRow;
}
/*~~~~~~~~~~~~~~~~~ LD ~~~~~~~~~~~~~~~~~~~~~~*/

function createAdultDropdown(roomNumber, form) {
   var adultDropDown = "<select name=\"roomConfigurationFormBean.room["+roomNumber+"].adult\" onchange=\"populateRoomConfigArray(form);appendOnFocusToAllElements();\">";
   var currentAdultNums = 2;
   if (roomConfigurationArray && roomConfigurationArray[roomNumber]) {
      currentAdultNums = roomConfigurationArray[roomNumber].numAdults;
   }
   for(var i=1;i<=numberOfAdults;i++) {
      if (currentAdultNums==i) { adultDropDown+= "<option value=\"" + i + "\" selected=\"selected\">" + i + "</option>"; }
      else { adultDropDown+= "<option value=\"" + i + "\">" + i + "</option>"; }
   }
   adultDropDown+= "</select>";
   return adultDropDown;
}

function createChildDropdown(roomNumber,obj,form) {
  var childDropDown = "<select name=\"roomConfigurationFormBean.room[" + roomNumber + "].children\" onchange=\"redrawChildAges(this,form);populateRoomConfigArray(form);appendOnFocusToAllElements();\">";
  if(obj == 'alternate')
   var childDropDown = "<select class=\"childrenList\" name=\"roomConfigurationFormBean.room[" + roomNumber + "].children\" onchange=\"redrawAlternateChildAges(this);populateRoomConfigArray(form);form.type[0].focus();\">";
   /*~~~~~~~~~~~~~~~~~ LD ~~~~~~~~~~~~~~~~~~~~~~*/
   if(obj == 'latedeals')
      var childDropDown = "<select name=\"roomConfigurationFormBean.room[" + roomNumber + "].children\" onchange=\"redrawLDChildAges(this, form);populateRoomConfigArray(form);appendOnFocusToAllElements();\">";
   /*~~~~~~~~~~~~~~~~~ LD ~~~~~~~~~~~~~~~~~~~~~~*/
   var currentChildrenNums = 0;
   if (roomConfigurationArray && roomConfigurationArray[roomNumber]) {
      currentChildrenNums = roomConfigurationArray[roomNumber].numChildren;
   }
   for(var i=0;i<=numberOfChildren;i++) {
      if (currentChildrenNums==i) {
         childDropDown+= "<option value=\"" + i + "\" selected=\"selected\">" + i + "</option>";
      } else {
         childDropDown+= "<option value=\"" + i + "\">" + i + "</option>";
      }
   }
   childDropDown+= "</select>";
   return childDropDown;
}

function createInfantDropdown(roomNumber) {
   var infantDropDown = "<select class=\"infantsList\" name=\"roomConfigurationFormBean.room["+roomNumber+"].infants\">";
   for(l=0;l<=9;l++) {
      infantDropDown+= "<option value=\"" + l + "\">" + l + "</option>";
   }
   infantDropDown+= "</select>";
   return infantDropDown;
}

function redrawChildAges(obj, form) {
   var roomNumber = getRoomNumber(obj.name);
   var numberOfChildren = obj.value;
   var childAges = "";
   if (numberOfChildren>0) {
      for(childNum=0;childNum<numberOfChildren;childNum++) {
         childAges+= "<div class=\"childage_containerdiv\">";
         childAges+= "<div class=\"col1 right\">"+roomConfigChildCaption+" "+(childNum + 1)+" "+roomConfigAgeCaption+"</div>";
         childAges+= "<div class=\"col2\"></div>";
         childAges+= "<div class=\"col3\" id=\"child_ages\"><select name=\"roomConfigurationFormBean.room[" + roomNumber + "].childAge[" + childNum + "]\" onchange=\"populateRoomConfigArray(form);\">";
         childAges+= "<option value=\"-?-\">-?-</option>";
         if(roomConfigurationArray.length>0 && roomConfigurationArray[roomNumber].childAges[childNum] == "<2")
         {
        	 childAges+= "<option value=\"<2\" selected=\"selected\">< 2</option>";
         }
         else
         {
         childAges+= "<option value=\"<2\" >< 2</option>";
         }

         for(age=2;age<=maxChildAge;age++) {
            if (form.elements["roomConfigurationFormBean.room[" + roomNumber + "].childAge[" + childNum + "]"]
               && (form.elements["roomConfigurationFormBean.room[" + roomNumber + "].childAge[" + childNum + "]"].value>0
               && age==form.elements["roomConfigurationFormBean.room[" + roomNumber + "].childAge[" + childNum + "]"].value)
               || roomConfigurationArray[roomNumber].childAges[childNum]==age) {
               childAges+= "<option value=\"" + age + "\" selected=\"selected\">" + age + "</option>";
            } else {
               childAges+= "<option value=\"" + age + "\">" + age + "</option>";
            }
         }
         childAges+= "</select></div>";
         childAges+= "</div>";
      }
   }
   if (getElem("room" + roomNumber + "_childrows") != null)
   {
	   if (ie6)
	   {
		   document.getElementById("room" + roomNumber + "_childrows").innerHTML = childAges;
	   }
	   else{
	   getElem("room" + roomNumber + "_childrows").innerHTML = childAges;
   }
}
}

/*~~~~~~~~~~~~~~~~~ LD ~~~~~~~~~~~~~~~~~~~~~~*/
function redrawLDChildAges(obj , form) {
  var roomNumber = getRoomNumber(obj.name);
  var numberOfChildren = obj.value;
  var childAges = "<span class=\"label\">";
  if (numberOfChildren == '0')
  {
    childAges +="&nbsp; <span><label> &nbsp; </label></span> </span> <br clear=\"all\"/> ";
  }
  if (numberOfChildren>0)
  {
     childAges+= "Child ages:*</span>";
     for(childNum=0;childNum<numberOfChildren;childNum++)
     {
        childAges+= "<span> <label>";
        childAges+= ""+roomConfigChildCaption+" "+(childNum + 1) + "</label>";
        childAges+= "<select name=\"roomConfigurationFormBean.room[" + roomNumber + "].childAge[" + childNum + "]\" onchange=\"populateRoomConfigArray(form);\">";
        childAges+= "<option value=\"-?-\">-?-</option>";
        if(roomConfigurationArray.length>0 && roomConfigurationArray[roomNumber].childAges[childNum] == "<2")
        {
          childAges+= "<option value=\"<2\" selected=\"selected\">< 2</option>";
        }
        else
        {
          childAges+= "<option value=\"<2\" >< 2</option>";
        }
        for(age=2;age<=maxChildAge;age++) {
           if (form.elements["roomConfigurationFormBean.room[" + roomNumber + "].childAge[" + childNum + "]"]
              && (form.elements["roomConfigurationFormBean.room[" + roomNumber + "].childAge[" + childNum + "]"].value>0
              && age==form.elements["roomConfigurationFormBean.room[" + roomNumber + "].childAge[" + childNum + "]"].value)||  (roomConfigurationArray.length>0 && roomConfigurationArray[roomNumber].childAges[childNum]==age))  {
              childAges+= "<option value=\"" + age + "\" selected=\"selected\">" + age + "</option>";
           } else {
              childAges+= "<option value=\"" + age + "\">" + age + "</option>";
           }
        }
        childAges+= "</select>";
        childAges+= "</span>";
     }
  }
  getElem("agecols" + roomNumber).innerHTML = childAges;
}

function redrawAlternateRoomConfiguration(numberOfRooms) {
   var roomConfig = "";
   if (numberOfRooms>0) {
      roomConfig = "<div><div>&nbsp;</div><div>"+roomConfigAdultsCaption+"</div><div>"+roomConfigChildrenCaption+"</div></div>";
      for(var i=0;i<numberOfRooms;i++) {
         roomConfig+= createSingleAlternateRoomConfiguration(i);
      }
      if(ie5) roomConfig += "<br clear=\"all\"/>";
   }
   getElem("roominfo").innerHTML = roomConfig;
   for(var i=0;i<numberOfRooms;i++) {
      redrawAlternateChildAges(document.forms[0].elements["roomConfigurationFormBean.room[" + i + "].children"]);
   }
   populateRoomConfigArray();
}

function createSingleAlternateRoomConfiguration(roomNumber) {
  var roomConfigRow = "<div id=\"room"+ roomNumber +"\">";
  roomConfigRow += "<div class=\"right\">Room " + ( roomNumber + 1 ) + "</div>";
  roomConfigRow += "<div>" + createAdultDropdown(roomNumber) + "</div>";
  roomConfigRow += "<div>" + createChildDropdown(roomNumber,'alternate') + "</div>";
  roomConfigRow += "</div>";
  roomConfigRow += "<span id=\"room"+ roomNumber +"_childrows\"></span>";
  return roomConfigRow;
}

function redrawAlternateChildAges(obj) {
   var roomNumber = getRoomNumber(obj.name);
   var numberOfChildren = obj.value;
   var childAges = "";
   if (numberOfChildren>0) {
      for(childNum=0;childNum<numberOfChildren;childNum++) {
         childAges+= "<div>"
         childAges+= "<div class=\"right\">"+roomConfigChildCaption+" "+(childNum + 1)+" "+roomConfigAgeCaption+"</div>";
          childAges+= "<div id=\"child_age\"><select class=\"childAgeList\" name=\"roomConfigurationFormBean.room[" + roomNumber + "].childAge[" + childNum + "]\" onchange=\"populateRoomConfigArray();document.searchForm.type[0].focus();\">";
         childAges+= "<option value=\"-?-\">-?-</option>";
         if(roomConfigurationArray.length>0 && roomConfigurationArray[roomNumber].childAges[childNum] == "<2")
         {
        	 childAges+= "<option value=\"<2\" selected=\"selected\">< 2</option>";
         }
         else
         {
         childAges+= "<option value=\"<2\">< 2</option>";
         }
         for(age=2;age<=maxChildAge;age++) {
            if (document.forms.frmSearchPanel.elements["roomConfigurationFormBean.room[" + roomNumber + "].childAge[" + childNum + "]"]
               && (document.forms.frmSearchPanel.elements["roomConfigurationFormBean.room[" + roomNumber + "].childAge[" + childNum + "]"].value>0
               && age==document.forms.frmSearchPanel.elements["roomConfigurationFormBean.room[" + roomNumber + "].childAge[" + childNum + "]"].value)
               || roomConfigurationArray[roomNumber].childAges[childNum]==age) {
               childAges+= "<option value=\"" + age + "\" selected=\"selected\">" + age + "</option>";
            } else {
               childAges+= "<option value=\"" + age + "\">" + age + "</option>";
            }
         }
         childAges+= "</select></div>";
         childAges+= "</div>"
      }
   }
   getElem("room" + roomNumber + "_childrows").innerHTML = childAges;
}

function getRoomNumber(name) {
   var roomNumber = name.substring(name.indexOf("[")+1,name.indexOf("]."));
   return roomNumber;
}

function showHideCaption(numberOfRooms, form) {
	var currentCaptionId  =  "showcaption";
	if (form.name == 'frmLightboxSearch')
	{
		currentCaptionId = "showcaption1";
	}
   getElem(currentCaptionId).innerHTML = "";
   for(var i=0;i<numberOfRooms;i++) {
      if (form.elements["roomConfigurationFormBean.room[" + i + "].children"].value >0) {
         getElem(currentCaptionId).style.display = "block";
         getElem(currentCaptionId).innerHTML = "* Please enter ages on date of return";
         break;
      }
      else
      {
         getElem(currentCaptionId).style.display = "none";
      }
   }
}

var intticker_pos = 1
// Create colours
var waiting_color = new Array()
waiting_color[1] = '#FF9C00'
waiting_color[2] = '#FFE6B5'

/** Creates cycle effect  **/
function waiting_ticker() {
   if (intticker_pos++ == 10) { intticker_pos = 1 }
   for(intcounter=1;intcounter<3;intcounter++) {
      i = intticker_pos - intcounter
      if (i <= 0) { i = (10 - intcounter + intticker_pos) }
      eval('getElem("ticker'+i+'").style.backgroundColor="' + waiting_color[intcounter] + '"');
   }
}

/** Starts cycle effect **/
function waiting_start() {
   window.setInterval(waiting_ticker,141)
}

/** Function to display the next page **/
function forwardToNextPage( pageName) {
  if ( pageName == "search" ) {
    queryString = document.getElementById("userCriteriaQueryString").value;
    document.location.replace( "/thomson/page/byo/search/results.page?" + queryString);
  }
  else if ( pageName == "options" ) {
    queryString = document.getElementById("userCriteriaQueryString").value;
    var pageUrl = document.location.href;
    var packageNumber = document.getElementById("holidayPackageNumber").value;
    document.location.replace( "/thomson/page/byo/booking/traveloptions.page?packageNumber="+packageNumber+"&"+queryString);
  }
  /*else if ( pageName == "uioptions" ) {
    queryString = document.getElementById("userCriteriaQueryString").value;
    var pageUrl = document.location.href;
    var packageNumber = document.getElementById("holidayPackageNumber").value;
    document.location.replace( "/thomson/page/byo/booking/uitraveloptions.page?packageNumber="+packageNumber+"&"+queryString);
  }*/

  else if ( pageName == "brochureoptions" ) {
    queryString = document.getElementById("userCriteriaQueryString").value;
    var pageUrl = document.location.href;
    var packageNumber = document.getElementById("holidayPackageNumber").value;
    document.location.replace( "/thomson/page/byo/booking/brochuretraveloptions.page?packageNumber="+packageNumber+"&"+queryString);
  }
  else if ( pageName == "confirm" ) {
    document.location.replace( "/thomson/page/byo/booking/bookingsuccess.page" );
  }
  else if ( pageName == "shortlist" ) {
	document.location.replace( "/thomson/page/byo/shortlist/shortlist.page" );
  }
}

/** Function to display the next page **/
function forwardToBookmarkPage()
{
document.location.replace(document.location.href);
}

function enableElementById(id)
{
  document.getElementById(id).disabled=false;
}

function validateReSearchCriteria(searchType, form)
{
  if ((searchType=='refine' && document.getElementById('countryCode').value!='') ||
       (searchType=='alt' && document.getElementById('countryCode').value!=''))
  {
    FieldObjDay1 = getElem('calendar_day')
    FieldObjMonthYear1 = getElem('calendar_month_year')
    var currentDateObj=new Date(currentDate);
    var arrDateSplit = FieldObjMonthYear1.value.split('/')
    dateVar = arrDateSplit[0] + "/" + FieldObjDay1.options[FieldObjDay1.selectedIndex].value + "/" + arrDateSplit[1];
    var checkinDay=new Date(dateVar);
    var submitData = 'true';

    if(searchType == 'alt')
    {
      if(document.getElementById("flagExpandItems").value=='true')
      {
        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 calendarDay = document.getElementById("return_day").value;
        var calendarMonthYear = document.getElementById("return_month_year").value;

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

        if(no_of_days == '0')
        {
          alert("Please select longer duration");
          document.getElementById("duration").value = document.getElementById("durationshort").value;
          setReturnDate();
          getElem('long_duration').innerHTML = document.getElementById("duration").value+" Nights";
          submitData = 'false';
          getElem('return_day').focus();
        }
        else if(no_of_days<0)
        {
          alert("Return date must be greater than arrival date");
          document.getElementById("duration").value = document.getElementById("durationshort").value;
          setReturnDate();
          getElem('long_duration').innerHTML = document.getElementById("duration").value+" Nights";
          submitData = 'false';
          getElem('return_day').focus();
        }
        else if(no_of_days > '99')
        {
          alert("Please select upto 99 nights only");
          document.getElementById("duration").value = document.getElementById("durationshort").value;
          setReturnDate();
          getElem('long_duration').innerHTML = document.getElementById("duration").value+" Nights";
          submitData = 'false';
          getElem('return_day').focus();
        }
      }
      else
      {
        document.getElementById("duration").value = document.getElementById("durationshort").value;
      }
    }
    if(checkinDay.before(new Date(),6))
    {
      alert("Please select a date on or after "+currentDateObj.getDate()+"/"+(currentDateObj.getMonth()+1)+"/"+currentDateObj.getFullYear());
      submitData = 'false';

      var dateObj = new Date(currentDate);
      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;
        }
      }

      if(searchType=="alt")
      {
        document.getElementById('day').selectedIndex = currentDateObj.getDate()-1;
      }

      getElem('calendar_day').focus();
    }
    else if(checkinDay.after(new Date(maxSeasonDate),6))
    {
      alert(dateAfterMax);
      submitData = 'false';
      getElem('calendar_day').focus();
    }
    else
    {
      if(searchType=="refine")
      {
        if (document.getElementById("countryDestCode").selectedIndex > '0')
        {
          clearPredictivePanels()
        }
        enableElementById("countryCode",'enable');
        enableElementById("destinationCode",'enable');
        enableElementById("resortCode",'enable');
        enableElementById("accommodationCode",'enable');
      }
      else
      {
        var roomConfig = populateRoomConfigArray();
        var totalPartySize = 0;
        var totalAdultPartySize = 0;
        var totalInfantSize = 0;
        var childFlag=0;
        for(var i=0;i<roomConfig.length;i++)
        {
          var room = roomConfig[i];
          totalPartySize +=  parseInt(room.numAdults) + parseInt(room.numChildren);
          totalAdultPartySize += parseInt(room.numAdults);
          for(var j=0;j<room.childAges.length;j++)
          {
            if (room.childAges[j]=="-?-")
            {
              childFlag++;
            }
            if (room.childAges[j]>=16)
            {
              totalAdultPartySize++;
            }
            if (room.childAges[j]=="<2")
            {
              totalInfantSize++;
            }
          }
        }
        if(childFlag)
        {
          alert("Please enter child age");
          submitData = 'false';
          getElem('child_age').focus();
        }
        if (totalPartySize-totalInfantSize > maxPartySize)
        {
          submitData = 'false';
          alert(invalidPartySize);
        }
        else if (totalInfantSize > totalAdultPartySize)
        {
          alert(tooManyInfants)
          submitData = 'false';
        }
        else
        {
          if (document.getElementById("countryDestCode").selectedIndex > '0')
          {
            clearPredictivePanels()
          }
          constructRoomConfigurationString(roomConfig);
          enableElementById("destinationCode",'enable');
          enableElementById("resortCode",'enable');
          enableElementById("accommodationCode",'enable');
          document.getElementById("accommFeaturesBitValue").value = '0';
        }
      }
    }
    /*if (!checkSummer10Destinations())
    {
      submitData='false';
    }*/
    if(submitData == 'true')
    {
      var SearchHistoryTime = new Date()
      form.timestamp.value=SearchHistoryTime.getTime();
      form.submit();
    }
  }
  else
  {
    alert('Please select a destination');
    getElem('countryDestCode').focus();
  }
}


function replaceVariableInMessage(message, variable, value)
{
  if (message.indexOf('$'+variable)>-1)
  {
    return newMessage = message.substring(0,message.indexOf('$'+variable))+value+message.substring(message.indexOf('$'+variable)+variable.length+1, message.length);
  }
}

/* Functionality added to check whether cookies are enabled in the browser (Bug# 28729) */
function checkCookieState()
{
  var cookieEnabled = (navigator.cookieEnabled) ? true : false;
  if(!cookieEnabled)
  {
    alert("Cookies need to be enabled in order to process your request.");
    return false;
  }
  else
    return true;
}

// Checks for Maximum party size and no. of adults >= no. of infants
function validateSearchCriteria(form)
{
  if (checkCookieState())
  {
    if (validateSearchCriteriaForm(form))
    {
    	var SearchHistoryTime = new Date()
      	form.timestamp.value=SearchHistoryTime.getTime();
        form.target="_top";
        form.submit();

    }
  }
}

var brochureAttempt=0;
function validateBrochureSearchCriteria()
{
  document.getElementById('BrochureSearch').value = document.getElementById('BrochureSearch').value.toUpperCase();
  var brochureCorrect = validateBrochureCode();
  if(brochureAttempt < 3)
  {
    if(!brochureCorrect)
    {
        document.forms.frmBrochureSearch.target="_top";
      	brochureAttempt++;
     }
     else
     {
         document.forms.frmBrochureSearch.target="_top";
         document.forms.frmBrochureSearch.submit();
     }
  }
  if(brochureAttempt == 3)
  {
    document.getElementById("brochureCodeSubmit").style.display = "none";
    document.getElementById("brochureCode").style.display = "none";
    document.getElementById("brochureCodeHeading").style.display = "none";
    document.getElementById("brochureCodeError").innerHTML="<p>Sorry you have entered an incorrect code 3 times. Please search for your preferred accommodation below</p>"
    document.getElementById("brochureCodeError").style.display = "block"
    return false;
  }
  if(brochureAttempt<3 && !brochureCorrect)
  	return false;
  if(brochureAttempt<3 && brochureCorrect)
  	return true;
}

function checkSummer10Destinations()
{
  var depMonthYear = getElem('calendar_month_year').value.split("/");
  if ((depMonthYear[0] > 10 && depMonthYear[1]==2010) || (depMonthYear[1]>=2011))
  {
    if (checkForAvailDestinations(document.getElementById("countryDestCode").options[document.getElementById("countryDestCode").selectedIndex].text, document.getElementById("departure").value))
    {
      alert('For Winter 2010, the destinations you can currently book are:' + '\n' + '\n' + 'Costa Rica' + '\n' + 'Cuba' + '\n' + 'Dominican Republic' + '\n' + 'Florida' + '\n' + 'Goa' + '\n' + 'Jamaica' + '\n' + 'Kenya' + '\n' + 'Maldives' + '\n' + 'Mexico' + '\n' + 'Sri Lanka' + '\n' + '\n' + 'Even more great destinations will be available soon!');
      return false;
    }
    return true;
  }
  return true;
}

function checkForAvailDestinations(countryDestCode, departure)
{
  var key;
  if ((countryDestCode == '' || countryDestCode == 'Select a Destination') && departure != '')
  {
    // departure heirarchy can vary from one to 4. So based on wat the user has entered, making sure that we alwayc pick the destination.
    var depheirarchy = departure.split(",");
    if (depheirarchy.length > 3)
    {
      key = new String(depheirarchy[2]).replace(/^\s\s*/, '').replace(/\s\s*$/, '');
    }
    else if (depheirarchy.length == 3)
    {
      key = new String(depheirarchy[1]).replace(/^\s\s*/, '').replace(/\s\s*$/, '');
    }
    else
    {
      key = new String(depheirarchy[0]).replace(/^\s\s*/, '').replace(/\s\s*$/, '');
    }
  }
  else if ((countryDestCode != '' || countryDestCode != 'Select a Destination') && departure == '')
  {
    key = new String(countryDestCode).replace(/^\s\s*/, '').replace(/\s\s*$/, '');
    // for IE7, the trim function doesnt seem to working as expected. So chekcing if the key starts with a blank spalce.
    if (key.charCodeAt(0) == 160)
    {
      key = key.substring(3);
    }
  }

  //alert('Key Length : ' + key.length);
  //alert('Key : ' + key);
  var countryCodes = new Array("Dominican Republic","Dominican Republic East" ,"Dominican Republic North","- Dominican Republic North","Dominican Republic South","- Dominican Republic South","Dominican Republic - La Romana","- Dominican Republic - La Romana","- Dominican Republic - Puerto Plata","Dominican Republic - Puerto Plata","- Dominican Republic - Punta Cana","Dominican Republic - Punta Cana","- Dominican Republic - Samana","Dominican Republic - Samana","Mexico","Mexico - Caribbean Coast","Mexico - Pacific Coast","Mexico - Puerto Vallarta","Jamaica","Caribbean & Mexico","Cuba","- Cuba - Holguin","Cuba - Holguin","- Cuba - Varadero","Cuba - Varadero","Cuba - Havana","- Cuba - Havana","India","Goa","Sri Lanka","Africa","Cape Verde","Cape Verde Islands","Kenya","The Americas","United States Of America","New Mexico","Costa Rica","Florida","Indian Ocean","Maldives");
  for (var i=0; i<countryCodes.length; i++)
  {
    if (key == countryCodes[i])
    {
      return false;
    }
  }
  return true;
}

function trim(value)
{
   var temp = value;
   var obj = /^(\s*)([\W\w]*)(\b\s*$)/;
   if (obj.test(temp))
   {
    temp = temp.replace(obj, '$2');
   }
   var obj = /  /g;
   while (temp.match(obj))
   {
    temp = temp.replace(obj, " ");
   }
   return temp;
}

function validateSearchCriteriaForm(form)
{
   if (document.getElementById("countryCode").value!='')
   {
   /* Added this alert below from dynamic_location.js under the function validateCheckInDate()
   as per Bug #18834 to validate the date when onclick rather than resetting automatically */
   FieldObjDay1 = getElem('calendar_day')
   FieldObjMonthYear1 = getElem('calendar_month_year')
   var currentDateObj=new Date(currentDate);
   var arrDateSplit = FieldObjMonthYear1.value.split('/')
   dateVar = arrDateSplit[0] + "/" + FieldObjDay1.options[FieldObjDay1.selectedIndex].value + "/" + arrDateSplit[1];
   var checkinDay=new Date(dateVar);
   var currentDateObj=new Date(currentDate);

   if (checkinDay.before(currentDateObj))
   {
      alert("Please select a date on or after "+currentDateObj.getDate()+"/"+(currentDateObj.getMonth()+1)+"/"+currentDateObj.getFullYear());
      // document.getElementById('day').selectedIndex = currentDateObj.getDate() - 1;
      resetCheckInDate(currentDate);
   }
   else
   {
    var roomConfig = populateRoomConfigArray(form);
    var totalPartySize = 0;
    var totalAdultPartySize = 0;
    var totalInfantSize = 0;
    var childFlag=0;
    for(var i=0;i<roomConfig.length;i++) {
       var room = roomConfig[i];
       totalPartySize +=  parseInt(room.numAdults) + parseInt(room.numChildren);
       totalAdultPartySize += parseInt(room.numAdults);
       for(var j=0;j<room.childAges.length;j++) {
          if (room.childAges[j]=="-?-")
          {
             childFlag++;
          }
          if (room.childAges[j]>=16) {
             totalAdultPartySize++;
          }
          if (room.childAges[j]=="<2") {
             totalInfantSize++;
          }
       }
    }
    if (totalPartySize-totalInfantSize > maxPartySize) {
       alert(invalidPartySize);
    } else if (totalInfantSize > totalAdultPartySize) {
       alert(tooManyInfants)
    }
    else
    {
      if(childFlag){
        alert("Please enter child age");
        getElem('child_ages').focus();
      }
      else
      {
        if (document.getElementById("countryDestCode").selectedIndex > '0')
        {
          clearPredictivePanels()
        }
        checkBox();
        constructRoomConfigurationString(roomConfig, form);
        enableElementById("destinationCode");
        enableElementById("resortCode");
        enableElementById("accommodationCode");
        return true;
      }
    }
   }
  }else{
    alert('Please select a destination');
    getElem('countryDestCode').focus();
  }
}

function validateLateCriteria(formObj)
{
   var roomConfig = populateRoomConfigArray(formObj);
   var totalPartySize = 0;
   var totalAdultPartySize = 0;
   var totalInfantSize = 0;
   var childFlag=0;
   for(var i=0;i<roomConfig.length;i++)
   {
    var room = roomConfig[i];
    totalPartySize +=  parseInt(room.numAdults) + parseInt(room.numChildren);
    totalAdultPartySize += parseInt(room.numAdults);
    for(var j=0;j<room.childAges.length;j++)
     {
        if (room.childAges[j]=="-?-")
        {
           childFlag++;
        }
        if (room.childAges[j]>=16) {
           totalAdultPartySize++;
        }
        if (room.childAges[j]=="<2") {
           totalInfantSize++;
        }
       }
    }
    if (totalPartySize-totalInfantSize > maxPartySize)
    {
      alert(invalidPartySize);
    }
    else if (totalInfantSize > totalAdultPartySize)
    {
      alert(tooManyInfants)
    }
    else if(childFlag)
    {
      alert("Please enter child age");
      getElem('child_ages').focus();
    }
    else
    {
      constructRoomConfigurationString(roomConfig,formObj);
      formObj.timestamp.value=Calendar.getTime();
      formObj.submit();
    }
}

function constructRoomConfigurationString(roomConfig, form)
{
   var roomConfigurationString = "";
   for(var i=0;i<roomConfig.length;i++) {
      var room = roomConfig[i];
      var childAgesString = "";
      roomConfigurationString +=  room.roomNumber + "|" + room.numAdults + "|" + room.numChildren + "|";
      for(var j=0;j<room.childAges.length;j++) {
         childAgesString += room.childAges[j] + "-";
      }
      childAgesString = childAgesString.substring(0,childAgesString.length-1);
      if (childAgesString=="") {
         roomConfigurationString = roomConfigurationString.substring(0,roomConfigurationString.length-1);
      }
      roomConfigurationString += childAgesString + "/";
   }
   form.partyRoomConfiguration.value = roomConfigurationString;
}


function checkBox()
{
  var total=0;
  for(i=1;i<=searchAttributeCount;i++)
  {
    var countAttribute= document.getElementById('holidayAttribute_'+i);
    if(countAttribute)
    {
      if(countAttribute.checked)
      {
        attribVal= parseInt(countAttribute.value);
        total=total + attribVal;
      }
    }
  }
  document.getElementById("accommFeaturesBitValue").value = total;
}

function changeDropdownStyle(elemId, size) {
  document.getElementById(elemId).setAttribute("size",size);
}

function updateListWithLocations(hideId, showId, updateId, form) {
  if ((hideId.indexOf("Resorts")>-1 && document.getElementById("destinationCode").value!="") || hideId.indexOf("Destinations")>-1) {
    document.getElementById(showId).style.display="block";
    document.getElementById(hideId).style.display="none";
    DynamicUpdate(updateId, 'change', '', form);
  }
}

function resetLocationLevel(elemId) {
  if (getElem(elemId).value.indexOf("COUNTRY") > -1) {
    getElem(elemId).selectedIndex = getElem(elemId).selectedIndex + 1;
  }
  DynamicUpdate(elemId, "change",'' ,form);
}

/* Result Map */

/* GeoCode object. */
function GeoCode(lon, lat, placeName, accomId)
{
   this.lon = lon;
   this.lat = lat;
   this.placeName = placeName;
   this.accomId = accomId;
}

/* Forms the query need to execute to get the result map. */
function formResultMapUrl(geoCode)
{
  var resultMapQuery = "client="+multiMapClient+"&width="+resultMapWidth+"&height="+resultMapHeight+"&lllist=";
  var geoCodesQuery = "";
  if (!geoCode)
  {
     for(var i=0;i<GeoCodes.length;i++)
     {
        if (isHotelDuplicate(GeoCodes[i].placeName, GeoCodes))
        {
           GeoCodes[i].lon = "";
           GeoCodes[i].lat = "";
           GeoCodes[i].placeName = "";
        }
        if (GeoCodes[i].lon!="" && GeoCodes[i].lat!="" && isHotelSelected(i))
        {
           geoCodesQuery += GeoCodes[i].lon + "," + GeoCodes[i].lat + ",";
        }
     }
  }else{
     geoCodesQuery = geoCode.lon + "," + geoCode.lat + ",";
  }
  geoCodesQuery = geoCodesQuery.substring(0, geoCodesQuery.length-1);
  resultMapQuery += geoCodesQuery;
   return "/thomson/page/byo/resultmap/resultmap.page?" + resultMapQuery;
}

function isHotelSelected(reference)
{
   if (getElem("chk_result_"+(reference+1)))
   {
      return getElem("chk_result_"+(reference+1)).checked;
   }else{
      return true;
   }
}

/* Check whether passed hotel exists more than once in the GeoCodes array. */
function isHotelDuplicate(hotelToSearch, geoCodeArray)
{
   var hotelCount = 0;
   for(var j=0;j<geoCodeArray.length;j++)
   {
      if (geoCodeArray[j].placeName==hotelToSearch)
      {
         hotelCount++;
      }
   }
   if (hotelCount>1)
   {
      return true;
   }
   return false;
}

/* Checks whether the longitude and latitude values are present
in the GeoCode object. */
function checkGeoCodesAvailability() {
   var available = false;
   for(var i=0;i<GeoCodes.length;i++)
   {
      if (GeoCodes[i].longitude!='' && GeoCodes[i].latitude!='')
      {
         available = true;
         break;
      }
   }
   return available;
}

function viewHotelOnMap(accomId) {
  for(var i=0;i<GeoCodes.length;i++)
  {
     if (GeoCodes[i].accomId == accomId)
     {
        if (getElem('map_container'))
        {
           var url = formResultMapUrl(GeoCodes[i]);
           url = url + "&mapType=singleHotel"
           getElem('map_container').style.display = "block";
           loadResultMapThroughIframe("dynamicFrame", url);
           break;
        }
     }
  }
}

/* Responsible for making AJAX call to map service. */
function getResultMap() {
   if (checkGeoCodesAvailability())
   {
      var el = getElem('resultmap');
      var content = el.firstChild;
      while (content && content.tagName != 'DIV') { content = content.nextSibling }
      displayContent('resultmap');
      if (currentStyle(content, 'display')=='block')
      {
         document.getElementById('resultmapmenu').innerHTML=hideMap;
         var url = formResultMapUrl();
         if (!getElem("resultMapContainer") || (getElem("resultMapContainer") && getElem("resultMapContainer").innerHTML.toLowerCase().indexOf("img")==-1))
         {
            loadResultMapThroughIframe("dynamicFrame", url);
         }
      }else{
        document.getElementById('resultmapmenu').innerHTML=showMap;
      }
   }
   else
   {
      if (getElem("resultMapContainer")) getElem("resultMapContainer").innerHTML="No map available.";
   }
}

function refreshResultMap() {
   var url = formResultMapUrl();
   if (areHotelsSelected()) {
     loadResultMapThroughIframe("dynamicFrame", url);
   }else{
     alert("Please select atleast one hotel to view on map.");
   }
}

function showMapLoadingMessage() {
   if (getElem("resultMapContainer")) getElem("resultMapContainer").innerHTML="Loading Map...";
   for(var i=1;i<=GeoCodes.length;i++) {
      if (getElem("result_"+i)) getElem("result_"+i).style.display="none";
   }

}

/* Pans the result map. */
function panResultMap(direction) {
   if (areHotelsSelected()) {
     //showMapLoadingMessage();
     var url = formResultMapUrl();
     url += "&amp;X=" + getElem("multiMapX").innerHTML + "&amp;Y=" + getElem("multiMapY").innerHTML + "&amp;" + direction + "&amp;scale=" + getElem("scale").innerHTML ;
     loadResultMapThroughIframe("dynamicFrame", url);
   }else{
     alert("Please select atleast one hotel to view on map.");
   }
}

/* Zoom in/out the result map. */
function zoomResultMap(direction) {
   if (areHotelsSelected()) {
     if ((getElem("scaleList").selectedIndex + direction)>=0 && (getElem("scaleList").selectedIndex + direction)<=(getElem("scaleList").length-1)) {
        var scaleToZoom = getElem("scaleList").options[getElem("scaleList").selectedIndex + direction].value;
        var url = formResultMapUrl();
        url += "&amp;scale=" + scaleToZoom ;
        loadResultMapThroughIframe("dynamicFrame", url);
     }
   }else{
     alert("Please select atleast one hotel to view on map.");
   }
}

/* Scales map to the given scale. */
function scaleResultMap(scale) {
   var currentscale=getElem("scale").innerHTML;
   if (areHotelsSelected()) {
     var url = formResultMapUrl();
     url += "&amp;scale=" + scale;
     loadResultMapThroughIframe("dynamicFrame", url);
   }else{
     alert("Please select atleast one hotel to view on map.");
     getElem("scaleList").value=currentscale;
   }
}

function loadResultMapThroughIframe(iframeName, url) {
   eval(iframeName+".document.location.replace('"+url+"')");
   updateHotelName();
}

/* Updates the result map marker legend with the hotel names as returned
from the search results. */
function updateHotelName(geoCodeList, mapType)
{

   if (getElem("hotel_checkboxes") && geoCodeList)
   {
      codesFromReq = geoCodeList.split(",");
      var hotelCheckBoxes = "<ol id='map'>";
      for(var i=1;i<=GeoCodes.length;i++)
      {
         var checkedStatus = "";
         if (mapType=="singleHotel")
         {
            if (getElem("marker_label_1") && GeoCodes[i-1].lon==codesFromReq[0] && GeoCodes[i-1].lat==codesFromReq[1])
            {
               checkedStatus = "checked='checked'";
            }
         }else{
            for(var j=0;j<codesFromReq.length;j++)
            {
               if (codesFromReq[j+1] && GeoCodes[i-1].lon==codesFromReq[j] && GeoCodes[i-1].lat==codesFromReq[j+1])
               {
                  checkedStatus = "checked='checked'";
               }
               j++;
            }
         }
   var variableAccomIdVal=String(GeoCodes[i-1].accomId);
  //Fragmenting the array object value into 2 parts to avoid calling of native method parseInt during  parameter parsing
  //as it may lead in invalid values if the object value lies out of range.
   var variableAccomIdPart1=variableAccomIdVal.substring(0,((variableAccomIdVal.length)/4));
   var variableAccomIdPart2=variableAccomIdVal.substr(((variableAccomIdVal.length)/4),((variableAccomIdVal.length)/2));
   var variableAccomIdPart3=variableAccomIdVal.substr((variableAccomIdVal.length)/2,((3*(variableAccomIdVal.length))/4));
   var variableAccomIdPart4=variableAccomIdVal.substr((3*(variableAccomIdVal.length)/4),variableAccomIdVal.length);

   hotelCheckBoxes = hotelCheckBoxes + "<li><input type='checkbox' "+checkedStatus+" name='chk_result_"+i+"' id='chk_result_"+i+"' onclick='toggleMapMarker("+i+")'><a href='javascript:GoToResult("+variableAccomIdPart1+","+variableAccomIdPart2+","+variableAccomIdPart3+","+variableAccomIdPart4+","+ i+")'> "+i+".&nbsp;"+GeoCodes[i-1].placeName+"</a></li>";
      }
      hotelCheckBoxes = hotelCheckBoxes + "</ol>";
   getElem("hotel_checkboxes").innerHTML = hotelCheckBoxes;
      updateHotelLegends(codesFromReq);
      //uncheckNonVisibleHotels();
   }
  }

function uncheckNonVisibleHotels() {
   for(var i=1;i<=GeoCodes.length;i++) {
      getElem("chk_result_"+i).checked = false;
   }
   for(var i=1;i<=GeoCodes.length;i++) {
      if (getElem("result_"+i)) {
         getElem("chk_result_"+(getElem("result_"+i).innerHTML)).checked = true;
      }
   }
}

function updateHotelLegends(codesFromReq) {
   var returnedCodeArr = new Array();
   for(var i=0;i<codesFromReq.length;i=i+2) {
      returnedCodeArr[returnedCodeArr.length] = new GeoCode(codesFromReq[i], codesFromReq[i+1], "", "");
   }
   for(var i=1;i<=returnedCodeArr.length;i++) {
      for(var j=1;j<=GeoCodes.length;j++) {
         if (GeoCodes[j-1].lon==returnedCodeArr[i-1].lon && GeoCodes[j-1].lat==returnedCodeArr[i-1].lat) {
            if (getElem("result_"+i)) {
               getElem("result_"+i).innerHTML = j;
               break;
            }
         }
      }
   }
}

function areHotelsSelected() {
  var hotelsSelected = false;
   for(var i=0;i<GeoCodes.length;i++) {
      if (GeoCodes[i].lon!="" && GeoCodes[i].lat!="" && isHotelSelected(i)) {
        hotelsSelected = true;
        break;
     }
  }
  return hotelsSelected;
}

/* Hides/displays the location marker on the result map on click of the
check box. */
function toggleMapMarker(id) {
  var markerId = "result_" + id;
 var marker = document.getElementById(markerId);
 var checkbox = document.getElementById("chk_result_"+id);

 if (marker)
 {
    marker.style.visibility = checkbox.checked ? "visible" : "hidden";
 }
}

function toggleMapMarkerByLabel(id) {
/*
 var checkbox = document.getElementById("chk_result_"+id);
   if (checkbox.checked){
   checkbox.checked = false;
   } else {
   checkbox.checked = true;
 }
*/
 toggleMapMarker(id)
}

function checkHotels(status) {
   for(var j=1;j<=GeoCodes.length;j++) {
      getElem("chk_result_"+j).checked = status;
      toggleMapMarker(j);
   }
   if (status) {
      refreshResultMap();
   }
}

/* Renders the content from the AJAX response into the 'finalContainer' DIV */
var displayResultMap = function(response)
{
   getElem("map_container").innerHTML = response;
   updateHotelName();
}

/* toCamelCase: example "font-size".toCamelCase() -> "fontSize" */
String.prototype.toCamelCase = function() {
   return this.replace(/-([a-z])/g, function(a, b) { return b.toUpperCase(); });
};

function currentStyle(el, property) {
   var d = document;
   var v = null;
   if (d.defaultView && d.defaultView.getComputedStyle) {
      var style = d.defaultView.getComputedStyle(el, null);
      v = style && style.getPropertyValue(property);
   } else if (el.currentStyle) {
      v = el.currentStyle[property.toCamelCase()];
   }
   if (v == null && el.style) {
      v = el.style[property.toCamelCase()];
   }
   return v;
}


function displayContent(elementId, fromIndex) {
  var el = getElem(elementId);
  if (el) {
    var content = el.firstChild;
    while (content && content.tagName != 'DIV') { content = content.nextSibling }
    if (content) {
      if (currentStyle(content, 'display') == 'block') {
        if (!fromIndex) {
          content.style.display = 'none';
          el.style.display = 'none';
        }
      } else {
        content.style.display = 'block';
        el.style.display = 'block';
      }
    }
  }
}
/* / Result Map */

function showError(){
   if(document.getElementById('errormessage').innerHTML!='') {
      alert(document.getElementById('errormessage').innerHTML);
   }
}

function saveSelectedHotel(holidayId) {
   var url = "/thomson/page/byo/search/saveselectedhotel.page?packageId=" + holidayId + "&task=save";
   saveHotelIframe.document.location.replace(url);
}

function removeSelectedHotel(obj,holidayId) {
   var url = "/thomson/page/byo/search/removeselectedhotel.page?ico=AOSearchRes_Remove&packageId=" + holidayId + "&task=remove";
   saveHotelIframe.document.location.replace(url);

   var element='saveHotelId'+accommodationId;
   objName=document.getElementById(element);
   objName.checked = false;
}
function handleRadioButtons() {
   for ( var i=0; i < document.searchForm.subtype.length; i++ ) {
      if ( eval(document.searchForm.subtype[i]) && document.searchForm.subtype[i].checked ) {
         if ( document.searchForm.subtype[i].value == "sun" ) {
            SPI.params.subtype = 'sun';
         }
         else if ( document.searchForm.subtype[i].value == "city") {
            SPI.params.subtype = 'city';
            document.searchForm.subtype[i].value = cityContextDesc+"|"+cityContextId;
         } else if ( document.searchForm.subtype[i].value == "accom") {
            SPI.params.subtype = 'accom';
            document.searchForm.subtype[i].value = villaContextDesc+"|"+villaContextId;
         }
      }
      if ( document.searchForm.subtype[i].value == "sun" ) {
         document.searchForm.subtype[i].value = sunContextDesc+"|"+sunContextId;
      } else if ( document.searchForm.subtype[i].value == "city") {
         document.searchForm.subtype[i].value = cityContextDesc+"|"+cityContextId;
      } else if ( document.searchForm.subtype[i].value == "accom") {
         document.searchForm.subtype[i].value = villaContextDesc+"|"+villaContextId;
      }
      document.searchForm.subtype[i].onclick = function() {
      DynamicUpdate("subtype","change",'',form);
      }
   }
}

function resetSubType() {
   for ( var i=0; i < document.searchForm.subtype.length; i++ ) {
      if ( eval(document.searchForm.subtype[i]) && document.searchForm.subtype[i].value==selectedSubType ) {
         document.searchForm.subtype[i].checked = true;
      }
   }
}

/*function displayAltRooms(elemId) {
   obj = document.getElementById(elemId);
   if (currentStyle(obj, 'display')=="block") {
      obj.style.display = "none";
      document.getElementById("lessRoomsLink").style.display = "none";
      document.getElementById("moreRoomsLink").style.display = "block";
   } else {
      obj.style.display = "block";
      document.getElementById("lessRoomsLink").style.display = "block";
      document.getElementById("moreRoomsLink").style.display = "none";
   }
}*/

function saveThisPackage(holidayId) {
   if(getElem("favlink_add"+holidayId)) {
      getElem("favlink_add"+holidayId).style.display="none";
      getElem("favlink_remove"+holidayId).style.display="";
   }
   $.ajax({
     url: "/thomson/page/byo/search/saveselectedpackage.page?packageId=" + holidayId + "&task=save",
     cache: false,
     success: function(html){
        if (($.trim(html)).substring(0, "<!-- Don't delete -->".length) == "<!-- Don't delete -->") {
           $("#contentCol3").html(html);
           shortlistinit();
        }
        else {
            window.document.location.reload(true);
        }
     }
   });
}

function removeThisPackage(holidayId) {
   if(getElem("favlink_add"+holidayId)) {
      getElem("favlink_add"+holidayId).style.display="";
      getElem("favlink_remove"+holidayId).style.display="none";
   }
   $.ajax({
     url: "/thomson/page/byo/search/removeselectedpackage.page?packageId=" + holidayId + "&task=remove",
     cache: false,
     success: function(html){
        if (($.trim(html)).substring(0, "<!-- Don't delete -->".length) == "<!-- Don't delete -->") {
            $("#contentCol3").html(html);
            shortlistinit();
        }
        else {
            window.document.location.reload(true);
        }
     }
   });
}

function saveSelectedPackage(holidayId) {
   if(getElem("favlink_add"+holidayId)) {
      getElem("favlink_add"+holidayId).style.display="none";
      getElem("favlink_remove"+holidayId).style.display="";
   }
   var url = "/thomson/page/byo/search/saveselectedpackage.page?packageId=" + holidayId + "&task=save";
   saveHotelIframe.document.location.replace(url);
}

function removeSelectedPackage(obj,holidayId) {
   if(getElem("favlink_add"+holidayId)) {
      getElem("favlink_add"+holidayId).style.display="";
      getElem("favlink_remove"+holidayId).style.display="none";
   }
   var url = "/thomson/page/byo/search/removeselectedpackage.page?packageId=" + holidayId + "&task=remove";
   saveHotelIframe.document.location.replace(url);
}

function loadDetailsContent(type, accomId) {
   listElements = getElem("detailsToc_"+accomId).getElementsByTagName("li");
   for(i=0;i<listElements.length;i++) {
      listElements[i].className = "";
      //if (listElements[i].id == ("photosLi_"+accomId) || listElements[i].id == ("videosLi_"+accomId) || listElements[i].id == ("mapLi_"+accomId) || listElements[i].id == ("reviewsLi_"+accomId) || listElements[i].id == ("printLi_"+accomId) ) {
   if (listElements[i].id == ("printLi_"+accomId) ) {
         listElements[i].className = "icon";
      }
   }
   innerHtml = getElem(type+"_"+accomId).innerHTML;
   if (innerHtml.indexOf("largeSlide_")>-1) {
      innerHtml = innerHtml.substring(0,innerHtml.indexOf("largeSlide_"))+"slide1_"+innerHtml.substring(innerHtml.indexOf("largeSlide_")+11,innerHtml.length);
   }
   if(innerHtml.indexOf("slideShowIndex_")>-1) {
      innerHtml = innerHtml.substring(0,innerHtml.indexOf("slideShowIndex_"))+"slideIndex_"+innerHtml.substring(innerHtml.indexOf("slideShowIndex_")+15,innerHtml.length);
   }
   if (innerHtml.indexOf("thumbMask_")>-1)
   {
      innerHtml = innerHtml.substring(0,innerHtml.indexOf("thumbMask_"))+"thumbMask1_"+innerHtml.substring(innerHtml.indexOf("thumbMask_")+10,innerHtml.length);
   }
   if (innerHtml.indexOf("thumbsContent_")>-1)
   {
      innerHtml = innerHtml.substring(0,innerHtml.indexOf("thumbsContent_"))+"thumbsContent1_"+innerHtml.substring(innerHtml.indexOf("thumbsContent_")+14,innerHtml.length);
   }

   if (innerHtml.indexOf('autostart="false"')>-1)
   {
      innerHtml = innerHtml.substring(0,innerHtml.indexOf('autostart="false"'))+'autostart="true"'+innerHtml.substring(innerHtml.indexOf('autostart="false"')+17,innerHtml.length);
   }
   if (type=='thomsonFlyLonghaul')
   {
      //innerHtml = "<iframe src='/thomson/cms?direct=byo/images/backgrounds/longhauldetailscontent.gif' frameborder="0" marginheight="0" marginwidth="0" scrolling="0" style='height:1056px;width:508px;'></iframe>";
      if (!ie6)
      {
        innerHtml = "<img src='/thomson/cms?direct=byo/images/backgrounds/Extralegroomv3a.gif'/>";
      }
   }

   while (innerHtml.indexOf("briefdesc_")>-1)
   {
      innerHtml = innerHtml.substring(0,innerHtml.indexOf("briefdesc_"))+"briefdesc1_"+innerHtml.substring(innerHtml.indexOf("briefdesc_")+10,innerHtml.length);
   }
   while (innerHtml.indexOf("fulldesc_")>-1)
   {
      innerHtml = innerHtml.substring(0,innerHtml.indexOf("fulldesc_"))+"fulldesc1_"+innerHtml.substring(innerHtml.indexOf("fulldesc_")+9,innerHtml.length);
   }
   while (innerHtml.indexOf("review_")>-1)
   {
      innerHtml = innerHtml.substring(0,innerHtml.indexOf("review_"))+ "review1_" + innerHtml.substring(innerHtml.indexOf("review_")+7,innerHtml.length);
   }

   getElem("description_container_"+accomId).innerHTML = innerHtml;
   if (type=="photos") { getElem("description_container_"+accomId).className="photogallery"; }
   else { getElem("description_container_"+accomId).className="textgallery"; }

   //if (type=="photos" ||type=="videos" ||type=="map" ||type=="reviews" ||type=="print" ) {
   if (type=="print" ) {
      getElem(type+"Li_"+accomId).className = "active icon";}
   else {
      getElem(type+"Li_"+accomId).className = "active";
   }
   getElem("printLi_"+accomId).className = "icon print";// force the print header to have no background
   if (type=="photos")
   {
     slideShow = getSlideShow(accomId);
     var imageArray = slideShow.imgArray;
     resizeImage(accomId, imageArray[0].reference);
   }
}

function displayHolidayDetails(accomId,linkName) {
   eval("detailsFrame_"+accomId).location.replace("/thomson/page/byo/details/details.page?packageNumber="+accomId+"&linkName="+linkName);
   getElem("holidayDetails_"+accomId).style.display = "inline";
   /*getElem("close_"+accomId).style.display = "inline";
   getElem("expand_"+accomId).style.display = "none";*/
   if (getElem("holidayDetailWrapper_"+accomId))
   {
     getElem("holidayDetailWrapper_"+accomId).style.backgroundColor = "#ffffe7";
   }
   if(document.getElementById("chooseandcontinue_"+accomId) != null){
   document.getElementById("chooseandcontinue_"+accomId).style.display = "inline";
    }
   if(document.getElementById("expandlink_"+accomId) != null)
    {
   document.getElementById("expandlink_"+accomId).style.display = "none";
   document.getElementById("expandimg_"+accomId).src='/thomson/cms/thomson.co.uk/byo/search/results?reference=ps_btn_choosecontinue'
    }
   //if(document.getElementById("cnlh_"+accomId))
   //{
      //document.getElementById("expandLonghaul_"+accomId).src='/thomson/cms?direct=byo/images/backgrounds/longhaul_expanded.gif'
      //if (getElem('cnlh_'+accomId)){getElem('cnlh_'+accomId).className='excnlh'};
   //}
}

function openImage(accomId,accomType,link)
{
    var elem = getElem('exCloseButton_'+accomId);
    if(elem.className=="exCloseButton" || elem.className=="exSelectedButton")
    {
        elem.className="cnCloseButton";
        //document.getElementById("expandButton_"+accomId).src='/thomson/cms/thomson.co.uk/byo/search/results?reference=contractButton';
        for(var i =0 ; i < 1000000 ; i++){}
        if(accomType == 'normal')
        {
            document.getElementById("href_"+accomId).onclick = function()
            {
                closeImage(accomId,accomType);
                hideExpandedDetails(accomId);
            }
        }
        if(accomType == 'ld')
        {
            document.getElementById("href_"+accomId).onclick = function()
            {
                closeImage(accomId,accomType);
                hideLateDealDetails(accomId);
            }
        }
        if(accomType == 'pb')
        {
            document.getElementById("href_"+accomId).onclick = function()
            {
                closeImage(accomId,accomType);
                hidePriceBreakDetails(accomId);
            }
        }
        if(accomType == 'evpb')
        {
            document.getElementById("href_"+accomId).onclick = function()
            {
                closeImage(accomId,accomType);
                hideExtraPriceBreakDetails(accomId);
            }
        }
        return;
    }
    if(link == 'h')
    {
        if(elem.className=="cnCloseButton")
        {
            elem.className="exSelectedButton";
            for(var i =0 ; i < 1000000 ; i++){}
            if(accomType == 'normal')
            {
                document.getElementById("href_"+accomId).onclick = function()
                {
                  openImage(accomId,accomType);
                  displayHolidayDetails(accomId);
                }
            }
            if(accomType == 'ld')
            {
                document.getElementById("href_"+accomId).onclick = function()
                {
                   openImage(accomId,accomType);
                   displayLateDealDetails(accomId);
                }
            }
            if(accomType == 'pb')
            {
                document.getElementById("href_"+accomId).onclick = function()
                {
                    openImage(accomId,accomType);
                    displayPriceBreakDetails(accomId);
                }
            }
            if(accomType == 'evpb')
            {
                document.getElementById("href_"+accomId).onclick = function()
                {
                   openImage(accomId,accomType);
                   displayExtraPriceBreakDetails(accomId);
                }
            }
            return;
        }
    }
}

function closeImage(accomId,accomType)
{
  if(getElem('exCloseButton_'+accomId).className=="cnCloseButton")
  {
     if(accomType == 'normal')
     {
        getElem('exCloseButton_'+accomId).className="exSelectedButton";
        document.getElementById("href_"+accomId).onclick = function()
        {
        openImage(accomId,accomType);
        displayHolidayDetails(accomId);
        }
     }
     if(accomType == 'ld')
     {
        getElem('exCloseButton_'+accomId).className="exSelectedButton";
        document.getElementById("href_"+accomId).onclick = function()
        {
           openImage(accomId,accomType);
           displayLateDealDetails(accomId);
        }
     }
    if(accomType == 'pb')
     {
        getElem('exCloseButton_'+accomId).className="exSelectedButton";
        document.getElementById("href_"+accomId).onclick = function()
        {
        openImage(accomId,accomType);
        displayPriceBreakDetails(accomId);
        }
     }
    if(accomType == 'evpb')
     {
        getElem('exCloseButton_'+accomId).className="exSelectedButton";
        document.getElementById("href_"+accomId).onclick = function()
        {
           openImage(accomId,accomType);
           displayExtraPriceBreakDetails(accomId);
        }
     }
   }
}

function displayHoliday(accomId,linkName) {
   var detailsViewed=false;
   if(  getElem("holidayDetails_"+accomId).style.display == "inline")
   {
      detailsViewed=true;
   }
   if(detailsViewed !=true)
   {
       displayHolidayDetails(accomId,linkName);
   }
   else
   {
      hideExpandedDetails(accomId);

   }
}
function hideExpandedDetails(accomId) {
   getElem("holidayDetails_"+accomId).innerHTML = "<div class='loadingMessage'>Loading accommodation details...</div>";
   getElem("holidayDetails_"+accomId).style.display = "none";
   /*getElem("close_"+accomId).style.display = "none";*/
   if(getElem("expand_"+accomId)!= null)
     {
   getElem("expand_"+accomId).style.display = "inline";
     }
   /*getElem("holidayDetailWrapper_"+accomId).style.backgroundColor = "#fff";*/
}

function displayChangeFlightResults(obj) {
   var displaySelectedList = "selectedListOfHolidays="+obj;
   document.location.replace("/thomson/page/byo/search/changeflight.page?" + displaySelectedList+"#resultsStart");
}

function submitScheduledFlightSearch(obj) {
   var searchScheduledFlightQuery = "airportDate="+obj;
   document.location.replace("/thomson/page/byo/search/changeflight.page?" + searchScheduledFlightQuery);
}

function displayChangeFlightAirportResults(obj) {
   var displaySelectedAirportList = "selectedDepartureAirport="+obj;
   document.location.replace("/thomson/page/byo/search/changeflight.page?" + displaySelectedAirportList+"#resultsStart");
}

function displayChangeFlightByDateResults(obj) {
   var displaySelectedAirportList = "selectedDepartureDate="+obj;
   document.location.replace("/thomson/page/byo/search/changeflight.page?" + displaySelectedAirportList+"#resultsStart");
}

function displayAllFlights()
{
   var displayAllAirportList = "selectedAllFlights="+'showAllFlights';
   document.location.replace("/thomson/page/byo/search/changeflight.page?" + displayAllAirportList+"#resultsStart");
}
function displayLateDealDetails(accomId)
{
   eval("detailsFrame_"+accomId).location.replace("/thomson/page/byo/details/latedealdetails.page?packageNumber="+accomId);
   getElem("lateDealDetails_"+accomId).style.display = "inline";
   /*getElem("closelatedeal_"+accomId).style.display = "inline";
   getElem("expandlatedeal_"+accomId).style.display = "none"; */
   getElem("holidayDetailWrapper_"+accomId).style.backgroundColor = "#ffffe7";
   document.getElementById("chooseandcontinue_"+accomId).style.display = "inline";
   document.getElementById("expandlink_"+accomId).style.display = "none";
   document.getElementById("expandimg_"+accomId).src='/thomson/cms/thomson.co.uk/byo/search/results?reference=ps_btn_choosecontinue'
}

function displayLateHoliday(accomId){
   var detailsViewed=false;
   if(  getElem("pricebreakDetails_"+accomId).style.display =="inline")

   {
      detailsViewed=true;
   }
   if(detailsViewed !=true)
   {
         displayLateDealDetails(accomId);
   }
   else
   {
      hideLateDealDetails(accomId);

   }
}
function hideLateDealDetails(accomId) {
   getElem("lateDealDetails_"+accomId).innerHTML = "<div class='loadingMessage'>Loading late deal details...</div>";
   getElem("lateDealDetails_"+accomId).style.display = "none";
   /*getElem("closelatedeal_"+accomId).style.display = "none";*/
   getElem("expandlatedeal_"+accomId).style.display = "inline";
   /*getElem("holidayDetailWrapper_"+accomId).style.backgroundColor = "#fff";*/
}

function displayPriceBreakDetails(accomId)
{
   eval("detailsFrame_"+accomId).location.replace("/thomson/page/byo/details/pricebreaker.page?packageNumber="+accomId);
   getElem("pricebreakDetails_"+accomId).style.display = "inline";
/*   getElem("closepricebreak_"+accomId).style.display = "inline";
   getElem("expandpricebreak_"+accomId).style.display = "none";*/
   getElem("holidayDetailWrapper_"+accomId).style.backgroundColor = "#ffffe7";
   document.getElementById("chooseandcontinue_"+accomId).style.display = "inline";
   document.getElementById("expandlink_"+accomId).style.display = "none";
   document.getElementById("expandimg_"+accomId).src='/thomson/cms/thomson.co.uk/byo/search/results?reference=ps_btn_choosecontinue'
}

function hidePriceBreakDetails(accomId) {
   getElem("pricebreakDetails_"+accomId).innerHTML = "<div class='loadingMessage'>Loading price breaker details...</div>";
   getElem("pricebreakDetails_"+accomId).style.display = "none";
   /*getElem("closepricebreak_"+accomId).style.display = "none";*/
   getElem("expandpricebreak_"+accomId).style.display = "inline";
   /*getElem("holidayDetailWrapper_"+accomId).style.backgroundColor = "#fff";*/
}

function displayPriceHoliday(accomId){
   var detailsViewed=false;
   if(  getElem("pricebreakDetails_"+accomId).style.display =="inline")

   {
      detailsViewed=true;
   }
   if(detailsViewed !=true)
   {
        displayPriceBreakDetails(accomId);
   }
   else
   {
      hidePriceBreakDetails(accomId);

   }
}
function displayExtraPriceBreakDetails(accomId)
{
   eval("detailsFrame_"+accomId).location.replace("/thomson/page/byo/details/extrapricebreak.page?packageNumber="+accomId);
   getElem("extrapricebreakDetails_"+accomId).style.display = "inline";
/*   getElem("closeextrapricebreak_"+accomId).style.display = "inline";
   getElem("expandextrapricebreak_"+accomId).style.display = "none";*/
   getElem("holidayDetailWrapper_"+accomId).style.backgroundColor = "#ffffe7";
   document.getElementById("chooseandcontinue_"+accomId).style.display = "inline";
   document.getElementById("expandlink_"+accomId).style.display = "none";
   document.getElementById("expandimg_"+accomId).src='/thomson/cms/thomson.co.uk/byo/search/results?reference=ps_btn_choosecontinue'
}

function displayExtraPriceHoliday(accomId,linkName) {
   var detailsViewed=false;
   if( getElem("extrapricebreakDetails_"+accomId).style.display == "inline")

   {
      detailsViewed=true;
   }
   if(detailsViewed !=true)
   {
       displayExtraPriceBreakDetails(accomId);
   }
   else
   {
      hideExtraPriceBreakDetails(accomId);

   }
}
function hideExtraPriceBreakDetails(accomId) {
   getElem("extrapricebreakDetails_"+accomId).innerHTML = "<div class='loadingMessage'>Loading price breaker details...</div>";
   getElem("extrapricebreakDetails_"+accomId).style.display = "none";
   /*getElem("closeextrapricebreak_"+accomId).style.display = "none";*/
   getElem("expandextrapricebreak_"+accomId).style.display = "inline";
   /*getElem("holidayDetailWrapper_"+accomId).style.backgroundColor = "#fff";*/
}


function appendChangeFlightQueryString(obj) {
   document.location.href="/thomson/page/byo/search/changeflight.page?sortOption="+obj;
}

function showfullItenary(obj) {
   document.getElementById(obj).style.display="";
   document.getElementById(obj+"_simple").style.display="none";
   document.getElementById(obj+"_showlink").style.display="none";
   document.getElementById(obj+"_hidelink").style.display="block";
}

function hidefullItenary(obj) {
   document.getElementById(obj+"_simple").style.display="";
   document.getElementById(obj).style.display="none";
   document.getElementById(obj+"_hidelink").style.display="none";
   document.getElementById(obj+"_showlink").style.display="block";
}
   var selectedList;

function highlightCell(airport, depdate) {
   var url1 = location.search;

   if(selectedList == undefined || selectedList== "undefined" || selectedList == null)
   {
      return;
   }
   if(selectedList != undefined || selectedList!= "undefined" || selectedList!= null)
   {
      var indexObj = selectedList;
      getElem("cell_"+indexObj).className="active_price";
   }
}

function viewAccomDetails(accomUniqueId, accomId, alternateAccom)
{
   url = "/thomson/page/byo/details/detailspopup.page?packageNumber="+accomUniqueId+"&popup=true";
   if(accomId)
   {
      url = url + "&AccommodationId=" + accomId;
   }
   if(alternateAccom)
   {
       url = url + "&alternateAccom=" + alternateAccom;
   }
   Popup(url,755,584);
}

/*function displayAltRooms(elemId,roomCount)
{
   obj = document.getElementById(elemId);

   if (currentStyle(obj, 'display')=="block")
   {
      obj.style.display = "none";
      document.getElementById("lessRoomsLink_"+roomCount).style.display = "none";
      document.getElementById("moreRoomsLink_"+roomCount).style.display = "block";
   }else{
      obj.style.display = "block";
      document.getElementById("lessRoomsLink_"+roomCount).style.display = "block";
      document.getElementById("moreRoomsLink_"+roomCount).style.display = "none";
   }
}*/

function GoToResult(accommIdValuePatition1,accommIdValuePatition2,accommIdValuePatition3,accommIdValuePatition4,count)
{
   var value=accommIdValuePatition1+""+accommIdValuePatition2+""+accommIdValuePatition3+""+accommIdValuePatition4;
   var pageNumber=parseInt((count-1)/pageSize);
   if (window.document.location.href.indexOf("showAllResults=true")>-1) {
   //getResultMap();
      url=(window.document.location.href.indexOf("#")>-1)?window.document.location.href.substring(0,window.document.location.href.indexOf("#")):window.document.location.href;
      window.document.location.replace(url+"#link_"+value);
   }
   else
   {
      url=(window.document.location.href.indexOf("?")>-1)?window.document.location.href.substring(0,window.document.location.href.indexOf("?")+1):(window.document.location.href.indexOf("#")>-1)?window.document.location.href.substring(0,window.document.location.href.indexOf("#")):window.document.location.href;
      window.document.location.replace(url+"pageNumber="+pageNumber+"#link_"+count);
   // window.getResultMap();
   }
}

function showResultMap()
{
      var el = getElem('resultmap');
      var content = el.firstChild;
      while (content && content.tagName != 'DIV') { content = content.nextSibling }
      el.style.display="block";
     content.style.display="block";
  }

  //Auto Completion of surnames
function autoCompletion(passengerCountBasedOnRooms, startAutoCompletion) {
   if(document.getElementById('autoCheck['+startAutoCompletion+']').checked) {
      for(index=startAutoCompletion; index<(startAutoCompletion+passengerCountBasedOnRooms-1); index++) {
         document.getElementById('passengerDetailsFormBeans['+index+'].lastName').value = document.getElementById('passengerDetailsFormBeans['+(index-1)+'].lastName').value;
      }
   }
}

//auto complete checkbox is unchecked if surname is changed
function checkSurnames(count)
{
 document.getElementById('autoCheck[1]').checked = false;
}

function UpdateOnDateChange()
{
   DynamicUpdate('date','change',1);
}// for the PopUp in the Search results page.

function getDetails()
{
   url = "/thomson/page/byo/search/resultsPopup.page?popup=true";
   Popup(url,700,600,'scrollbars=yes');
}

function updateFormElementFromCheckBox(checkBoxObj, formElement)
{
   if (document.getElementById(formElement))
   {
       document.getElementById(formElement).value = checkBoxObj.checked;
   }
}
function forwardToAltSearch()
{
   var roomConfig = populateRoomConfigArray();
   constructRoomConfigurationString(roomConfig, form);
   var url=alternateSearchPanelLink;

   if (url.indexOf("?")>-1)
   {
      top.location.href=url+"&"+GenerateRequestForAltSearchPage(document.searchForm);
   }
   else
   {
      top.location.href=url+"?"+GenerateRequestForAltSearchPage(document.searchForm);
   }
}

function GenerateRequestForAltSearchPage(form)
{
   var params = [];
   for (i = 0; i < form.elements.length; i++)
   {
      obj = form.elements[i];
      if(!(obj.disabled))
      {
      if (obj.type == 'radio')
      {
         if (obj.checked)
         {
            params.push(escape(obj.name) + '=' + obj.value);
         }
      }
      else if (obj.type == 'select-one' ||  obj.type == 'hidden')
      {
         params.push(escape(obj.name) + '=' + obj.value);
      }
      else if (obj.type == 'checkbox')
      {
         if (obj.checked)
         {
            params.push(escape(obj.name) + '=' + obj.value);
         }
      }
   }
   }
   return params.join('&');
}

function Popuptandc(seasonDate,packageType,i18pref)
{
 var url="/thomson/page/tandc/tandc.page?lang="+i18pref+"&seasonDate="+seasonDate+"&packageType="+packageType;
    Popup(url,755,584,'scrollbars=yes');
}
function displayFullDescription(reviewId)
{
   obj1 = 'fulldesc1_'+reviewId;
   obj2 = 'briefdesc1_'+reviewId;
   document.getElementById(obj1).style.display = "block";
   document.getElementById(obj2).style.display = "none";
}

function displayShortDescription(reviewId)
{
   obj1 = 'fulldesc1_'+reviewId;
   obj2 = 'briefdesc1_'+reviewId;
   document.getElementById(obj1).style.display = "none";
   document.getElementById(obj2).style.display = "block";
}

function displayNextReview(totalReviews,currentReview,uniqueId)
{
   var nextReview = 0;

   rev1 = 'review1_'+ uniqueId+ '_'+currentReview;
   nextReview = currentReview+1;
   rev2 = 'review1_'+uniqueId +'_'+nextReview;
   document.getElementById(rev1).style.display = "none";
   document.getElementById(rev2).style.display = "block";

}

function displayPreviousReview(totalReviews,currentReview,uniqueId)
{
   var previousReview = 0;

   rev1 = 'review1_'+uniqueId+'_'+currentReview;
   previousReview = currentReview-1;
   rev2 = 'review1_'+uniqueId+'_'+previousReview;
   document.getElementById(rev1).style.display = "none";
   document.getElementById(rev2).style.display = "block";

}

function viewOtherAccomDetails(accomUniqueId,param)
{
   if(param==1)
  {
     url = "/thomson/page/byo/details/latedealdetails.page?packageNumber="+accomUniqueId+"&popup=true";
  }
  if(param==2)
  {
     url = "/thomson/page/byo/details/extrapricebreak.page?packageNumber="+accomUniqueId+"&popup=true";
  }
  if(param==3)
  {
     url = "/thomson/page/byo/details/pricebreaker.page?packageNumber="+accomUniqueId+"&popup=true";
  }

   Popup(url,755,584,'scrollbars=yes');
}
function viewTermsAndConditions()
{
   url = "https://www.thomsonbeach.co.uk/th/beach/viewTermsAndConditions.do?brochureId=TH01&seasonId=S2007";
   Popup(url,600,400,'scrollbars=yes,resizable=yes');
}
function forwardToOtherDestinations()
{
   var roomConfig = populateRoomConfigArray();
   constructRoomConfigurationString(roomConfig, form);
   var url=otherDestinationsSearchPanelLink;
   /*document.searchForm.destinationCode.options[0].value='';
   document.searchForm.accommodationCode.options[0].value='';
   document.searchForm.resortCode.options[0].value='';*/
  document.getElementById("departure").value = '';
  document.getElementById("countryCode").value = '';
  document.getElementById("destinationCode").value = '';
  document.getElementById("resortCode").value = '';
   if (url.indexOf("?")>-1)
   {
     top.location.href=url+"&"+GenerateRequest(document.searchForm);
   }
   else
   {
      top.location.href=url+"?"+GenerateRequest(document.searchForm);
   }
}

function forwardToOtherDestinationsAO()
{
   var roomConfig = populateRoomConfigArray();
   constructRoomConfigurationString(roomConfig);
   var url=otherDestinationsSearchPanelLink_ao;
   if (url.indexOf("?")>-1)
   {
     top.location.href=url+"&"+GenerateRequest(document.searchForm);
   }
   else
   {
      top.location.href=url+"?"+GenerateRequest(document.searchForm);
   }
}
function convertToDecimal(X)
{
  var S,T;
  return(S=new String(Math.round(X*100))). substr(0, T=(S.length-2)) + '.' + S.substr(T, 2);
}

function brochurePopup(prodCode,accomId)
{
    var style2 = document.getElementById(prodCode).style;
  style2.display="block";

}
function displayPopup(event, obj, index,frompage)
{

  if (typeof document.body.style.maxHeight != "undefined") {
   // IE 7, mozilla, safari, opera 9
 }
 else {
   if(typeof(frompage)!="undefined" && frompage=="panel")
  {
    if(displayPropertiesFlag==true && index > 5)
    {
        ShowDropDownList(0, 'panel');
      }
      if(displayPropertiesFlag==false && index < 3)
    {
        ShowDropDownList(0, 'panel');

      }
}

 }

  var pos = findPos(obj);
  document.getElementById('popupHeading').innerHTML = attArrayPopupHead[index];
  document.getElementById('popupDesc').innerHTML = attArrayPopupDesc[index];

  document.getElementById('attPopup').style.position="absolute";

  document.getElementById('attPopup').style.left=10;
  if(typeof(frompage)!="undefined" && frompage=="panel")
  {
	  document.getElementById('attPopup').style.left=0+"px";
  }
  if(typeof(frompage)!="undefined" && frompage=="horizPanel"){
	  document.getElementById('attPopup').style.top=(pos[1]-20)+"px";
  }else{
	  document.getElementById('attPopup').style.top=(pos[1]+60)+"px";
  }
 document.getElementById('attPopup').style.display="block";
 // document.getElementById('attPopup').style.visibility="visible";

  //ShowDropDownList(1);
}

function displayAttributes()
{
  displayPropertiesFlag =true;
  for(i=3;i<attArray.length;i++)
  {
    document.getElementById("attcontainer_"+attArray[i]).style.display="block";

  }
  document.getElementById("moreHolLink").style.display="none";
  document.getElementById("moreHolidayText").style.display="none"
  //document.getElementById("lessHolLink").style.display="block";
}


function findPos(obj) {
 if (obj)
 {
   var curleft = curtop = 0;
   if (obj.offsetParent) {
    curleft = obj.offsetLeft
    curtop = obj.offsetTop
    while (obj = obj.offsetParent) {
     curleft += obj.offsetLeft
     curtop += obj.offsetTop
    }
   }
   return [curleft,curtop];
 }else{
   return [0,0];
 }
}

function openMoreAttributesLink(flag)
{
  if (flag)
  {
       displayAttributes();
  }
     /*else
  {
       hideAttributes();
  }*/
}

function ShowDropDownList(show,obj) {

    if(obj == 'panel') {

       select_array=new Array ("ratingselect","accommodationType","selectrooms");}
   if (document.all && select_array.length>0) {
      for (var i=0; i<select_array.length; i++) {
        document.getElementById(select_array[i]).style.visibility=(show==0)?"hidden":"visible";

      }
   }
}

function generateDeepLink(form)
{
 if (validateSearchCriteriaForm(form))
 {
      form.target="urlFrame";
      form.submit();
 }
}

function loadLonghaulDetails(type,accomId)
{
  loadLonghaulDetailsContent(type,accomId);
  for(i=0;i<1000000;i++){}
}
function loadLonghaulDetailsContent(type,accomId)
{
   listElements = getElem("detailsToc_"+accomId).getElementsByTagName("li");
   for(i=0;i<listElements.length;i++) {
      listElements[i].className = "";
      }
  var innerHtml = getElem(type+"_"+accomId).innerHTML;
  if (ie6)
  {
    getElem("description_container_"+accomId).innerHTML = innerHtml;
  }else{
    getElem("description_container_"+accomId).innerHTML = "<img src='/thomson/cms?direct=byo/images/backgrounds/Extralegroomv3a.gif'/>";
  }
  getElem("description_container_"+accomId).className="textgallery";
  getElem(type+"Li_"+accomId).className = "active";
  getElem("printLi_"+accomId).className = "icon print";
}

function loadlh(accomId)
{
  eval("detailsFrame_"+accomId).location.replace("/thomson/page/byo/details/details.page?packageNumber="+accomId+"&linkName=thomsonFlyLonghaul");
}

//26164 change
function updateFormElementFromCheckBoxMarketing(checkBoxObj, formElement)
{
  if (document.getElementById(formElement))
     {
     if (checkBoxObj.checked)
         {
        document.getElementById(formElement).value = false;
       }
     else
         {
      document.getElementById(formElement).value = true;
     }
     }
 }

 function loadAccomDetails(packageID, unitCode, brochureSearch)
 {
   if (getElem("holidayDetailWrapper_"+packageID))
   {
     getElem("holidayDetailWrapper_"+packageID).style.backgroundColor = "#ffffe7";
   }
   navigateToAccomDetails(packageID, unitCode,brochureSearch);
 }

 // This method navigateToAccomDetails() is overridden in accomdetails.js it will be deleted from there after first checkin.
 function navigateToAccomDetails(packageID, unitCode, brochureSearch)
 {
  queryString = document.getElementById("userCriteriaQueryString").value;
  if(brochureSearch == 'true')
  {
      "<c:set var='brochurePackageNumber' scope='session' value='"+packageID+"'/>";
      document.location.href="/thomson/page/byo/accomdetails/brochureaccomdetails.page?brochurePackageNumber="+packageID+"&"+queryString;
  }
  else
  {
      document.location.href="/thomson/page/byo/accomdetails/accomdetails.page?packageNumber="+packageID+"&"+queryString;
  }
 }

 /**********written for crossell****************/
 function getAlternateWeek(weekflag)
{
   queryString = document.getElementById("userCriteriaQueryString").value;
   var calendarDay = document.getElementById("calendar_day");
   var calendarMonthYear = document.getElementById("calendar_month_year").value.split('/');
   var monthYear = document.getElementById("calendar_month_year").value;
   var numberOfNights = document.getElementById("duration").value;
   var dateWrapper = Dates;

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

     if(weekflag)
     {
    	 /*calculate departure date for next week*/
       var newDepartureDate = new Date(departureDate.getTime()+(numberOfNights * 86400000));
         var day = newDepartureDate.getDate();
         if(day < 10)
         {
        	 day= '0' + day;
         }
         var month = newDepartureDate.getMonth()+1;

       var monthyear = month + "/" + newDepartureDate.getFullYear();
       var url = ("/thomson/page/byo/waiting/searchwaiting.page?wel=t&day="+day+"&monthYear="+monthyear+"&crossell=true&"+queryString+"");
       document.location.replace(url);

     }
     else
     {
    	 /*calculate departure date for previous week*/
       var newDepartureDate = new Date(departureDate.getTime()-(numberOfNights * 86400000));
       var day = newDepartureDate.getDate();
       var monthyear = (newDepartureDate.getMonth()+1) + "/" + newDepartureDate.getFullYear();

     if(validateDepartureDate(newDepartureDate))
     {
    	 /*append the new date to url only if the previous date calculated is after todays date*/
        var url = ("/thomson/page/byo/waiting/searchwaiting.page?wel=t&day="+day+"&monthYear="+monthyear+"&crossell=true&"+queryString+"");
        document.location.replace(url);
     }
     }
  }
}

function validateNewDate(calendarDay,calendarMonthYear)
{
  dateVar = calendarMonthYear[0] + "/" + calendarDay.value + "/" + calendarMonthYear[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 (checkinDay.after(maxDate))
    {
      alert("please try for next week");
      return false;
  }
    if (checkinDay.before(minDate))
    {
      if (checkinDay.before(currentDateObj))
      {
    alert("please try for next week");
      }
      else
      {
    alert("please try for next week");
      } return false;
  }
    else
    {
      return true;
    }
}

function validateDepartureDate(newdate)
{
  var todaydate = new Date();
  if(newdate.before(todaydate))
  {
    alert("please try for next week");
    return false;
  }
  return true;
}

function fixImagePNG(elemID)
{
   if(!elemID){return false};
   var img = document.getElementById(elemID);
   if(!img){return false};
   if( ! img.complete )
   {
      img.onload = fix_png;
   }
   else
   {
      fix_png.apply( img );
   }
}

function fix_png( )
{
    var img = this;
    var span = document.createElement( "span" );
    if( img.id) span.id = img.id;
    if( img.className ) span.className = img.className;
    if( img.onclick ) span.onclick = img.onclick;
    if( img.onmouseover ) span.onmouseover = img.onmouseover;
    if( img.onmouseout ) span.onmouseout = img.onmouseout;
    if( img.onmouseup  ) span.onmouseup = img.onmouseup;
    if( img.onmousedown ) span.onmousedown = img.onmousedown;
    span.title = img.title ? img.title : img.alt;
    span.style.width = img.width + "px";
    span.style.height = img.height + "px";
    span.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src=\'" + img.src + "\', sizingMethod='scale'";
    img.id = null;
    img.parentNode.insertBefore( span , img );
    img.parentNode.removeChild( img );
}

//Used by Availability Indicator and brochure search panel popups
function stickyClose(id)
{
  document.getElementById(id).style.display = "none";
}

//Used by Availability Indicator popup in search results
function searchResultsSticky(id)
{
	var id = document.getElementById(id);
	id.style.display="block";
	id.style.left='140px';
}

//Used by Availability Indicator popup in TO page
zIndex=1;
function showSticky(id, stickyAlign)
{
	zIndex++;
	var id = document.getElementById(id);
	id.style.display="block";
	id.style.left='660px';
	id.style.overflow="auto";
	id.style.zIndex=zIndex;
	if(!ie6)
	{
		document.getElementById(stickyAlign).style.height="24px";
	}
}


/***** Function to enqueque window.onload calls *****/

  function addLoadEvent(func) {
      var oldonload = window.onload;
      if (typeof window.onload != 'function') {
        window.onload = func;
        //alert(func);
      } else {
        window.onload = function() {
          if (oldonload) {
            oldonload();
          }
          func();
        }
      }
    }

function toggleBrochureContainer()
{
  if(document.getElementById('brochurePanelH2').className != '')
  {
    document.getElementById('brochurePanelH2').className = "";
    document.getElementById('brochureCodeContainer').style.display = "block";
  }
  else
  {
    document.getElementById('brochurePanelH2').className = "collapsed";
    document.getElementById('brochureCodeContainer').style.display = "none";
    document.getElementById('brochureCodeOverlay').style.display = "none";
  }
}

/****** Function to validate the Brochure code ***/

function validateBrochureCode()
{
  var BrochureCodeFormat = /^(([A-Za-z]{3})|([A-Za-z]{6}))$/;
  var userInput = document.getElementById('BrochureSearch').value;
  var isCorrectBrochureCode =BrochureCodeFormat.test(userInput);

  "<c:set var='brochureCode' scope='session' value='"+userInput+"'/>";
  if(!isCorrectBrochureCode)
  {
    document.getElementById('brochureCodeError').style.display="block";
    document.getElementById('BrochureSearch').value="";
  }
  else
  {
    document.getElementById('brochureCodeError').style.display="none";
  }
  return isCorrectBrochureCode;
}

function validateLightbox(form)
{
   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 checkinDay=new Date(dateVar);

   var currentDateObj=new Date();
   currentDateObj.setDate(currentDateObj.getDate()+1);

   if (checkinDay.before(currentDateObj))
   {
      alert("Please select a date on or after "+currentDateObj.getDate()+"/"+(currentDateObj.getMonth()+1)+"/"+currentDateObj.getFullYear());
      // document.getElementById('day').selectedIndex = currentDateObj.getDate() - 1;
      resetCheckInDate(currentDateObj);
      currentDateObj.setDate(currentDateObj.getDate()-1);
   }
   else
   {
    var roomConfig = populateRoomConfigArray(form);
    var totalPartySize = 0;
    var totalAdultPartySize = 0;
    var totalInfantSize = 0;
    var childFlag=0;
    for(var i=0;i<roomConfig.length;i++) {
       var room = roomConfig[i];
       totalPartySize +=  parseInt(room.numAdults) + parseInt(room.numChildren);
       totalAdultPartySize += parseInt(room.numAdults);
       for(var j=0;j<room.childAges.length;j++) {
          if (room.childAges[j]=="-?-")
          {
             childFlag++;
          }
          if (room.childAges[j]>=16) {
             totalAdultPartySize++;
          }
          if (room.childAges[j]=="<2") {
             totalInfantSize++;
          }
       }
    }
    if (totalPartySize-totalInfantSize > maxPartySize) {
       alert(invalidPartySize);
    }
    else if (totalInfantSize > totalAdultPartySize) {
       alert(tooManyInfants)
    }
    else
    {
      if(childFlag){
        alert("Please enter child age");
        getElem('child_ages').focus();
      }
      else
      {
        checkBox();
        constructRoomConfigurationString(roomConfig, form);
        return true;
      }
    }
  }
}

/***** function to display Brochure code container once selected *****/

function displayBrochure()
{
  if(document.getElementById('brochurePanelH2')){
	document.getElementById('brochurePanelH2').className = "collapsed";
	var brochureCode = document.getElementById('brochureCodeContent').value;
	var brochureCodeContainer = document.getElementById('brochureCodeContainer');
	brochureCodeContainer.style.display="none";
    if(brochureCode != '')
    {
    brochureCodeContainer.style.display="block";
    document.getElementById('BrochureSearch').value = brochureCode;
    document.getElementById('brochurePanelH2').className = "";
    }
  }
}

/******* function to hide Error message when Normal search is performed ***********/

function hideErrorMessage()
{
  document.getElementById('brochureCodeError').style.display="none";
}

function displaySticky(id)
{
	document.getElementById(id).style.display = "block";
}

function toggleDefaultText(){
	jQuery(".defaultText").focus(function(e){
	if (jQuery(this).val() == jQuery(this)[0].title){
		jQuery(this).removeClass("defaultText");
		jQuery(this).val("");
		}
	 });

	jQuery(".defaultText").blur(function(){
	if(jQuery(this).val() == ""){
	if(jQuery("#brochureCodeContent").val() == ""){
		jQuery(this).addClass("defaultText");
		jQuery(this).val($(this)[0].title);
	}else{
		jQuery(this).removeClass("defaultText");
		jQuery(this).val(jQuery("#brochureCodeContent").val());
	}
	}
    });

	jQuery(".defaultText").blur();
 }

   // Added for Search Results Re-design.
   function stickyShow(Destid, sourceId, elem)
	{
	  var offset = $(elem).offset();
	  var Destid = document.getElementById(Destid);
	  var destParentOffset = $($(Destid).parent()).offset();

	  Destid.innerHTML = document.getElementById(sourceId).innerHTML;

	  //Condition added to handle location of when brand is clicked.
	  if (offset.top - destParentOffset.top < 0)
	  {
	    Destid.style.top = '-23px';
	  }
	  else
	  {
	    Destid.style.top = (offset.top - destParentOffset.top + (($(elem).parent()).height())/2) + 'px';
	  }
	  Destid.style.left = (offset.left - destParentOffset.left + $(elem).width() - $(Destid).width() - 9) + 'px';
	  Destid.style.zIndex = "90";
	  Destid.style.position = "absolute";
	  Destid.style.display = "block";
	}
