function pen_enable_book()
{
	if (document.getElementById("bookableNotice1"))
		document.getElementById("bookableNotice1").innerHTML = '<a class="book" href="javascript:completeItineraryWrapper()">Book</a>';
	if (document.getElementById("bookableNotice2"))
		document.getElementById("bookableNotice2").innerHTML = '<a class="book" href="javascript:completeItineraryWrapper()">Book</a>';
}

function pen_disable_book()
{
	if (document.getElementById("bookableNotice1"))
		document.getElementById("bookableNotice1").innerHTML = "&nbsp;";
	if (document.getElementById("bookableNotice2"))
		document.getElementById("bookableNotice2").innerHTML = "<p>&nbsp;</p>";
}

function completeItineraryWrapper()
{
	updateWaitingDivNotice("bookButton");
	package.completeItinerary();
}

function addModule(inComponentId, inRequirementFieldId, inRequirementValue)
{
	updateWaitingDivNotice("checkingAvailability");
	package.updateComponentSingleReq(inComponentId, inRequirementFieldId, inRequirementValue);
}

function backPackage(inComponentId, inRequirementFieldId, inRequirementValue)
{
	updateWaitingDivNotice("returnBooking");
	package.showPackage()
}

function dateSelection(inComponentId, inRequirementFieldId, inRequirementValue)
{
	updateWaitingDivNotice("checkingAvailability");
	package.updateComponentSingleReq(inComponentId, inRequirementFieldId, inRequirementValue);
}

function updateComponentSingleReqWrapper(inComponentId, inRequirementFieldId, inRequirementValue)
{
	updateWaitingDivNotice("updateBooking");
	package.updateComponentSingleReq(inComponentId, inRequirementFieldId, inRequirementValue);
}

function updateComponentAndBookWrapper(inComponentId, inRequirementFieldId, inRequirementValue)
{
	updateWaitingDivNotice("updateBooking");
	package.updateComponentAndBook(inComponentId, inRequirementFieldId, inRequirementValue);
}

function setDisplay(inElement, inValue)
{
    var element = (typeof inElement == 'object' ? inElement : document.getElementById(inElement));

    if (element != null)
	element.style.display = inValue;
}

function setDisabled(inElement, inValue)
{
    var elem = (typeof inElement == 'object' ? inElement : document.getElementById(inElement));

    elem.disabled = inValue;
}

function ttAddEvent(inElement, inEventName, inFuncName)
{
    if (inElement == null || inEventName == null || inFuncName == null)
	return;

    if (inElement.ttAddEventListener)						
	inElement.ttAddEventListener(inEventName, inFuncName, true);
    else if (inElement.attachEvent)						
	inElement.attachEvent("on" + inEventName, inFuncName);
}

function ttRemoveEvent(inElement, inEventName, inFuncName)
{
    if (inElement == null || inEventName == null || inFuncName == null)
	return;

    if (inElement.ttRemoveEventListener)				
	inElement.ttRemoveEventListener(inEventName, inFuncName, true);
    else if (inElement.detachEvent)					
	inElement.detachEvent("on" + inEventName, inFuncName);
}

function killEvent(inEvent)
{
    var event = (!inEvent) ? window.event : inEvent;

    if (event.stopPropagation)
    {
	event.preventDefault();
	event.stopPropagation();
    }
    else
    {
	event.returnValue  = false;
	event.cancelBubble = true;
    }
}

function toggleSelectElemDisplay(inBrowseElem, inLeft, inTop)
{
    var selectElemArray = document.getElementsByTagName('select');

    if (selectElemArray.length == 0)
	return;

    var browse = (typeof inBrowseElem == 'object' ? inBrowseElem : document.getElementById(inBrowseElem));


    if (!isDisplayed(browse))
    {
	for (var i = 0; i < selectElemArray.length; i++)
	    selectElemArray[i].style.visibility = 'visible';

	return;
    }

    var bl = inLeft;			
    var br = bl + browse.offsetWidth;	
    var bt = inTop;		
    var bb = bt + browse.offsetHeight;		

    for (var i = 0; i < selectElemArray.length; i++)
    {
	var e = selectElemArray[i];

	if (e.style.visibility == 'hidden')
	    continue;

	var p = findAbsolutePos(e);

	var el = p.left;			
	var er = el + e.offsetWidth;
	var et = p.top;		
	var eb = et + e.offsetHeight;

	if (el <= br && er >= bl && et <= bb && eb >= bt)
	    e.style.visibility = 'hidden';
    }
}

function showWaitNotice()
{
    if (document.getElementById('waitNotice') == null)
		return;

    if (mShowStartPkgWait == true && document.getElementById('startWaitNotice') != null)
    {
		setDisplay('startWaitNotice', '');
    }
    else
    {
		createbgDiv();//defined in lightbox.js
		setDisplay('bgDiv', 'block');
		setDisplay('ieFix', 'block');
		setDisplay('waitNotice', 'block');
		positionWaitNotice();
		opacity();
		window.onscroll = positionWaitNotice;
    }
    
    ttAddEvent(document, "click",	   cancelWaitNotice);
    ttAddEvent(document, "keypress", cancelWaitNotice); 	
    ttAddEvent(document, "keydown",  cancelWaitNotice); 

    var inputElements = document.getElementsByTagName('input');

    for (var i = 0; i < inputElements.length; i++)
    {
	if (inputElements[i].type == 'button' || inputElements[i].type == 'submit')
	    setDisabled(inputElements[i], true);
    }
}

function positionWaitNotice()
{	
	
	var waitWindow = document.getElementById('waitNotice');
	var topDiv = document.getElementsByTagName('div')[0]; //picks up the first div of the page
    topDiv.parentNode.insertBefore(waitWindow, topDiv);
	waitWindowTop = (waitWindow.offsetHeight)/2*-1;
	if (navigator.appVersion.indexOf("MSIE")!=-1){
		/*create hack to look like fixed position for ie6*/
		waitWindow.style.position = 'absolute';
		var scrollTop=document.documentElement.scrollTop;
		waitWindow.style.top = ((scrollTop + ((document.documentElement.clientHeight/2) + waitWindowTop))) + 'px';
	} else {
		waitWindow.style.position = 'fixed';
		waitWindow.style.marginTop = waitWindowTop + 'px';
	}
}

function scrollToElement(inElementId)
{
    var elem = document.getElementById(inElementId);

    var leftPos = 0;
    var topPos  = 0;

    //Find the position of the element 
    while (elem != null)
    {
	leftPos += elem.offsetLeft;
	topPos  += elem.offsetTop;
	elem    = elem.offsetParent;
    }

    window.scrollTo(leftPos, topPos);
}

function cancelWaitNotice(inEvent)
{
    var event = (!inEvent) ? window.event : inEvent;

    if (event.keyCode == 27)
    {
	hideWaitNotice();
	return(true);
    }

    killEvent(event);
    return(false);
}

function hideWaitNotice()
{
    setDisplay('bgDiv', 'none');
	setDisplay('ieFix', 'none');
	var waitWindow;
    
    if (mShowStartPkgWait == true)
    {
		waitWindow = document.getElementById('startWaitNotice');
		mShowStartPkgWait = false;
    }
    else
    {
		waitWindow = document.getElementById('waitNotice');
    }
    
    if (waitWindow == null)
		return;

    setDisplay(waitWindow, 'none');
	
    ttRemoveEvent(document, "click",    cancelWaitNotice);
    ttRemoveEvent(document, "keypress", cancelWaitNotice); 
    ttRemoveEvent(document, "keydown",  cancelWaitNotice); 
    
    var inputElements = document.getElementsByTagName('input');

    for (var i = 0; i < inputElements.length; i++)
    {
	if (inputElements[i].type == 'button' || inputElements[i].type == 'submit')
	    setDisabled(inputElements[i], false);
    }
    
    toggleSelectElemDisplay(waitWindow, 0, 0);
}

function getBrowserGeometry()
{
    var geometry = new Array(4);

    geometry['top']    = window.scrollY	    ? window.scrollY	 : document.body.scrollTop;
    geometry['left']   = window.scrollX	    ? window.scrollY	 : document.body.scrollLeft;
    geometry['width']  = window.innerWidth  ? window.innerWidth	 : document.body.clientWidth;
    geometry['height'] = window.innerHeight ? window.innerHeight : document.body.clientHeight;

    return(geometry);
}

function findAbsolutePos(inElement)
{
    var elem = (typeof inElement == 'object' ? inElement : document.getElementById(inElement));

    if (elem == null)
	return(false);

    var left = 0;
    var top  = 0;

    for (; elem.offsetParent; elem = elem.offsetParent)
    {
	left += elem.offsetLeft;
	top  += elem.offsetTop;
    }

    return(new coordinate(left, top));
}

function coordinate(inLeft, inTop)
{
    this.left = inLeft;
    this.top  = inTop;
}

function isDisplayed(inElement)
{
    var element = (typeof inElement == 'object' ? inElement : document.getElementById(inElement));

    if (element != null)
    {
	if (element.style.display != 'none')
	    return(true);
    }

    return(false);
}

/*
 * This function looks for any uncompleted modules (ie those that have been 'added' but not removed/selected) and executes the code
 * to get rid of them.
 */
function removeAnyUncompletedModules()
{
	var element = document.getElementById('removeActivityBt');
		
	if (!element || element == null)
		return;	
	
	var fnString = element.href;
		
	if (fnString == null || fnString.length < 10)
		return;
		
	// Chop of the 'javascript:' and remove any spaces in this string for IE6
	var fnToEval = fnString.substr(11, fnString.length).replace(/%20/g, "");	
		
	eval(fnToEval);
}

/*
 * This function waits for the offending half completed module to be removed from the package before going on to execute the 
 * funtion that the user has requested. This recursive code is necessary for IE, since it seems to not wait for the first function 
 * to complete before starting execution of the second.
 */
function runPackageFn(inFunctionCall)
{
	if (document.getElementById('removeActivityBt') == null)
	{
		eval(inFunctionCall);
	}
	else
	{		
		setTimeout('runPackageFn("' + inFunctionCall + '")', 1);
	}	
}

function ensureConsistentStateAndSubmit(inFunctionCall, inWaitingDivCode)
{
	updateWaitingDivNotice(inWaitingDivCode);
	removeAnyUncompletedModules();
	runPackageFn(inFunctionCall);
}

/*
 * This function will be called when a flight is selected to disable all radio buttons that allow selection of the other carrier, in
 * the other direction.
 * This function is written with the assumption that a radio button can never be unselected.
 */ 
function toggleShownFlightOptions(inActiveCarrier, inDirection)
{
    var rowElements = document.getElementsByTagName('table');

    for (var i = 0; i < rowElements.length; i++)
    {
		/* The row element id is in the form <Carrier>_<Direction>_<number> */ 
		var elemIdArr = rowElements[i].id.split('_');
	
		if (elemIdArr.length < 3)
		    continue;
		
		var carrier   = elemIdArr[0];
	        var direction = elemIdArr[1];
		
		// If we are in the same direction as the active radio button dont do anything
		if (direction == inDirection)
		    continue;
		
		// If we are in the opposite direction, with the same carrier, ensure we are visible, otherwise ensure we are hidden.
		if (carrier == inActiveCarrier)
		{
		    setDisplay(rowElements[i], '');
		}
		else
		{
		    setDisplay(rowElements[i], 'none');
		    setDisplay(document.getElementById('showallButton'), '');
		}
    }

    // Ensure nothing that is hidden is selected, if it is, unselect it

    var radioElements = document.getElementsByTagName('input');

    for (var j = 0; j < radioElements.length; j++)
    {
		if (radioElements[j].type != 'radio' || !radioElements[j].checked)
		    continue;
		
		/* The row element id is in the form radio_<Carrier>_<Direction>_<number> */ 
		var elemIdArr = radioElements[j].id.split('_');
	
		if (elemIdArr.length < 4)
		    continue;
		
		var carrier   = elemIdArr[1];
	        var direction = elemIdArr[2];
		
		// If we are in the same direction as the active radio button dont do anything
		if (direction == inDirection)
		    continue;
		
		// If we are in the opposite direction, with the same carrier, ensure we are visible, otherwise ensure we are hidden.
		if (carrier != inActiveCarrier)
		    radioElements[j].checked = false;
    }
}

function showAllFlightOptions()
{
    var rowElements = document.getElementsByTagName('table');

    for (var i = 0; i < rowElements.length; i++)
    {
		/* The row element id is in the form <Carrier>_<Direction>_<number> */ 
		var elemIdArr = rowElements[i].id.split('_');
	
		if (elemIdArr.length < 3)
		    continue;
		
		setDisplay(rowElements[i], '');
    }

    // Ensure nothing that is hidden is selected, if it is, unselect it

    var radioElements = document.getElementsByTagName('input');

    for (var j = 0; j < radioElements.length; j++)
    {
		if (radioElements[j].type != 'radio' || !radioElements[j].checked)
		    continue;
		
		/* The row element id is in the form radio_<Carrier>_<Direction>_<number> */ 
		var elemIdArr = radioElements[j].id.split('_');
	
		if (elemIdArr.length < 4)
		    continue;
		
		radioElements[j].checked = false;
    }
    
}

function editComp(){
	scrollToElement('componentWorkingSection');
	if (document.getElementById("hotelError")){
		document.getElementById("hotelError").style.display="none";
	
	}	
}

/*
   User defined functions.
*/

/*
 * Function to submit a date change. Expects the inDate to be of format dd/mm/yyyy. Will submit only the date that needs to change. 
 */

function submitDateChange(inDate, inDateFld, inIncrement, inComponentId)
{
   var errorDiv = document.getElementById("cdpErrorMessage");
   if (inIncrement < 0 &&  errorDiv != null)
   {
   	   errorDiv.style.display = "";
	   document.getElementById("previousButton").style.display = "none";
       return;	
   }
   
   updateWaitingDivNotice("checkingAvailability");
   
   /* date is dd/mm/yyyy */
   var pen_dateArr = inDate.split('/');
   
   var pen_date = new Date();
   
   /* setUTCFullYear expects months in the range of 0 to 11 */
	pen_date.setUTCFullYear(pen_dateArr[2], (pen_dateArr[1] - 1), pen_dateArr[0]);

   /* increment date */

   var newDate = parseInt(pen_date.getUTCDate()) + parseInt(inIncrement);

   pen_date.setUTCDate(newDate);

   /* need to submit date in format dd/mm/yyyy */
   var newMonth = (pen_date.getUTCMonth() + 1);

   newMonth = newMonth > 9 ? newMonth : '0' + newMonth;

   var submitDate = pen_date.getUTCDate() + "/" + newMonth + "/" + pen_date.getUTCFullYear();

   /* inComponentId, inReqFldId, inReqValue */ 
   package.updateComponentSingleReq(inComponentId, inDateFld, submitDate);
}

function submitFlightSelection(inSubmitFieldId, inDepFlightName, inRetFlightName, inStartDate, inEndDate)
{
    var depFlightSelected = false;
    var retFlightSelected = false;
	
    updateWaitingDivNotice("updateBooking");
	
    var inputElements = document.getElementsByTagName('input');

    for (var i = 0; i < inputElements.length; i++)
    {
		if (inputElements[i].type == 'radio' && inputElements[i].checked)
		{
		    if (inputElements[i].name == inDepFlightName)
			depFlightSelected = true;
		    else if (inputElements[i].name == inRetFlightName)
			retFlightSelected = true;
		}
    }
    
    if (!depFlightSelected || !retFlightSelected)
    {
		document.getElementById('selectFltsErr').style.display = '';
		scrollToElement('selectFltsErr');
		return;
    }

    package.updateComponent(inSubmitFieldId, 'componentWorkingSectionForm');  
}

/*
 * Function ensures the conditions are acknowledged before the user is allowed to submit.
 */ 
function validateBookingForm(inErrorDiv)
{
	var isMissingField = false;
    var isMissingCCField = false;
    
	document.getElementById('javascriptError').style.display = "none";
	document.getElementById('javascriptError').innerHTML = "";
    document.getElementById('creditCardJavascriptError').style.display = "none";
    document.getElementById('creditCardJavascriptError').innerHTML = "";
	
	var errorDiv = document.getElementById(inErrorDiv);
	if (errorDiv)
	    document.getElementById(inErrorDiv).style.display = "none";	
	
	if(!fieldSpecifiedCorrectly('state', 'State')) 
		isMissingField = true;
	
    if(!fieldSpecifiedCorrectly('town', ' Town')) 
		isMissingField = true;
		
	if(!fieldSpecifiedCorrectly('postcode', 'Postcode')) 
		isMissingField = true;
	
    if(!fieldSpecifiedCorrectly('agentReference', 'Country/Region')) 
		isMissingField = true;
		
    if(!fieldSpecifiedCorrectly('contact', 'Contact Phone'))
		isMissingField = true;

    if(!fieldSpecifiedCorrectly('email', 'Email')) 
		isMissingField = true;		
    
    if(!fieldSpecifiedCorrectly('firstAddressLine', 'First Street Address Line')) 
		isMissingField = true;

    if(!ccFieldSpecifiedCorrectly('cardName', 'Name')) 
        isMissingCCField = true;  
        
    if(!ccFieldSpecifiedCorrectly('cardNumber', 'Card Number')) 
        isMissingCCField = true;

    if(!ccFieldSpecifiedCorrectly('verifNo', 'Verification Number')) 
        isMissingCCField = true;
        
    if(!ccFieldSpecifiedCorrectly('cardExp', 'Expiry Date')) 
        isMissingCCField = true;  
	
	if (errorDiv) {
		if (document.getElementById('accept1') && !document.getElementById('accept1').checked) {
			document.getElementById(inErrorDiv).style.display = 'none';
			document.getElementById(inErrorDiv).style.display = '';
			return;
		}
		
		if (document.getElementById('accept2') && !document.getElementById('accept2').checked) {
			document.getElementById(inErrorDiv).style.display = 'none';
			document.getElementById(inErrorDiv).style.display = '';
			return;
		}
		
		if (document.getElementById('accept3') && !document.getElementById('accept3').checked) {
			document.getElementById(inErrorDiv).style.display = 'none';
			document.getElementById(inErrorDiv).style.display = '';
			return;
		}
	}	

    if (isMissingField)
    {
        scrollToElement("javascriptError");
        return;
    }
    else if (isMissingCCField)
    {
        scrollToElement("creditCardJavascriptError");
        return;
    }
	
	concatFields();
	
	updateWaitingDivNotice("paymentButton")
	
    package.completeBooking('passengerDetailsForm');
}

function fieldSpecifiedCorrectly(inId, inDescription){
	var field = document.getElementById(inId);

	if (field && field.value.length == 0)
	{
		document.getElementById('javascriptError').innerHTML += "Must enter the " + inDescription + ".<br/>";
		document.getElementById('javascriptError').style.display = "block";
		return(false);
	}

	if (field.value.indexOf(',') >= 0)
	{
		document.getElementById('javascriptError').innerHTML += "Cannot enter a comma (,) in the field " + inDescription + ". <br/>";
		document.getElementById('javascriptError').style.display = "block";
		return(false);
	}
	
	return(true);
}

function ccFieldSpecifiedCorrectly(inId, inDescription){
    var field = document.getElementById(inId);

    if (field && field.value.length == 0)
    {
        document.getElementById('creditCardJavascriptError').innerHTML += "Must enter the " + inDescription + ".<br/>";
        document.getElementById('creditCardJavascriptError').style.display = "block";
        return(false);
    }
    
    return(true);
}

function concatFields()
{	
	var fields = '';
;
	fields += document.getElementById('town').value + ',';
	fields += document.getElementById('state').value + ',';
	fields += document.getElementById('postcode').value;

	
	document.getElementById("hiddenAddressLine").value = fields;
} 

/*
 * Function ensures the conditions are acknowledged before the user is allowed to submit. Supports links
 */ 
function validateBooking(inErrorDiv)
{
    if (document.getElementById('accept1') && !document.getElementById('accept1').checked)
    {
		document.getElementById(inErrorDiv).style.display = 'none';
		document.getElementById(inErrorDiv).style.display = '';
    }
    
    if (document.getElementById('accept2') && !document.getElementById('accept2').checked)
    {
		document.getElementById(inErrorDiv).style.display = 'none';
		document.getElementById(inErrorDiv).style.display = '';
    }
    
    if (document.getElementById('accept3') && !document.getElementById('accept3').checked)
    {
	    document.getElementById(inErrorDiv).style.display = 'none';
	    document.getElementById(inErrorDiv).style.display = '';
    }
    
    package.completeBooking('passengerDetailsForm');
}

function closeWorkingDiv()
{
	
    document.getElementById('componentWorkingSection').innerHTML = "&nbsp;";
}

function verifyPromoCdp(arg_form, inStartDate, inEndDate, inDepFltSched, inRetFltSched)
{

    if (!verifyCdpDates(inStartDate, inEndDate, inDepFltSched, inRetFltSched))
        return(false);
    if (!checkAdultInfant())
    	return(false);
    return(verifyCdp(arg_form));
}

function verifyCdpDates(inStartDate, inEndDate, inDepFltSched, inRetFltSched)
{
    var depDate = new Date(convertDate(document.getElementById("startDate").value)); 
    var retDateVal = document.getElementById("endDate").value
   
    if (!retDateVal || retDateVal.length == 0)
    {
        alert("Enter a returning date");
        return(false);
    }    
      
    var retDate = new Date(convertDate(retDateVal));
 
    if (!validateDuration(depDate, retDate))
    {
        alert("duration does not validate");
        return(false);
    }
        
    // Variables newDow, startDate, and stopDate in calendar.js
    negDow = inDepFltSched;    
    startDate = new Date(inStartDate);
    stopDate = new Date(inEndDate); 
    
    
    if (disallowDate(depDate))
    {
        alert("Cannot depart on specified date. Please select another date.");
        return(false);
    }    
    
    negDow = inRetFltSched;

        
    if (disallowDate(retDate))
    {
        alert("Cannot return on specified date. Please select another date.");
        return(false);
    }   
    
    return(true);
}

function validateDuration(inDepDate, inRetDate)
{
    var duration = calculateDuration(inDepDate, inRetDate);
    
    if (duration < 0)
    {
        alert("Return date must be on or after the departing date");
        return(false);
    }
    
    document.getElementById("duration").value = duration;
    
    return(true);
}

function depCityChange()
{
    document.getElementById("startDate").value = "";
    document.getElementById("endDate").value = "";
    var depCity = document.getElementById("depCityCdp").value;
    
    var startDateFltSch = document.getElementById("startDateFltSch");
    var endDateFltSch = document.getElementById("endDateFltSch");

    startDateFltSch.innerHTML = dowValues(fltDepSched[depCity]);
    if (startDateFltSch.innerHTML.length == 0)
        startDateFltSch.style.display = "none";   
    else
        startDateFltSch.style.display = "";  
    
    endDateFltSch.innerHTML = dowValues(fltRetSched[depCity]);
    if (endDateFltSch.innerHTML.length == 0)
        endDateFltSch.style.display = "none"; 
    else
        endDateFltSch.style.display = "";    
    
}

/**
 * Expects Day of Week String in form of 1,2,3 .. 
 * @param {Object} inDowStr
 */
function dowValues(inDowStr)
{
    var weekArray = new Array("", "Mon", "Tue", "Wed", "Thur", "Fri", "Sat", "Sun");
    var fltStr = ""
        
    if (inDowStr == null)
        return(fltStr);
        
    var dowStrArr = inDowStr.split(",");
    
    if (dowStrArr.length == 0)
		return(fltStr);
		   
    for(var i = 0; i < dowStrArr.length; i++)
    {
		var dayOfWeekNum = dowStrArr[i];
		
		if (!dayOfWeekNum || dayOfWeekNum > 7 || dayOfWeekNum < 0)
			continue;
			
        fltStr = fltStr + weekArray[dayOfWeekNum];
        
        if (i != (dowStrArr.length - 1))
            fltStr = fltStr + ", ";
    }
  
  	if (fltStr.length == 0)
		return(fltStr);
		
    return("No Flights: " + fltStr);
}

function verifyCdp(arg_form)
{
    lclMsg = "";
    totalPassengers =parseInt (arg_form.child_1.value) +  parseInt (arg_form.adult_1.value);
    
    if (( totalPassengers < minTotPax) || ( totalPassengers > maxTotPax))
    {
       lclMsg += "- Selected a minimum of " + minTotPax + " and a maximum " + maxTotPax + " passengers (incl. children)\n";         
    }
    if (minDuration!=0)
    {
        
        selectedStay = parseInt (arg_form.duration.value); 

        
        if (selectedStay < minDuration )
        {
            lclMsg += "- The minimum number of nights allowed is " + minDuration +" \n";    
            
        }
        if (selectedStay > maxDuration)
        {
            lclMsg += "- The maximum number of nights allowed is " + maxDuration +" \n";        
        }
        
        //test if number is entered in number of nights.
        testVar = isNaN(selectedStay);
        if (testVar == true){
            lclMsg += "- Please enter a valid number for nights \n";    
        }
    }
    
    if(lclMsg!="")
    {
        lclMsg = "Please ensure you have...\n" + lclMsg;
        alert(lclMsg);
        return false;
    }

    var adult_count = arg_form.adult_1.value;
    var child_count = arg_form.child_1.value;
    var room_mixes = adult_count + "A";
    if (child_count > 0)
    {
        room_mixes += child_count + "C";
        for (i = 1; i <= child_count; i++)
            room_mixes += "-" + document.getElementById("cdpRm1ChildAge" + i).value;
    }          

    document.getElementById("room_mixes").value = room_mixes;   

    return true;
}

function displayCdpChildAgeBoxes(numChild)
{
    if (document.getElementById("cdpBook")!=null){
        // random children allowed for hotel and holiday booking
        var chdds = document.getElementById("cdpBook").getElementsByTagName("dd");
        totNum = chdds.length;
    } else {
        //fixed number for site main search box hotel booking
        totNum = 4;
    }
    document.getElementById("ChildAgeRow").style.display = numChild > 0 ? "" : "none";
    for (i=1; i<=numChild; i++)
        document.getElementById("cdpRm1ChildAge" + i).style.display = "";
    for (; i<=totNum; i++)
        document.getElementById("cdpRm1ChildAge" + i).style.display = "none";
    
}

function goButtonValidate(inDurationField)
{
    var durationFld = document.getElementById(inDurationField);
    if (durationFld.value == null || durationFld.value.length == 0)
    {
        return(false);
    }
    return(true);
}

function getWaitMessage(inMessageCode)
{
	var waitNotices = new Array()
	waitNotices["initialWaitNotice"] = "We're checking availability and finding the best prices for your Holiday Package ...";
	waitNotices["updateBooking"] = "Please wait while we update your booking.";
	waitNotices["removingModule"] = "Please wait while we remove your activity.";
	waitNotices["checkingAvailability"] = "Please wait while we check for availability.";
	waitNotices["bookButton"] = "Please wait while we confirm your booking.";
	waitNotices["paymentButton"] = "Please wait while we confirm your booking.";
	waitNotices["returnBooking"] = "Please wait while we return you to your booking"
	return (waitNotices[inMessageCode]);
}

function updateWaitingDivNotice(inMessageCode)
{
	var waitNoticeContent = document.getElementById('waitNoticeContent');

	if (!waitNoticeContent || waitNoticeContent == null)
		return;
		
	waitNoticeContent.innerHTML = getWaitMessage(inMessageCode);		
}

function load()
{          
   CPackage.showWaitNotice = showWaitNotice;     
   CPackage.hideWaitNotice = hideWaitNotice;
   CPackage.enableItineraryCompletion = pen_enable_book;
   CPackage.disableItineraryCompletion = pen_disable_book;
   CPackage.editingComponent = editComp;
} 

function onDepSelect(cal, date)
{
	var oldDepDate = document.getElementById("startDate").value;
	var endDate = document.getElementById("endDate").value;
	
    if (cal.dateClicked)
    {
        output.value = date;
        prevDate.setTime(cal.date.getTime());
        cal.hide();
    }
    
    // This feels wrong on so many levels.
    var depDate = new Date(convertDate(oldDepDate)); 
    
	if (!document.getElementById("endDate"))
		return;
		
    var retDate = new Date(convertDate(endDate));
    var duration = calculateDuration(depDate, retDate);
    var newRetDate = convertDatePlusOffset(document.getElementById("startDate").value, duration);

	if (duration == 0)
	{
		document.getElementById("duration").value = duration;
		document.getElementById("endDate").value = convertDateMMDDYYYYtoDDMMMYY(newRetDate);
	}
	else
	{
		document.getElementById("durationOutput").innerHTML = "";
		document.getElementById("duration").value = "";
		document.getElementById("endDate").value = "";
	}
}

function onRetSelect(cal, date)
{
    if (cal.dateClicked)
    {
        output.value = date;
        prevDate.setTime(cal.date.getTime());
        cal.hide();
    }
    
    // This feels wrong on so many levels.
    var depDate = new Date(convertDate(document.getElementById("startDate").value)); 
    
	if (!document.getElementById("endDate"))
		return;
		
    var retDate = new Date(convertDate(document.getElementById("endDate").value));
    var duration = calculateDuration(depDate, retDate);
    
    if (duration <= 0 || isNaN(duration))
    {
		document.getElementById("durationOutput").innerHTML = "";
		document.getElementById("duration").value = "";
		document.getElementById("endDate").value = "";
        
		return;
    }
    
    generateDuration(duration);
}

function checkAdultInfant()
{
	if (!hasFlights)
		return(true);
	
	var i, child_age, number_infant = 0;
	var adults = document.getElementById("cdpRm1AdultCount").value;
	var children = document.getElementById("cdpRm1ChildCount").value;

	for(i = 1; i <= children; i++)
	{
		child_age = document.getElementById("cdpRm1ChildAge" + i).value;
		if (child_age == 1)
			number_infant++;
	}
	
	if (adults < number_infant)
	{
		alert("Number of children under the age of 1 can not be greater than number of adults");
		return(false);
	}
	return(true);
}