var calendar = null;
var divId = "";
var weekDays = [ "S", "M", "T", "W", "T", "F", "S" ];
var MIN_YEAR = 1900;
var MAX_YEAR = 2070;
var MONTHS = 12;

function createHiddenIFrame(){
	return document.createElement("<IFRAME style='filter:progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0);position:absolute;top:0px;left:0px;width:100%;height:100%;z-index:-1' frameBorder=0 scrolling=no src='javascript:false;' ></IFRAME>");
}

function Calendar( startDate, selectedDate, disabledDateRanges, fieldName, specialDates, activatePastDatesNavigation ) {	
	this.startDate = startDate;
	this.monthIndex = 0;
	this.selectedDate = selectedDate;	
	this.disabledDateRanges = disabledDateRanges;	
	this.fieldName = fieldName;

	this.todaysDateCSSClassName = "calendarBgc01 calendarTd calendarBold calendarHand";
	this.onMouseOverCSSClassName = "calendarBgc04 calendarTd calendarBold calendarHand";
	this.defaultCSSClassName = "calendarTd calendarHand";
	this.selectedDateCSSClassName = "calendarTd calendarBold calendarHand calendarBgc05";
	this.specialDates = specialDates;
	this.specialDateCSSClassName = "calendarBgc05 calendarTd calendarBold calendarHand";
	this.disbaleDateCSSClassName = "calendarLt calendarTc02 calendarTd";
	this.activatePastDatesNavigation = activatePastDatesNavigation;
}

function DateRange( fromDate, toDate ) {
	this.fromDate = fromDate;
	this.toDate = toDate;
}

function showCalendar( fieldName, specialDates, disabledDateRanges, startDate, activatePastDatesNavigation ) {
	var selectedFieldValue = document.getElementById( fieldName ).value;
	var selectedDate = null;
	if( !( isNaN( new Date( selectedFieldValue ) ) ) ) {
		selectedDate = new Date( selectedFieldValue );
		selectedDate.setHours( 0 );
		selectedDate.setMinutes( 0 );
		selectedDate.setSeconds( 0 );
		selectedDate.setMilliseconds( 0 );
		startDate = new Date( selectedDate );
	} else if( !( isNull( specialDates ) ) ) { //specialDates is an associative array, which contains date as a key as well as value.
		for( var specialDateKey in specialDates ) {
			if( !( isNaN( new Date( specialDateKey ) ) ) ) {
				startDate = new Date( specialDateKey );
				break;
			}
		}
	}
	if( isNull( startDate ) && !( isEmpty( disabledDateRanges ) ) ) {
		var numberOfDisabledDateRanges = disabledDateRanges.length;
		var currentDate = getCurrentDate();
		for( var index = 0 ; index < ( numberOfDisabledDateRanges ) ; index++ ) {
			var toDate = new Date( disabledDateRanges[index].toDate );
			if( compareDates( toDate, currentDate ) >= 0 && ( toDate.getFullYear() < MAX_YEAR ) ) {
				startDate = toDate;
				startDate.setDate( startDate.getDate() + 1 );
				break;
			}
		}
	}
 	if( isNull( startDate ) ) {
		startDate = getCurrentDate();
	}
	if( isNull( activatePastDatesNavigation ) ) {
		activatePastDatesNavigation = false;
	}
	createCalendar( startDate, selectedDate, fieldName, disabledDateRanges, specialDates, activatePastDatesNavigation );
}

function createCalendar( startDate, selectedDate, fieldName, disabledDateRanges, specialDates, activatePastDatesNavigation ) {
	divId = "calendarPopup";
	if( !isNull( document.getElementById( divId ) ) ) {
		document.onmousedown = function() {};
		document.onmouseover = function() {};
	}
	calendar = new Calendar( startDate, selectedDate, disabledDateRanges, fieldName, specialDates, activatePastDatesNavigation );
	var calendarPopup = createCalendarPopup();
	if( isIE() && ( browserVersion <= 6 ) ) {
		window.setTimeout( displayCalendar, 250 );
		setCalendarDefaultCoordinates( fieldName, divId );
		//hideElementsForCalendar( divId );
	} else {
		displayCalendar();
		setCalendarDefaultCoordinates( fieldName, divId );
	}
	document.onmouseover = function() { document.onmousedown = function() { closeCalendar( divId ); }; };
}

function createCalendarPopup() {
	var calendarPopup = document.getElementById( divId );
	if( isNull( calendarPopup ) ) {
		calendarPopup = createPopupDiv( divId, 0, 0, 470, 300, true, false, "" );
		
		calendarPopup.onmouseover = function( event ) { setDragEvent( divId, event, 15 ) };
		calendarPopup.style.height = '215';
	}
	return calendarPopup;
}

function setCalendarDefaultCoordinates( fieldName, divId ) {
	var referenceElement = document.getElementById( fieldName );
	var referenceElementHeight = referenceElement.offsetHeight;
	var referenceElementPos = getPosRelativeToPage(referenceElement);
	var referenceElementLeft = referenceElementPos.x;
	var referenceElementTop = referenceElementPos.y;
	var pageRect = getPageRect();
	var pageLeft = pageRect.x;
	var pageTop = pageRect.y;
	var pageHeight = pageRect.height;
	var pageWidth = pageRect.width;
	var calendarPopup = document.getElementById( divId );	
	if( ( referenceElementTop + referenceElementHeight + calendarPopup.offsetHeight ) > ( pageTop + pageHeight ) ) {
		referenceElementTop = referenceElementTop - calendarPopup.offsetHeight;
	} else {
		referenceElementTop = referenceElementTop + referenceElementHeight + 5;
	}
	if( ( referenceElementLeft + calendarPopup.offsetWidth ) > pageLeft + pageWidth ) {
		referenceElementLeft = pageLeft + pageWidth - calendarPopup.offsetWidth - 10;
	} 
	calendarPopup.style.top = referenceElementTop;
	calendarPopup.style.left = referenceElementLeft;
}

function displayCalendar() {
	var startDate = new Date( calendar.startDate.getFullYear(), calendar.startDate.getMonth(), calendar.startDate.getDate() );
	startDate.setHours( 0 );
	startDate.setMinutes( 0 );
	startDate.setSeconds( 0 );
	startDate.setMilliseconds( 0 );
	if( isNaN( startDate ) ) {
		startDate = getCurrentDate();
	}

	if( !( isValidYear( startDate )  ) ) {
		alert( "Please enter a valid year between 1900 and 2070" );
		return;
	}
	
	if( ( startDate.getFullYear() == MAX_YEAR ) &&  ( startDate.getMonth() == 11 ) ) {
		// When MAX_YEAR and 12th month is selected.Display 11th as first Month.
		startDate.setMonth( startDate.getMonth() - 1 );
	}

	startDate.setDate( 1 );
	startDate.setMonth( startDate.getMonth() + parseInt( calendar.monthIndex, 10 ) );
	var firstMonthCalendar = getCalenderByMonth( startDate, true );
	startDate.setMonth( startDate.getMonth() + 1 );
	var secondMonthCalendar = getCalenderByMonth( startDate, false );

	var calendarMainTable = document.createElement( "TABLE" );
	calendarMainTable.id = 'allotmentCalendarTable';
	calendarMainTable.cellSpacing = '0';
	calendarMainTable.cellPadding = '0';

	var calendarTBody = document.createElement( "TBODY" );
	
	// Row 1
	var row1 = document.createElement( "TR" );

	var column1Row1 = document.createElement( "TD" );
	column1Row1.className = 'calendarTopLeftBorder calendarBgc00'
	var spacerImageLeftBorder = document.createElement( "IMG" );
	spacerImageLeftBorder.src = _webLoc + '/shared/images/core/spacer.gif';
	spacerImageLeftBorder.alt = "";
	spacerImageLeftBorder.border = '0';
	spacerImageLeftBorder.width = '1';
	spacerImageLeftBorder.height = '1';
	column1Row1.appendChild( spacerImageLeftBorder );

	var column2Row1 = document.createElement( "TD" );
	column2Row1.colSpan = '2';
	column2Row1.className = 'calendarTopBorder calendarPr10 calendarBgc00';
	var spacerImageTopBorder1 = document.createElement( "IMG" );
	spacerImageTopBorder1.src = _webLoc + '/shared/images/core/spacer.gif';
	spacerImageTopBorder1.alt = "";
	spacerImageTopBorder1.border = '0';
	spacerImageTopBorder1.width = '1';
	spacerImageTopBorder1.height = '1';
	column2Row1.appendChild( spacerImageTopBorder1 );
	
	if( calendar.activatePastDatesNavigation ) {
		column2Row1.appendChild( getYearSelectionTable( startDate ) );
	}
	
	var column4Row1 = document.createElement( "TD" );
	column4Row1.className = 'calendarTopRightCorner';
	var imageForColumn4Row1 = document.createElement( "IMG" );
	if( calendar.activatePastDatesNavigation ) {
		imageForColumn4Row1.src = _webLoc + '/shared/images/calendar/topRightCorner_02.png';
	} else {
		imageForColumn4Row1.src = _webLoc + '/shared/images/calendar/topRightCorner.png';		
	}
	imageForColumn4Row1.alt = "";
	column4Row1.appendChild( imageForColumn4Row1 );
	
	row1.appendChild( column1Row1 );
	row1.appendChild( column2Row1 );	
	row1.appendChild( column4Row1 );

	//Row 2
	var row2 = document.createElement( "TR" );

	var column1Row2 = document.createElement( "TD" );
	column1Row2.className = 'calendarLeftBorder calendarBgc00';
	var spacerImageForLeftBorder1 = document.createElement( "IMG" );
	spacerImageForLeftBorder1.src = _webLoc + '/shared/images/core/spacer.gif';
	spacerImageForLeftBorder1.alt = "";
	spacerImageForLeftBorder1.border = '0';
	spacerImageForLeftBorder1.width = '1';
	spacerImageForLeftBorder1.height = '1';
	column1Row2.appendChild( spacerImageForLeftBorder1 );

	//First Month table
	var column2Row2 = document.createElement( "TD" );
	column2Row2.className = 'calendarValt calendarPr05 calendarBgc00';
	column2Row2.appendChild( firstMonthCalendar );
	
	//Second Month table
	var column3Row2 = document.createElement( "TD" );
	column3Row2.className = 'calendarValt calendarPr10 calendarBgc00';
	column3Row2.appendChild( secondMonthCalendar );
	
	var column4Row2 = document.createElement( "TD" );
	column4Row2.className = 'calendarRightBg';
	column4Row2.rowSpan = '2';
	var imageForColumn4Row2 = document.createElement( "IMG" );
	imageForColumn4Row2.src = _webLoc + '/shared/images/calendar/rightBg.png';
	imageForColumn4Row2.alt = "";
	imageForColumn4Row2.height = '190';
	column4Row2.appendChild( imageForColumn4Row2 );

	row2.appendChild( column1Row2 );
	row2.appendChild( column2Row2 );
	row2.appendChild( column3Row2 );
	row2.appendChild( column4Row2 );
	
	// Row 3	
	var row3 = document.createElement( "TR" );
	var column1Row3 = document.createElement( "TD" );
	column1Row3.className = 'calendarLeftBorder calendarBgc00';
	var spacerImageForLeftBorder2 = document.createElement( "IMG" );
	spacerImageForLeftBorder2.src = _webLoc + '/shared/images/core/spacer.gif';
	spacerImageForLeftBorder2.alt = "";
	spacerImageForLeftBorder2.border = '0';
	spacerImageForLeftBorder2.width = '1';
	spacerImageForLeftBorder2.height = '1';
	column1Row3.appendChild( spacerImageForLeftBorder2 );
	
	//Two colspan.
	var column2Row3 = document.createElement( "TD" );
	column2Row3.colSpan = '2';
	column2Row3.className = 'calendarTac calendarBgc00 calendarBold calendarPb05 calendarPt05 calendarFs11';
	var link = document.createElement('A');
	link.href = "javascript:;";
	link.onclick = function() { closeCalendar( divId ); }	
	var closeText = document.createTextNode( "close" );	
	link.appendChild(closeText);
	column2Row3.appendChild( link );	
	
	var column4Row3 = document.createElement( "TD" );
	column4Row3.className = 'calendarRightBg';
	
	row3.appendChild( column1Row3 );
	row3.appendChild( column2Row3 );
	row3.appendChild( column4Row3 );
	
	//Row 4
	var row4 = document.createElement( "TR" );	
	
	var column1Row4 = document.createElement( "TD" );
	column1Row4.className = 'calendarBottomLeftCorner';
	var imageForColumn1Row4 = document.createElement( "IMG" );
	imageForColumn1Row4.src = _webLoc + '/shared/images/calendar/bottomLeftCorner.png';
	imageForColumn1Row4.alt = "";
	column1Row4.appendChild( imageForColumn1Row4 );

	//Two colspan.
	var column2Row4 = document.createElement( "TD" );
	column2Row4.colSpan = '2';
	var imageForColumn2Row4 = document.createElement( "IMG" );
	imageForColumn2Row4.src = _webLoc + '/shared/images/calendar/bottomBg.png';
	imageForColumn2Row4.alt = "";
	imageForColumn2Row4.width = '435';
	column2Row4.appendChild( imageForColumn2Row4 );
	
	var column4Row4 = document.createElement( "TD" );
	column4Row4.className = 'calendarBottomRightCorner';
	var imageForColumn4Row4 = document.createElement( "IMG" );
	imageForColumn4Row4.src = _webLoc + '/shared/images/calendar/bottomRightCorner.png';
	imageForColumn4Row4.alt = "";
	column4Row4.appendChild( imageForColumn4Row4 );

	row4.appendChild( column1Row4 );
	row4.appendChild( column2Row4 );
	row4.appendChild( column4Row4 );
	
	calendarTBody.appendChild( row1 );
	calendarTBody.appendChild( row2 );
	calendarTBody.appendChild( row3 );
	calendarTBody.appendChild( row4 );

	calendarMainTable.appendChild( calendarTBody );
	
	document.getElementById( divId ).innerHTML = "";
	document.getElementById( divId ).appendChild( calendarMainTable );
	document.getElementById( divId ).style.display = "block";
	if( ( isIE() ) && ( browserVersion <= 6 ) ) {
		document.getElementById( divId ).appendChild(createHiddenIFrame());
	}
	fixPNG(imageForColumn4Row1);
	fixPNG(imageForColumn4Row2);
	fixPNG(imageForColumn1Row4);
	fixPNG(imageForColumn2Row4);
	fixPNG(imageForColumn4Row4);
}

function getYearSelectionTable( startDate ) {
	var presentDate = getCurrentDate(); 
	var yearTable = document.createElement( "TABLE" );
	yearTable.width = "100%"
	yearTable.cellSpacing = '0';
	yearTable.cellPadding = '0';
	
	var tBody = document.createElement( "TBODY" );
	
	var row1 = document.createElement( "TR" );
	
	var column1 = document.createElement( "TD" );
	column1.width = "45%";
	
	column1.align = "right";
	var previousImage = document.createElement( "IMG" );
	previousImage.src = _webLoc + '/shared/images/calendar/previousYear.gif';
	previousImage.alt = "Previous Year Button";
	previousImage.border = '0';
	previousImage.className = " calendarHand";
	if( enableDisableNavigationButtons( startDate, true ) ) {
		previousImage.onclick = function() { moveCalendarByYear( -1 ); }
	}
	column1.appendChild( previousImage );
	
	var column2 = document.createElement( "TD" );
	column2.width = "10%";
	column2.align = "center";
	var selectField = document.createElement( "SELECT" );
	var seletedYear = ( startDate.getMonth() == 0 )?( startDate.getFullYear() - 1 ):startDate.getFullYear();
	for( var index = 1900, counter = 0; index <= presentDate.getFullYear(); index++, counter++ ) {
		selectField[ counter ] = new Option( index , index );
		if( index == seletedYear ) {
			selectField[ counter ].selected = true;
		}
	}
	selectField.id = "year";
	selectField.className = "calendarFs11 textbox w60 m05";
	selectField.onchange = function() { selectYear(); }
	column2.appendChild( selectField );
	
	var column3 = document.createElement( "TD" );
	column3.width = "45%";
	column3.align = "left";
	var nextImage = document.createElement( "IMG" );
	nextImage.src = _webLoc + '/shared/images/calendar/nextYear.gif';
	nextImage.alt = "Next Year Button";
	nextImage.border = '0';
	nextImage.className = " calendarHand";
	if( enableDisableNavigationButtons( startDate, true ) ) {
		nextImage.onclick = function() { moveCalendarByYear( 1 ); }
	}
	column3.appendChild( nextImage );
	
	row1.appendChild( column1 );
	row1.appendChild( column2 );
	row1.appendChild( column3 );
	
	tBody.appendChild( row1 );

	yearTable.appendChild( tBody );
	
	return yearTable;
}

function getCalenderByMonth( startDate, showPreviousButton ) {
	var calendarTable = document.createElement( "TABLE" );
	calendarTable.className = 'calendarTable calendarBgc00';
	calendarTable.cellSpacing = '0';
	calendarTable.cellPadding = '0';

	var calendarTBody = document.createElement( "TBODY" );
	
	//Row 1
	var row1 = document.createElement( "TR" );
	row1.className = "calendarCaption"

	var column1Row1 = document.createElement( "TD" );
	column1Row1.className = "calendarTal calendarPl10";
	if( showPreviousButton ) {
		var previousImage = document.createElement( "IMG" );
		previousImage.src = _webLoc + '/shared/images/calendar/previous.gif';
		previousImage.alt = "Previous Month Button";
		previousImage.border = '0';
		previousImage.width = '9';
		previousImage.height = '10';
		previousImage.className = " calendarHand";
		if( enableDisableNavigationButtons( startDate, true ) ) {
			previousImage.onclick = function() { moveCalendarByMonth( -1 ); }
		}
		column1Row1.appendChild( previousImage );
	}

	var column2Row1 = document.createElement( "TD" );
	column2Row1.colSpan = '5';	
	column2Row1.appendChild( document.createTextNode( getMonthAndYear( startDate ) ) );	

	var column3Row1 = document.createElement( "TD" );
	column3Row1.className = "calendarTar calendarPr10";
	if( !( showPreviousButton  ) ) {
		var nextImage = document.createElement( "IMG" );
		nextImage.src = _webLoc + '/shared/images/calendar/next.gif';
		nextImage.alt = "Next Month Button";
		nextImage.border = '0';
		nextImage.width = '9';
		nextImage.height = '10';
		nextImage.className = " calendarHand";
		if( enableDisableNavigationButtons( startDate, false ) ) {
			nextImage.onclick = function() { moveCalendarByMonth( 1 ); }
		}
		column3Row1.appendChild( nextImage );
	}
	
	row1.appendChild( column1Row1 );
	row1.appendChild( column2Row1 );
	row1.appendChild( column3Row1 );

	calendarTBody.appendChild( row1 );
	
	//Row 2
	var row2 = document.createElement( "TR" );
	for( var index = 0; index < weekDays.length ;index++ ) {
		var column = document.createElement( "TD" );
		if( ( index % 6 ) == 0) {
			column.className = 'calendarHeader calendarTc04';
		} else {
			column.className = 'calendarHeader calendarTc03';
		}
		column.appendChild( document.createTextNode( weekDays[ index ] ) );
		row2.appendChild( column );
	}
	calendarTBody.appendChild( row2 );
	var loopLowerBound = 0;
	loopLowerBound -= startDate.getDay();
	var loopUpperBound = 32 - new Date( startDate.getFullYear(), startDate.getMonth(), 32 ).getDate();
	var columnCounter = 0;
	var row3;
	var noOfRows = 0;
	for( var loopCounter = loopLowerBound ; loopCounter < loopUpperBound ; loopCounter++ ) {
		if( columnCounter == 0 ) {			
			row3 = document.createElement( "TR" );
			noOfRows++;
		}
		if( loopCounter < 0 ) {
			var column = document.createElement( "TD" );
			column.className = 'calendarTd';
			column.appendChild( document.createTextNode( " ") );
			row3.appendChild( column );			
		} else {
			var date = new Date( startDate.getFullYear(), startDate.getMonth(), startDate.getDate() );
			date.setDate( date.getDate() + loopCounter );
			date.setHours( 0 );
			date.setMinutes( 0 );
			date.setSeconds( 0 );
			date.setMilliseconds( 0 );			
			var column = createDayColumn( date );
			row3.appendChild( column );
		}
		columnCounter++;
		if( columnCounter == 7 ) {			
			calendarTBody.appendChild( row3 );
			columnCounter = 0;
		}
	}
	if( ( columnCounter != 0 ) && ( columnCounter != 7 ) ) {
		for( var i = columnCounter ; i < 7 ; i++ ) {		
			var column = document.createElement( "TD" );
			column.className = 'calendarTd';
			column.appendChild( document.createTextNode( " ") );
			row3.appendChild( column );
		}		
		calendarTBody.appendChild( row3 );
	}

	calendarTable.appendChild( calendarTBody );
	return calendarTable;
}

function createDayColumn( date ) {
	var column = document.createElement( "TD" );
	var todayDate = getCurrentDate();
	var isDisabled = isDateDisabled( date, calendar.disabledDateRanges, calendar.activatePastYearNavigation );
	if( !( isDisabled ) ) {
		if( ( calendar.selectedDate != null ) && ( compareDates( date, calendar.selectedDate ) == 0 ) ) {
			column.className = calendar.selectedDateCSSClassName;
			column.onmouseover = function() { changeCSSClass( column, calendar.onMouseOverCSSClassName ); };
			column.onmouseout = function() { changeCSSClass( column, calendar.selectedDateCSSClassName ); };
		} else if ( ( calendar.specialDates != null ) && ( isSpecialDate( date, calendar.specialDates ) ) ) {
			column.className = calendar.specialDateCSSClassName;
		} else if( compareDates( todayDate, date ) == 0 ) {
			column.className = calendar.todaysDateCSSClassName;					
		} else {
			//If day is Sunday or Saturday Change CSS Color.
			if( ( date.getDay() ) % 6 == 0 ) {
				column.className = "calendarTd calendarTc04 calendarHand";		
				column.onmouseover = function() { changeCSSClass( column, "calendarBgc04 calendarTd calendarBold calendarTc04 calendarHand" ); };
				column.onmouseout = function() { changeCSSClass( column, "calendarTd calendarTc04 calendarHand" ); };
			} else {
				column.className = calendar.defaultCSSClassName;		
				column.onmouseover = function() { changeCSSClass( column, calendar.onMouseOverCSSClassName ); };
				column.onmouseout = function() { changeCSSClass( column, calendar.defaultCSSClassName ); };				
			}			
		}
		column.onclick = function() { selectDate( date ); };
		column.appendChild( document.createTextNode(  date.getDate() ) );
	} else {
		column.className = calendar.disbaleDateCSSClassName;
		column.appendChild( document.createTextNode(  date.getDate() ) );
	}
	return column;

}

function closeCalendar( divId ) {
	if( document.getElementById( divId ) != null ) {
		document.getElementById( divId ).style.display = 'none';
		if( ( isIE() ) && ( browserVersion <= 6 ) ) {
			showElementsHiddenByCalendar( divId );
		}
		removeElement( divId );
		document.onmousedown = function() {};
		document.onmouseover = function() {};
	}
}
function changeCSSClass( column, className ) {
	column.className = className;
}

function selectDate( selectedDate ) {
	document.getElementById( calendar.fieldName ).value = getFormattedDate( selectedDate );
	closeCalendar( divId );
	document.getElementById( calendar.fieldName ).select();
	document.getElementById( calendar.fieldName ).onblur();
}

function getFormattedDate( selectedDate ) {
	var dateString = "";
	if( selectedDate != null ) {
		var monthString = selectedDate.getMonth() + 1;
		if( selectedDate.getMonth() >= 0  && selectedDate.getMonth() <  9 ) {
			monthString = '0' + monthString;
		}
		var dayString = selectedDate.getDate();
		if( ( selectedDate.getDate() > 0 ) && ( selectedDate.getDate() <= 9 ) ) {
			dayString = '0' + dayString;
		}
		var yearString = selectedDate.getFullYear();
		dateString = monthString + '/' + dayString + '/' + yearString;
	}
	return dateString;
}

function isSpecialDate( date, specialDates )  {
	if( !( isNull( specialDates ) ) && !( isNull( specialDates[ date ] ) ) ) {
		return true;
	}
	return false;
}

function compareDates( firstDate, secondDate ) {
	if( ( firstDate.getFullYear() == secondDate.getFullYear() ) && ( firstDate.getMonth() == secondDate.getMonth() ) && ( firstDate.getDate() == secondDate.getDate() ) ) {
		return 0;
	} else if( firstDate > secondDate ) {
		return 1;
	} else if( firstDate < secondDate ) {
		return -1;
	}
}

function isValidYear( date ) {
	if( ( date.getFullYear() >= MIN_YEAR ) && ( date.getFullYear() <= MAX_YEAR ) ) {
		return true;
	}
	return false;
}

function isDateDisabled( date, disabledDateRanges, activatePastYearNavigation ) {
	var presentDate = getCurrentDate();
	var isDisabled = true;
	if( !( isEmpty( disabledDateRanges ) ) ) {
		if( !activatePastYearNavigation && ( compareDates( date, presentDate ) < 0 ) ) {
			return isDisabled;
		}
		var numberOfDisabledDateRanges = disabledDateRanges.length;
		for( var index = 0 ; index < numberOfDisabledDateRanges ; index++ ) {
			var dateRange = disabledDateRanges[ index ];
			if( ( compareDates( date, dateRange.fromDate ) >= 0 ) && ( compareDates( date, dateRange.toDate ) <= 0 ) ) {
				return isDisabled;
			}
		}
		isDisabled = false;
	} else if( ( !( calendar.activatePastDatesNavigation ) && ( compareDates( date, presentDate ) >= 0 ) ) || ( ( calendar.activatePastDatesNavigation ) && ( compareDates( date, presentDate ) <= 0 ) ) ) {
		isDisabled = false;
	}
	return isDisabled;
}

function compareDateWithDateRange(date, dateRange) {
	var flag1 = compareDates(dateRange.fromDate, date);
	var flag2 = compareDates(date, dateRange.toDate);
	if(flag1<=0 && flag2<=0) {
		return 0;
	} else if(flag2 >0) {
		return 1;
	}else {
		return -1;		
	}
}

function getFirstEnabledDate(fromDate, sortedDisabledDateRanges) {
	var enabledDate = fromDate;
	if(!fromDate){
		enabledDate = getMinCalendarDate();
	}	
	for(var i=0; i<sortedDisabledDateRanges.length; i++) {
		dateRange = sortedDisabledDateRanges[i];
		var flag = compareDateWithDateRange(enabledDate, dateRange);
		if(flag == -1) {		
			return enabledDate;	
		}else if(flag == 0){
			enabledDate = addDays(dateRange.toDate, 1);
		}	
	}
	return null;	
}

function hideElementsForCalendar( divId ) {
	var tagsList = new Array( 'applet', 'iframe', 'select' );
	var numberOfTags = tagsList.length;
	var hiddenElementsArray = new Array();
	for( var tagIndex = 0 ; tagIndex < numberOfTags ; tagIndex++ ) {
		var elementsToHide = document.getElementsByTagName( tagsList[ tagIndex ] );
		if( ( elementsToHide != undefined ) && ( elementsToHide != null ) ) {
			var calendarPos = getPosRelativeToPage(document.getElementById(divId));
			var calendarLeft = calendarPos.x;
			var calendarTop = calendarPos.y;
			var calendarWidth = document.getElementById( divId ).offsetWidth;
			var calendarHeight = document.getElementById( divId ).offsetHeight;
			var numberOfElements = elementsToHide.length;
			for( var elementIndex = 0 ; elementIndex < numberOfElements ; elementIndex++ ) {
				var elementToHide = elementsToHide[ elementIndex ];
				var elementPos = getPosRelativeToPage(elementToHide);
				var elementLeft = elementPos.x;
				var elementTop = elementPos.y;
				var elementRight = elementLeft + elementToHide.offsetWidth;
				var elementBottom = elementTop + elementToHide.offsetHeight;				
				var elementId = elementToHide.id;
				if( ( ( elementLeft >= calendarLeft ) && ( elementLeft <= ( calendarLeft + calendarWidth ) ) ) &&
					( ( elementTop >= calendarTop ) && ( elementTop <= ( calendarTop + calendarHeight ) ) ) ) {
					elementToHide.style.visibility = "hidden";
					hiddenElementsArray[elementId] = "1";
				} else {
					if( ( ( elementRight >= calendarLeft ) && ( elementRight <= ( calendarLeft + calendarWidth ) ) ) &&
						( ( elementBottom >= calendarTop ) && ( elementBottom <= ( calendarTop + calendarHeight ) ) ) ) {
						elementToHide.style.visibility = "hidden";
						hiddenElementsArray[elementId] = "1";
					} else {
						if( ( ( elementLeft >= calendarLeft ) && ( elementLeft <= ( calendarLeft + calendarWidth ) ) ) &&
							( ( elementBottom >= calendarTop ) && ( elementBottom <= ( calendarTop + calendarHeight ) ) ) ) {
							elementToHide.style.visibility = "hidden";
							hiddenElementsArray[elementId] = "1";
						} else {
							if( ( ( elementRight >= calendarLeft ) && ( elementRight <= ( calendarLeft + calendarWidth ) ) ) &&
								( ( elementTop >= calendarTop ) && ( elementTop <= ( calendarTop + calendarHeight ) ) ) ) {
								elementToHide.style.visibility = "hidden";
								hiddenElementsArray[elementId] = "1";
							} 
						}
					}
				}
			}
		}
	}
	_hiddenElements[divId] = hiddenElementsArray;
	return true;
}

function showElementsHiddenByCalendar(divId) {
	hideElements(false, null, divId);	
}

function mousedown() {
	document.body.style.cursor = 'default';
	mouseover = false;
}

function getMonthAndYear( date ) {
	var months = new Array( 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' );
	return ( months[ date.getMonth() ] + " " + date.getFullYear() );
}

function moveCalendarByMonth( movementIndex ) {
	if( calendar.activatePastDatesNavigation ) {
		var presentDate = getCurrentDate();
		var startDate = new Date( calendar.startDate );
		startDate.setMonth( startDate.getMonth() + parseInt( ( calendar.monthIndex + movementIndex ), 10 ) );
		if( ( startDate > presentDate ) && !( startDate.getMonth() == presentDate.getMonth() ) ) {
			return false;
		}
	}
	calendar.monthIndex = calendar.monthIndex + movementIndex;
	displayCalendar();
	return true;
}

function enableDisableNavigationButtons( date, isPreviousButton ) {
	if( isPreviousButton ) {
		if( !( ( date.getFullYear() == MIN_YEAR ) && ( date.getMonth() == 0 ) ) ) {
			return true;
		}
	} else {
		if( !( ( date.getFullYear() == MAX_YEAR ) && ( date.getMonth() == 11 ) ) ) {
			return true;
		}
	}
	return false;
}

function getMinCalendarDate() {
	var minDate = new Date();
	minDate.setFullYear(MIN_YEAR, 0 , 1);
	minDate.setHours(0);
 	minDate.setMinutes(0);
	minDate.setSeconds(0);
	minDate.setMilliseconds(0);
 	return minDate;	
}

function getMaxCalendarDate() {
	 var maxDate = new Date();
	 maxDate.setFullYear(MAX_YEAR, 11, 31);
	 maxDate.setHours(23);
	 maxDate.setMinutes(59);
	 maxDate.setSeconds(59);
	 maxDate.setMilliseconds(999);
	 return maxDate;
}

function getCurrentDate() {
	var currentDate = new Date();
	currentDate.setHours( 0 );
	currentDate.setMinutes( 0 );
	currentDate.setSeconds( 0 );
	currentDate.setMilliseconds( 0 );
	return currentDate;
}

function selectYear() {
	var presentDate = getCurrentDate();
	var selectedYear = parseInt( document.getElementById( "year" ).value, 10 );
	var startDate = new Date( calendar.startDate );
	startDate.setDate( 1 );
	startDate.setMonth( startDate.getMonth() + parseInt( calendar.monthIndex, 10 ) );
	var yearDifference = selectedYear - ( startDate.getFullYear() );
	var movementIndex = ( yearDifference * MONTHS );
	startDate.setFullYear( selectedYear );
	if( ( startDate > presentDate ) ) {
		movementIndex = movementIndex - ( startDate.getMonth() - presentDate.getMonth() );
	}
	calendar.monthIndex = calendar.monthIndex + movementIndex;
	displayCalendar();
}

function moveCalendarByYear( index ) {
	var presentDate = getCurrentDate();
	var selectedYear = parseInt( document.getElementById( "year" ).value, 10 );
	var startDate = new Date( calendar.startDate );
	var fullYear = selectedYear + index;
	var movementIndex = index * MONTHS;
	startDate.setFullYear( fullYear );
	if( !( isValidYear( startDate )  ) ) {
		return;
	}
	if( ( startDate.getFullYear() ) <= presentDate.getFullYear() ) {
		calendar.monthIndex = calendar.monthIndex + movementIndex;
		displayCalendar();
	}
}var allotmentCalendar = null;
var allotmentCalendarDivId  = "";

function AllotmentCalendar( anchorName, title, subTitle, startDate, cutoffMonths, dayAllotments, numberOfNights, productUid, disabledDateRanges, specialDates ) {
	this.anchorName = anchorName;
	this.title = title;
	this.subTitle = subTitle;
	this.startDate = startDate;
	this.cutoffMonths = cutoffMonths;
	this.monthIndex = 0;
	this.dayAllotments = dayAllotments;
	this.disableCSSClassName = "calendarLt calendarTc02 calendarTd";
	this.specialDateCSSClassName = "calendarBgc05 calendarBold";
	this.ALLOTMENT = "Y";
	this.STOPSELL = "N";
	this.ONREQUEST = "N";
	this.cssClassList = { "Y" : "calendarTd calendarHand calendarTdAvl",
						  "N" : "calendarTd calendarTdSold"
						}
	this.numberOfNights = numberOfNights;
	this.productUid = productUid;
	this.disabledDateRanges = disabledDateRanges;
	this.specialDates = specialDates;
	this.dataContainer = 'dataContent';
	this.fieldName = "calendarCheckinDate";
}

function DayAllotment( date, status ) {
	this.date = date;
	this.status = status;
}

function createAllotmentCalendar( anchorName, title, subTitle, startDate, cutoffMonths, dayAllotments, numberOfNights, productUid, disabledDateRanges, specialDates ) {
	var divId = "allotmentCalendarDivPopup";
	allotmentCalendarDivId = divId;
	
	var dayAllotments = getDayAllotmentHashMap( dayAllotments );
	allotmentCalendar = new AllotmentCalendar( anchorName, title, subTitle, startDate, cutoffMonths, dayAllotments, numberOfNights, productUid, disabledDateRanges, specialDates );
	
	var calendarPopup = createAllotmentCalendarPopup( divId );
	window.setTimeout(displayAllotmentCalendar, 100 );
	setCalendarDefaultCoordinates( anchorName, divId );
	//if( ( isIE() ) && ( browserVersion <= 6 ) ) {
		//hideElementsForCalendar( divId );
	//}
}

function getDayAllotmentHashMap( dayAllotments ) {
	if( !( isNull( dayAllotments ) ) ) {
		var numberOfDayAllotments = dayAllotments.length;
		var newDayAllotments = new Array();
		for( var index = 0 ; index < numberOfDayAllotments ; index++ ) {
			newDayAllotments[ dayAllotments[ index ].date ] = dayAllotments[ index ];
		}
		return newDayAllotments;
	}
	return null;
}

function createAllotmentCalendarPopup( divId ) {
	var calendarPopup = document.getElementById( divId );
	if( isNull( calendarPopup ) ) {
		calendarPopup = createPopupDiv( divId, 0, 0, 470, 250, true, false, "" );
		calendarPopup.onmouseover = function( event ) { setDragEvent( divId, event, 15 ) };
		calendarPopup.style.height = '250';
	}
	return calendarPopup;
}

function displayAllotmentCalendar() {
	var startDate = new Date( allotmentCalendar.startDate.getFullYear(), allotmentCalendar.startDate.getMonth(), allotmentCalendar.startDate.getDate() );
	startDate.setHours( 0 );
	startDate.setMinutes( 0 );
	startDate.setSeconds( 0 );
	startDate.setMilliseconds( 0 );
	if( isNaN( startDate ) ) {
		startDate = new Date();
	}

	if( !( isValidYear( startDate )  ) ) {
		alert( "Please enter a valid year between 1900 and 2070" );
		return;
	}
	
	if( ( startDate.getFullYear() == MAX_YEAR ) &&  ( startDate.getMonth() == 11 ) ) {
		// When MAX_YEAR and 12th month is selected.Display 11th as first Month.
		startDate.setMonth( startDate.getMonth() - 1 );
	}

	startDate.setDate( 1 );
	startDate.setMonth( startDate.getMonth() + parseInt( allotmentCalendar.monthIndex ) );
	var firstMonthCalendar = getAllotmentCalenderByMonth( startDate, true );
	startDate.setMonth( startDate.getMonth() + 1 );
	var secondMonthCalendar = getAllotmentCalenderByMonth( startDate, false );

	var calendarMainTable = document.createElement( "TABLE" );
	calendarMainTable.id = 'allotmentCalendarTable';
	calendarMainTable.cellSpacing = '0';
	calendarMainTable.cellPadding = '0';

	var calendarTBody = document.createElement( "TBODY" );
	
	// Row 1
	var row1 = document.createElement( "TR" );

	var column1Row1 = document.createElement( "TD" );
	column1Row1.className = 'calendarTopLeftBorder calendarBgc00'
	var spacerImageLeftBorder = document.createElement( "IMG" );
	spacerImageLeftBorder.src = _webLoc + '/shared/images/core/spacer.gif';
	spacerImageLeftBorder.alt = "";
	spacerImageLeftBorder.border = '0';
	spacerImageLeftBorder.width = '1';
	spacerImageLeftBorder.height = '1';
	column1Row1.appendChild( spacerImageLeftBorder );

	var column2Row1 = document.createElement( "TD" );
	column2Row1.colSpan = '2';
	column2Row1.className = 'calendarTopBorder calendarTar calendarPr10 calendarBgc00';
	var spacerImageTopBorder1 = document.createElement( "IMG" );
	spacerImageTopBorder1.src = _webLoc + '/shared/images/core/spacer.gif';
	spacerImageTopBorder1.alt = "";
	spacerImageTopBorder1.border = '0';
	spacerImageTopBorder1.width = '1';
	spacerImageTopBorder1.height = '1';
	column2Row1.appendChild( spacerImageTopBorder1 );

	var column4Row1 = document.createElement( "TD" );
	column4Row1.className = 'calendarTopRightCorner';
	var imageForColumn4Row1 = document.createElement( "IMG" );
	imageForColumn4Row1.src = _webLoc + '/shared/images/calendar/topRightCorner.png';
	imageForColumn4Row1.alt = "";
	column4Row1.appendChild( imageForColumn4Row1 );
	
	row1.appendChild( column1Row1 );
	row1.appendChild( column2Row1 );	
	row1.appendChild( column4Row1 );

	//Row 2
	var row2 = document.createElement( "TR" );

	var column1Row2 = document.createElement( "TD" );
	column1Row2.className = 'calendarLeftBorder calendarBgc00';
	var spacerImageForLeftBorder1 = document.createElement( "IMG" );
	spacerImageForLeftBorder1.src = _webLoc + '/shared/images/core/spacer.gif';
	spacerImageForLeftBorder1.alt = "";
	spacerImageForLeftBorder1.border = '0';
	spacerImageForLeftBorder1.width = '1';
	spacerImageForLeftBorder1.height = '1';
	column1Row2.appendChild( spacerImageForLeftBorder1 );

	//First  Month table
	var column2Row2 = document.createElement( "TD" );
	column2Row2.className = 'calendarValt calendarPr05 calendarBgc00';
	column2Row2.appendChild( firstMonthCalendar );
	
	//Second Month table
	var column3Row2 = document.createElement( "TD" );
	column3Row2.className = 'calendarValt calendarPr10 calendarBgc00';
	column3Row2.appendChild( secondMonthCalendar );
	
	var column4Row2 = document.createElement( "TD" );
	column4Row2.className = 'calendarRightBg';
	column4Row2.rowSpan = '3';
	var imageForColumn4Row2 = document.createElement( "IMG" );
	imageForColumn4Row2.src = _webLoc + '/shared/images/calendar/rightBg.png';
	imageForColumn4Row2.alt = "";
	imageForColumn4Row2.height = '221';
	column4Row2.appendChild( imageForColumn4Row2 );

	row2.appendChild( column1Row2 );
	row2.appendChild( column2Row2 );
	row2.appendChild( column3Row2 );
	row2.appendChild( column4Row2 );
	
	//Row 3
	var row3 = document.createElement( "TR" );
	
	var column1Row3 = document.createElement( "TD" );
	column1Row3.className = 'calendarLeftBorder calendarBgc00';
	var spacerImageForLeftBorder3= document.createElement( "IMG" );
	spacerImageForLeftBorder3.src = _webLoc + '/shared/images/core/spacer.gif';
	spacerImageForLeftBorder3.alt = "";
	spacerImageForLeftBorder3.border = '0';
	spacerImageForLeftBorder3.width = '1';
	spacerImageForLeftBorder3.height = '28';
	column1Row3.appendChild( spacerImageForLeftBorder3 );
	
	var column2Row3 = document.createElement( "TD" );
	column2Row3.className = "calendarFs11 calendarBgc00 calendarBold";
	var labelForCheckinDate = document.createElement( "LABEL" );
	labelForCheckinDate.appendChild( document.createTextNode( "Check-in Date: " ) );
	var separatorForCheckinDateAndTextBox = document.createElement( "IMG" );
	separatorForCheckinDateAndTextBox.src = _webLoc + '/shared/images/core/spacer.gif';
	separatorForCheckinDateAndTextBox.alt = "";
	separatorForCheckinDateAndTextBox.border = '0';
	separatorForCheckinDateAndTextBox.width = '8';
	separatorForCheckinDateAndTextBox.height = '1';
	labelForCheckinDate.appendChild( separatorForCheckinDateAndTextBox );
	var inputTextForCheckinDate = document.createElement( "INPUT" );
	inputTextForCheckinDate.id = "calendarCheckinDate";
	inputTextForCheckinDate.className = "calendarFs11 textbox w80";
	inputTextForCheckinDate.style.border = "1px solid #000000";
	inputTextForCheckinDate.type = "text";
	inputTextForCheckinDate.size = "11";
	inputTextForCheckinDate.value = "mm/dd/yyyy";
	inputTextForCheckinDate.onkeypress = function( event ) { return checkDate( event ); } 
	inputTextForCheckinDate.onblur = function( event ) { showText( inputTextForCheckinDate, 'mm/dd/yyyy' ); }
	inputTextForCheckinDate.onchange = function( event ) { updateCheckoutDate( inputTextForCheckinDate.id, "calendarNoOfNights", "calendarCheckoutDate" ); }
	labelForCheckinDate.appendChild( inputTextForCheckinDate );
	column2Row3.appendChild( labelForCheckinDate );
	
	var column3Row3 = document.createElement( "TD" );
	column3Row3.className = "calendarFs11 calendarBgc00 calendarBold";
	var labelForNumberOfNights = document.createElement( "LABEL" );
	labelForNumberOfNights.appendChild( document.createTextNode( "# of Nights: " ) );
	var numberOfNightsDropDown = document.createElement( "SELECT" );
	numberOfNightsDropDown.id = "calendarNoOfNights";
	numberOfNightsDropDown.onchange = function( event ) { updateCheckoutDate( inputTextForCheckinDate.id, "calendarNoOfNights", "calendarCheckoutDate" ); };
	numberOfNightsDropDown.className = "calendarFs11 textbox w50";
	numberOfNightsDropDown[0] = new Option( "-", "" );
	for( var index = 1; index <= 30 ; index++ ) {
		numberOfNightsDropDown[ index ] = new Option( index , index );
		if( allotmentCalendar.numberOfNights == index ) {
			numberOfNightsDropDown[ index ].selected = true;
		}
	}
	labelForNumberOfNights.appendChild( numberOfNightsDropDown );
	column3Row3.appendChild( labelForNumberOfNights );
		
	var column4Row3 = document.createElement( "TD" );
	column4Row3.className = 'calendarRightBg';
	
	row3.appendChild( column1Row3 );
	row3.appendChild( column2Row3 );
	row3.appendChild( column3Row3 );
	row3.appendChild( column4Row3 );
	
	//Row 5
	var row4 = document.createElement( "TR" );
	
	//Two colspan.	
	var column1Row4 = document.createElement( "TD" );
	column1Row4.className = 'calendarLeftBorder calendarBgc00';
	var spacerImageForLeftBorder4= document.createElement( "IMG" );
	spacerImageForLeftBorder4.src = _webLoc + '/shared/images/core/spacer.gif';
	spacerImageForLeftBorder4.alt = "";
	spacerImageForLeftBorder4.border = '0';
	spacerImageForLeftBorder4.width = '1';
	spacerImageForLeftBorder4.height = '30';
	column1Row4.appendChild( spacerImageForLeftBorder4 );
	
	var column2Row4 = document.createElement( "TD" );
	column2Row4.className = "calendarFs11 calendarBgc00 calendarBold";
	var labelForCheckoutDate = document.createElement( "LABEL" );
	labelForCheckoutDate.appendChild( document.createTextNode( "Check-out Date: " ) );
	var inputTextForCheckoutDate = document.createElement( "INPUT" );
	inputTextForCheckoutDate.id = "calendarCheckoutDate";
	inputTextForCheckoutDate.className = "calendarFs11 textbox w80";
	inputTextForCheckoutDate.type = "text";
	inputTextForCheckoutDate.size = "11";
	inputTextForCheckoutDate.value = "mm/dd/yyyy";
	inputTextForCheckoutDate.onkeypress = function( event ) { return checkDate( event ); } 
	inputTextForCheckoutDate.onblur = function( event ) {  showText( inputTextForCheckoutDate, 'mm/dd/yyyy' ); }
	inputTextForCheckoutDate.onchange = function( event ) { updateNights( inputTextForCheckinDate.id, "calendarNoOfNights", "calendarCheckoutDate" ); };
	labelForCheckoutDate.appendChild( inputTextForCheckoutDate );
	column2Row4.appendChild( labelForCheckoutDate );
	
	// Added onfocus event for checkin date and checkout date textbox;
	var borderColor = "1px solid #000000";
	inputTextForCheckinDate.onfocus = function( event ) { 	clearText( inputTextForCheckinDate, 'mm/dd/yyyy' );
														  	selectTextField( inputTextForCheckinDate, borderColor ); 
														  	changeBorderColor( inputTextForCheckoutDate, "1px solid #7f9db9" ); 
														 }
	inputTextForCheckoutDate.onfocus = function( event ) { 	clearText( inputTextForCheckoutDate, 'mm/dd/yyyy' );
															selectTextField( inputTextForCheckoutDate, borderColor ); 
														  	changeBorderColor( inputTextForCheckinDate, "1px solid #7f9db9" ); 
														 }
	//Ends here
												
	var column3Row4 = document.createElement( "TD" );
	column3Row4.className = 'calendarBgc00';
	
	var closeImage = document.createElement( "IMG" );
	closeImage.src = _webLoc + "/shared/images/core/buttons/close-red-btn.gif";
	closeImage.alt = "Close Calendar Button";
	closeImage.className = 'button';
	closeImage.onclick = function( event ) { closeCalendar( allotmentCalendarDivId ); disableElement( allotmentCalendar.dataContainer, false ); };
	column3Row4.appendChild( closeImage );
	
	var separator =  document.createElement( "IMG" );
	separator.src = _webLoc + '/shared/images/core/spacer.gif';
	separator.alt = "";
	separator.border = '0';
	separator.width = '10';
	separator.height = '1';
	column3Row4.appendChild( separator );
	
	var searchImage= document.createElement( "IMG" );
	searchImage.src = _webLoc + '/shared/images/core/buttons/search-red-btn.gif';
	searchImage.alt = "Search Button";
	searchImage.className = "button";
	searchImage.onclick = function() { searchAgain(); };
	column3Row4.appendChild( searchImage );
	
	var column4Row4 = document.createElement( "TD" );
	column4Row4.className = 'calendarRightBg';
	
	row4.appendChild( column1Row4 );
	row4.appendChild( column2Row4 );
	row4.appendChild( column3Row4 );
	row4.appendChild( column4Row4 );
	
	//Row 6
	var row5 = document.createElement( "TR" );
	var column1Row5 = document.createElement( "TD" );
	column1Row5.className = 'calendarBottomLeftCorner';
	var imageForColumn1Row5 = document.createElement( "IMG" );
	imageForColumn1Row5.src = _webLoc + '/shared/images/calendar/bottomLeftCorner.png';
	imageForColumn1Row5.alt = "";
	column1Row5.appendChild( imageForColumn1Row5 );

	//Two colspan.
	var column2Row5 = document.createElement( "TD" );
	column2Row5.colSpan = '2';
	column2Row5.align = "right";
	var imageForColumn2Row5 = document.createElement( "IMG" );
	imageForColumn2Row5.src = _webLoc + '/shared/images/calendar/bottomBg.png';
	imageForColumn2Row5.alt = "";
	imageForColumn2Row5.width = '435';
	column2Row5.appendChild( imageForColumn2Row5 );
	
	var column4Row5 = document.createElement( "TD" );
	column4Row5.className = 'calendarBottomRightCorner';
	var imageForColumn4Row5 = document.createElement( "IMG" );
	imageForColumn4Row5.src = _webLoc + '/shared/images/calendar/bottomRightCorner.png';
	imageForColumn4Row5.alt = "";
	column4Row5.appendChild( imageForColumn4Row5 );

	row5.appendChild( column1Row5 );
	row5.appendChild( column2Row5 );
	row5.appendChild( column4Row5 );

	calendarTBody.appendChild( row1 );
	calendarTBody.appendChild( row2 );
	calendarTBody.appendChild( row3 );
	calendarTBody.appendChild( row4 );
	calendarTBody.appendChild( row5 );

	calendarMainTable.appendChild( calendarTBody );
	
	document.getElementById( allotmentCalendarDivId ).innerHTML = "";
	document.getElementById( allotmentCalendarDivId ).appendChild( calendarMainTable );
	document.getElementById( allotmentCalendarDivId ).style.display = "block";
	document.getElementById( allotmentCalendarDivId ).style.visibility = "visible";
	if( ( isIE() ) && ( browserVersion <= 6 ) ) {
		document.getElementById( allotmentCalendarDivId ).appendChild(createHiddenIFrame());
	}
	fixPNG(imageForColumn4Row1);
	fixPNG(imageForColumn4Row2);
	fixPNG(imageForColumn1Row5);
	fixPNG(imageForColumn2Row5);
	fixPNG(imageForColumn4Row5);
}

function getAllotmentCalenderByMonth( startDate, showPreviousButton ) {
	var calendarTable = document.createElement( "TABLE" );
	calendarTable.className = 'calendarTable calendarBgc00';
	calendarTable.cellSpacing = '0';
	calendarTable.cellPadding = '0';

	var calendarTBody = document.createElement( "TBODY" );
	
	//Row 1
	var row1 = document.createElement( "TR" );
	row1.className = "calendarCaption"

	var column1Row1 = document.createElement( "TD" );
	column1Row1.className = "calendarTal calendarPl10";
	if( showPreviousButton && !( allotmentCalendar.monthIndex <= -( allotmentCalendar.cutoffMonths ) ) ) {
		var previousImage = document.createElement( "IMG" );
		previousImage.src = _webLoc + '/shared/images/calendar/previous.gif';
		previousImage.alt = "Previous Month Button";
		previousImage.border = '0';
		previousImage.width = '9';
		previousImage.height = '10';
		previousImage.className = " calendarHand";
		if( enableDisableNavigationButtons( startDate, true ) ) {
			previousImage.onclick = function() { moveAllotmentCalendarByMonth( -1 ); }
		}
		column1Row1.appendChild( previousImage );
	}

	var column2Row1 = document.createElement( "TD" );
	column2Row1.colSpan = '5';	
	column2Row1.appendChild( document.createTextNode( getMonthAndYear( startDate ) ) );	

	var column3Row1 = document.createElement( "TD" );
	column3Row1.className = "calendarTar calendarPr10";
	if( !( showPreviousButton  ) && !( allotmentCalendar.monthIndex >= allotmentCalendar.cutoffMonths ) ) {
		var nextImage = document.createElement( "IMG" );
		nextImage.src = _webLoc + '/shared/images/calendar/next.gif';
		nextImage.alt = "Next Month Button";
		nextImage.border = '0';
		nextImage.width = '9';
		nextImage.height = '10';
		nextImage.className = " calendarHand";
		if( enableDisableNavigationButtons( startDate, false ) ) {
			nextImage.onclick = function() { moveAllotmentCalendarByMonth( 1 ); }
		}
		column3Row1.appendChild( nextImage );
	}
	
	row1.appendChild( column1Row1 );
	row1.appendChild( column2Row1 );
	row1.appendChild( column3Row1 );

	calendarTBody.appendChild( row1 );
	
	//Row 2
	var row2 = document.createElement( "TR" );
	for( var index = 0; index < weekDays.length ;index++ ) {
		var column = document.createElement( "TD" );
		if( ( index % 6 ) == 0) {
			column.className = 'calendarHeader calendarTc04';
		} else {
			column.className = 'calendarHeader calendarTc03';
		}
		column.appendChild( document.createTextNode( weekDays[ index ] ) );
		row2.appendChild( column );
	}
	calendarTBody.appendChild( row2 );
	var loopLowerBound = 0;
	loopLowerBound -= startDate.getDay();
	var loopUpperBound = 32 - new Date( startDate.getFullYear(), startDate.getMonth(), 32 ).getDate();
	var columnCounter = 0;
	var row3;
	var noOfRows = 0;
	for( var loopCounter = loopLowerBound ; loopCounter < loopUpperBound ; loopCounter++ ) {
		if( columnCounter == 0 ) {			
			row3 = document.createElement( "TR" );
			noOfRows++;
		}
		if( loopCounter < 0 ) {
			var column = document.createElement( "TD" );
			column.className = 'calendarTd';
			column.appendChild( document.createTextNode( " ") );
			row3.appendChild( column );			
		} else {
			var date = new Date( startDate.getFullYear(), startDate.getMonth(), startDate.getDate() );
			date.setDate( date.getDate() + loopCounter );
			date.setHours( 0 );
			date.setMinutes( 0 );
			date.setSeconds( 0 );
			date.setMilliseconds( 0 );			
			var column = createAllotmentDayColumn( date );
			row3.appendChild( column );
		}
		columnCounter++;
		if( columnCounter == 7 ) {			
			calendarTBody.appendChild( row3 );
			columnCounter = 0;
		}
	}
	if( ( columnCounter != 0 ) && ( columnCounter != 7 ) ) {
		for( var i = columnCounter ; i < 7 ; i++ ) {		
			var column = document.createElement( "TD" );
			column.className = 'calendarTd';
			column.appendChild( document.createTextNode( " ") );
			row3.appendChild( column );
		}		
		calendarTBody.appendChild( row3 );
	}

	calendarTable.appendChild( calendarTBody );
	return calendarTable;
}

function createAllotmentDayColumn( date ) {
	var column = document.createElement( "TD" );
	var todayDate = new Date();
	todayDate.setHours( 0 );
	todayDate.setMinutes( 0 );
	todayDate.setSeconds( 0 );
	todayDate.setMilliseconds( 0 );
	var dayAllotment = getDayAllotment( date );
	if( isDateDisabled( date, allotmentCalendar.disabledDateRanges, false ) ) {
		column.className = allotmentCalendar.disableCSSClassName;
		column.appendChild( document.createTextNode(  date.getDate() ) );
	} else if( !( isNull( dayAllotment ) ) ) {
		var specialDateCSS = ( isSpecialDate( date, allotmentCalendar.specialDates ) ) ? allotmentCalendar.specialDateCSSClassName:"";
		column.className = specialDateCSS + allotmentCalendar.cssClassList[ dayAllotment.status ];
		if( dayAllotment.status == allotmentCalendar.ALLOTMENT ) {
			column.onclick = function() { selectAllotmentDate( date ); }
		}
		column.appendChild( document.createTextNode( date.getDate() ) );
	} else {
		column.className = allotmentCalendar.disableCSSClassName;
		column.appendChild( document.createTextNode(  date.getDate() ) );
	}
	return column;
}

function moveAllotmentCalendarByMonth( movementIndex ) {
	allotmentCalendar.monthIndex = allotmentCalendar.monthIndex + movementIndex;
	displayAllotmentCalendar();
	return true;
}

function selectAllotmentDate( selectedDate ) {
	var element = document.getElementById( allotmentCalendar.fieldName ); 
	element.value = getFormattedDate( selectedDate );
	element.onchange();
	clearErrorElements();
	changeBorderColor( element, "1px solid #000000" );
}

function updateCheckoutDate( checkinDateFieldName, nightsFieldName, checkoutDateFieldName ) {
	var numberOfNights = document.getElementById( nightsFieldName ).value;
	var checkinDate = new Date( document.getElementById( checkinDateFieldName ).value );
	if( !( isNaN( checkinDate ) ) ) {
		if( numberOfNights == "" ) {
			showErrorMessage('Please select the number of nights.', allotmentCalendarDivId );
			return false;
		}
		numberOfNights = parseInt( numberOfNights );
		var checkoutDate = addDays( checkinDate, numberOfNights );
		if( isDateDisabled( checkoutDate, allotmentCalendar.disabledDateRanges, false ) ) {
			showErrorMessage('Package is not available for given Check-out date. Please try with different dates.', allotmentCalendarDivId );
			document.getElementById( checkoutDateFieldName ).value = "mm/dd/yyyy";
			return false;
		}
		document.getElementById( checkoutDateFieldName ).value = getFormattedDate( checkoutDate );
	} 
}

function updateNights( checkinDateFieldName, nightsFieldName, checkoutDateFieldName ) {
	var checkinDate = new Date( document.getElementById( checkinDateFieldName ).value );
	var checkoutDate = new Date( document.getElementById( checkoutDateFieldName ).value );
	if( !( isNaN( checkinDate ) ) && !( isNaN( checkoutDate ) ) ) {
		var nights = computeDifferenceBetweenDates( checkinDate, checkoutDate );
		if( ( nights > 0 ) && ( nights <= 30 ) ) { 
			document.getElementById( nightsFieldName ).value = nights;
		} else {
			document.getElementById( nightsFieldName )[0].selected = true;
		}
	}
}

function getDayAllotment( date ) {
	var dayAllotments = allotmentCalendar.dayAllotments;
	if( !isNull( dayAllotments ) ) {
		return dayAllotments[ date ];	
	}
	return null;
}

function searchAgain() {
	clearErrorElements();
	var checkinDate = document.getElementById( "calendarCheckinDate" ).value;
	var checkoutDate = document.getElementById( "calendarCheckoutDate" ).value;
	if( checkinDate == 'mm/dd/yyyy' || checkinDate == '' ) {
		showErrorMessage('Please enter a Check-in date.', allotmentCalendarDivId, 'calendarCheckinDate', '1px solid #7f9db9');
		return false;
	}
	if( checkoutDate == 'mm/dd/yyyy' || checkoutDate == '' ) {
		showErrorMessage('Please enter a Check-out date.', allotmentCalendarDivId, 'calendarCheckoutDate', '1px solid #7f9db9');
		return false;
	}
	if( validateDate( 'calendarCheckinDate', allotmentCalendarDivId ) && validateDate( 'calendarCheckoutDate', allotmentCalendarDivId ) ) {
		//checkinDate = new Date( checkinDate );
		//checkoutDate = new Date( checkoutDate );
		if( isDateDisabled( new Date( checkinDate ), allotmentCalendar.disabledDateRanges, false ) ) {
			showErrorMessage('Package is not available for given Check-in date. Please try with different dates.', allotmentCalendarDivId );
			return false;
		}
		if( isDateDisabled( new Date( checkoutDate ), allotmentCalendar.disabledDateRanges, false ) ) {
			showErrorMessage('Package is not available for given Check-out date. Please try with different dates.', allotmentCalendarDivId );
			return false;
		}
		if( compareDates( new Date( checkoutDate ), new Date( checkinDate ) ) <= 0 ) {
			showErrorMessage( 'Check-out Date should be later than Check-in Date', allotmentCalendarDivId, 'calendarCheckoutDate', '1px solid #7f9db9');
			return false;	
		}
		closeCalendar( allotmentCalendarDivId );
		disableElement( allotmentCalendar.dataContainer, false );
		performSearchAgain( checkinDate, checkoutDate, allotmentCalendar.productUid, allotmentCalendarDivId );
	}
	return true;
}

function selectTextField( field, borderColor ) {
	clearErrorElements();
	allotmentCalendar.fieldName = field.id;
	changeBorderColor( field, borderColor );
}

function changeBorderColor( field, borderColor ) {
	field.style.border = borderColor;
}
var dtCh= "/";
var minYear=1900;
var maxYear=2100;

function DaysArray(n) {
	for (var i = 1; i <= n; i++) {
		this[i] = 31;
		if (i==4 || i==6 || i==9 || i==11) {this[i] = 30;}
		if (i==2) {this[i] = 29;}
   } 
   return this;
}

function checkAlphaNumeric( event ){
	event = event || window.event;
	
	var key = (event.charCode == undefined || event.charCode == 0) ? event.keyCode : event.charCode;

	return ( ( key > 96 && key < 123 ) /*lower case letters*/|| 
			( key > 64 && key < 91 ) /*upper case letters*/|| 
			( key > 47 && key < 58 ) /*digits*/||
			( key == 8 ) /*backspace*/||
			( key == 9 ) /*tab*/ )
}

function checkCityName( event ) {	
	event = event || window.event;
	
	var key = (event.charCode == undefined || event.charCode == 0) ? event.keyCode : event.charCode;

	return ( ( key > 96 && key < 123 ) /*lower case letters*/|| 
			( key > 64 && key < 91 ) /*upper case letters*/|| 
			( key > 43 && key < 48 ) /*comma, hyphen, dot and forward slash */|| 
			( key == 8 ) /*backspace*/||
			( key == 9 ) /*tab*/|| 
			( key == 32 ) /*space*/|| 
			( key > 37 && key < 42 ) /*ampersand, single quote, left parenthesis, right parenthesis*/);
}

function checkDate( event ) {
	event = event || window.event;
	
	var key = (event.charCode == undefined || event.charCode == 0) ? event.keyCode : event.charCode;
	
	return ( ( key > 46 && key < 58 ) /*forward slash & digits*/|| 
			( key == 8 ) /*backspace*/|| 
			( key == 9 ) /*horizontal tab*/ );
}

function checkDecimal( event ){
	event = event || window.event;
	
	var key = (event.charCode == undefined || event.charCode == 0) ? event.keyCode : event.charCode;

	return ( ( key > 47 && key < 58 ) /*digits*/||
			( key == 46 ) /*dot*/ ||
			( key == 8 ) /*backspace*/||
			( key == 9 ) /*tab*/ )
}

function checkNumeric( event ){
	event = event || window.event;
	var key = (event.charCode == undefined || event.charCode == 0) ? event.keyCode : event.charCode;
	return ( ( key > 47 && key < 58 ) /*digits*/||
			( key == 8 ) /*backspace*/||
			( key == 9 ) /*tab*/ ||
			(event.keyCode == 46 && event.charCode ==0) ||
			isDeleteKey(event) /*delete*/
		   )
}

/*
Check for phone field length
*/
function validatePhoneNumber( fieldName1, fieldName2, fieldName3, message ) {
	clearErrorElements();
	var totLength;
    var value1Len = document.getElementById( fieldName1 ).value.length;
    var value2Len = document.getElementById( fieldName2 ).value.length;
    var value3Len = document.getElementById( fieldName3 ).value.length;
    totLength = value1Len + value2Len + value3Len;
    if ( totLength < 10 ) {
    	if( value1Len < 3 ) {
    		showErrorMessage( message, 'dataContent', fieldName1, '1px solid #7f9db9' );	 
    	} else if( value2Len < 3 ) {
    		showErrorMessage( message, 'dataContent', fieldName2, '1px solid #7f9db9' );
    	} else if( value3Len < 4 ) {
    		showErrorMessage( message, 'dataContent', fieldName3, '1px solid #7f9db9' );
    	} 	
    	return false;
    }
   return true;
}

function isDeleteKey(event) {
	if(event.type=="keypress") {
		//charCode not defined for IE and keypress event not fired for delete Key
		//charCode ==0 and keyCode ==46 for FireFox and keypress event fired for delete Key
		if(event.keyCode == 46 && event.charCode == 0) {
			return true;
		}		
	}else if(event.type=="keyup" || event.type=="keydown") {
		if(event.keyCode == 46) {
			return true;
		}
	}
	return false;
}

function isShiftTabOrDeleteKey(event) {
	event = event || window.event;
	var key = (event.charCode == undefined || event.charCode == 0) ? event.keyCode : event.charCode;
	return (key == 9) || (key==16) || isDeleteKey(event);
}

function isEnterKey( event ) {
	event = event || window.event;
	if( event.keyCode == 13 ) {
		return true;
	}
	return false;
}

function checkPersonName( event ) {
	event = event || window.event;
	
	var key = (event.charCode == undefined || event.charCode == 0) ? event.keyCode : event.charCode;

	return ( ( key > 96 && key < 123 ) /*lower case letters*/|| 
			( key > 64 && key < 91 ) /*upper case letters*/|| 
			( key > 43 && key < 47 ) /*comma, hyphen, dot */|| 
			( key == 8 ) /*backspace*/||
			( key == 9 ) /*tab*/|| 
			( key == 32 ) /*space*/|| 
			( key > 37 && key < 42 ) /*ampersand, single quote, left parenthesis, right parenthesis*/)
}

function isInteger(s){
	var i;
    for (i = 0; i < s.length; i++){   
        // Check that current character is number.
        var c = s.charAt(i);
        if (((c < "0") || (c > "9"))) return false;
    }
    // All characters are numbers.
    return true;
}

function isNull( object ) {
	if( ( object == undefined ) || ( object == null ) ) {
		return true;
	}
	return false;
}

function isEmpty( field ) {
	if( isNull( field ) || ( field.length == 0 ) ) {
		return true;
	}
	return false;
}

function stripCharsInBag(s,bag){
	var i;
    var returnString = "";
    // Search through string's characters one by one.
    // If character is not in bag, append to returnString.
    for (i = 0; i < s.length; i++){   
        var c = s.charAt(i);
        if (bag.indexOf(c) == -1) returnString += c;
    }
    return returnString;
}

function daysInFebruary (year){
	// February has 29 days in any year evenly divisible by four,
    // EXCEPT for centurial years which are not also divisible by 400.
    return (((year % 4 == 0) && ( (!(year % 100 == 0)) || (year % 400 == 0))) ? 29 : 28 );
}

function isDate( fieldName, containerDiv ) {
	clearErrorElements();
	var dt = document.getElementById( fieldName );
	var dtStr = dt.value;
	var daysInMonth = DaysArray(12);
	var pos1=dtStr.indexOf(dtCh);
	var pos2=dtStr.indexOf(dtCh,pos1+1);
	var strMonth=dtStr.substring(0,pos1);
	var strDay=dtStr.substring(pos1+1,pos2);
	var strYear=dtStr.substring(pos2+1);
	strYr=strYear;
	if (strDay.charAt(0)=="0" && strDay.length>1)
		strDay=strDay.substring(1);
	if (strMonth.charAt(0)=="0" && strMonth.length>1)
		strMonth=strMonth.substring(1);
	for (var i = 1; i <= 3; i++) {
		if (strYr.charAt(0)=="0" && strYr.length>1)
			strYr=strYr.substring(1);
	}
	month=parseInt(strMonth);
	day=parseInt(strDay);
	year=parseInt(strYr);
	if(trim(dtStr) != ""){
		if (pos1==-1 || pos2==-1){
			showErrorMessage('The date format should be : mm/dd/yyyy', containerDiv, fieldName, '1px solid #7f9db9' );
			return false;
		}
		if (strMonth.length<1 || month<1 || month>12){
			showErrorMessage('Please enter a valid month.', containerDiv, fieldName, '1px solid #7f9db9' );
			return false;
		}
		if (strDay.length<1 || day<1 || day>31 || (month==2 && day>daysInFebruary(year)) || day > daysInMonth[month]){
			showErrorMessage('Please enter a valid day.', containerDiv, fieldName, '1px solid #7f9db9' );;
			return false;
		}
		if (strYear.length != 4 || year==0 || year<minYear || year>maxYear){
			showErrorMessage('Please enter a valid four-digit year.', containerDiv, fieldName, '1px solid #7f9db9' );
			return false;
		}
		if (dtStr.indexOf(dtCh,pos2+1)!=-1 || isInteger(stripCharsInBag(dtStr, dtCh))==false){
			showErrorMessage('Please enter a valid date', containerDiv, fieldName, '1px solid #7f9db9' );
			return false;
		}
	}
	return true;
}

function isIE() {
	return ( (navigator.userAgent.match(/msie/i)) &&
		   !(navigator.userAgent.match(/opera/i)) );
}

function isFireFox() {
	return ( navigator.userAgent.match(/gecko/i) )
}

function isSafari() {
	var vendor = navigator.vendor || "";	
	if (vendor.indexOf("Apple Computer, Inc.") > -1) {
		return true;
	}
	return false;
}

/*Validate the emailIds*/
function validateEmail( emailIdField, container ) {
	clearErrorElements();
	var commaSeparatedEmailIds = document.getElementById(emailIdField).value ;
	var emailIdsArray = commaSeparatedEmailIds.split( "," );
	var totalNoEmailIds = emailIdsArray.length;
	if ( totalNoEmailIds == 0 && commaSeparatedEmailIds != '' ) {
		totalNoEmailIds = 1;
		emailIdsArray = commaSeparatedEmailIds;
	}
	for( var loopCounter = 0 ; loopCounter < totalNoEmailIds ; loopCounter++ ) {
		emailId = trim(emailIdsArray[loopCounter]);
		if (emailId == '' ) {		
			return true;
		}
		var invalidChars = '\/\'\\ ";:?!()[]\{\}^|#$*&%';
		for (i=0; i<invalidChars.length; i++) {
		   if (emailId.indexOf(invalidChars.charAt(i),0) > -1) {
				showErrorMessage( 'Email address contains invalid characters', container, emailIdField, '1px solid #7f9db9' );		
				document.getElementById(emailIdField).focus();
				return false;
		   }
		}
		for (i=0; i<emailId.length; i++) {
		   if (emailId.charCodeAt(i)>127) {
				showErrorMessage('Email address contains non ascii characters', container, emailIdField, '1px solid #7f9db9' );				
				document.getElementById(emailIdField).focus();
				return false;
		   }
		}
		var atPos = emailId.indexOf('@',0);
		if (atPos == -1) {
				showErrorMessage( 'Email address must contain an @', container, emailIdField, '1px solid #7f9db9' );
				document.getElementById(emailIdField).select();
				return false;
		}
		if (atPos == 0) {
				showErrorMessage( 'Email address must not start with @', container, emailIdField, '1px solid #7f9db9' );
				document.getElementById(emailIdField).select();
				return false;
		}
		if (emailId.indexOf('@', atPos + 1) > - 1) {
				showErrorMessage( 'Email address must contain only one @', container, emailIdField, '1px solid #7f9db9' );				
				document.getElementById(emailIdField).select();
				return false;
		}
		if (emailId.indexOf('.', atPos) == -1) {
				showErrorMessage( 'Email address must contain a period in the domain name', container, emailIdField, '1px solid #7f9db9' );				
				document.getElementById(emailIdField).select();
				return false;
		}
		if (emailId.indexOf('@.',0) != -1) {
				showErrorMessage( 'Period must not immediately follow @ in email address', container, emailIdField, '1px solid #7f9db9' );
				document.getElementById(emailIdField).select();
				return false;
		}
		if (emailId.indexOf('.@',0) != -1){
				showErrorMessage( 'Period must not immediately precede @ in email address', container, emailIdField, '1px solid #7f9db9' );
				document.getElementById(emailIdField).select();
				return false;
		}
		if (emailId.indexOf('..',0) != -1) {
				showErrorMessage( 'Two periods must not be adjacent in email address', container, emailIdField, '1px solid #7f9db9' );
				document.getElementById(emailIdField).select();
				return false;
		}
		var suffix = emailId.substring(emailId.lastIndexOf('.')+1);
		if(suffix) {
			suffix = suffix.toLowerCase();
		}
		if (suffix.length != 2 && suffix != 'com' && suffix != 'net' && suffix != 'org' && suffix != 'edu' && suffix != 'int' && suffix != 'mil' && suffix != 'gov' & suffix != 'arpa' && suffix != 'biz' && suffix != 'aero' && suffix != 'name' && suffix != 'coop' && suffix != 'info' && suffix != 'pro' && suffix != 'museum') {
				showErrorMessage( 'Invalid primary domain in email address', container, emailIdField, '1px solid #7f9db9' );
				document.getElementById(emailIdField).select();
				return false;
		}		
	}
	return true;
}
/*
	validate empty fields
*/
function validateField( fieldName, message ) {
	clearErrorElements();
	var field = document.getElementById( fieldName );
	if(field) {
		if( trim(field.value) == "" ||  trim(field.value) == "mm/dd/yyyy") {		
			showErrorMessage( message, 'dataContent', fieldName, '1px solid #7f9db9' );		
			return false;
		}
	}
	return true;
}

function validateDropDownField( fieldName, message, divName ) {
	clearErrorElements();
	var dropDownFieldValue = trim( document.getElementById( fieldName ).value ); 
	if( dropDownFieldValue == "" ){		
		showErrorMessage( message, 'dataContent', divName, '#7f9db9' );
		return false;
	}
	return true;
}

//for Number checking with 2 decimal part
function validateNumberWithDecimal( fieldName ) {
	var field = document.getElementById( fieldName );

	event = event || window.event;
	
	var key = (event.charCode == undefined || event.charCode == 0) ? event.keyCode : event.charCode;

	if( key != 8 && key != 37 && key != 39 && key != 46 ) {
	 	var patt = /(\d*)\.{1}(\d{0,2})/;
	 	var donepatt = /^(\d*)\.{1}(\d{2})$/;
	 	var str = field.value;
	 	var result;
	 	if ( !str.match(donepatt) ) {
	 		result = str.match( patt );
	 		if ( result!= null ) {
	 			field.value = field.value.replace(/[^\d]/gi,'');
	 			str = result[1] + '.' + result[2] ;
				field.value = str;
			} else {
		 		if ( field.value.match(/[^\d]/gi) )
	 				field.value = field.value.replace(/[^\d]/gi,'');
	 		}
		}
	}		
}

// Number checking
function validateNumber( fieldName ) {
	var field = document.getElementById( fieldName );

	event = event || window.event;
	
	var key = (event.charCode == undefined || event.charCode == 0) ? event.keyCode : event.charCode;

	if( key != 8 && key != 37 && key != 39 && key != 46 ) {
		if( field.value.match(/[^\d]/gi) ) {
 			field.value = field.value.replace(/[^\d]/gi,'');
 		}
 	}
}

// Alphanumeric checking
function validateAlphanumeric( fieldName ) {
	var field = document.getElementById( fieldName );

	event = event || window.event;
	
	var key = (event.charCode == undefined || event.charCode == 0) ? event.keyCode : event.charCode;

	if( key != 8 && key != 37 && key != 39 && key != 46 ) {
		if( field.value.match(/[^0-9a-zA-Z]/gi) ) {
 			field.value = field.value.replace(/[^0-9a-zA-Z]/,'');
 		}
 	}
}

/* funciton to validate Date. Returns true if entered value is of date format.*/
function validateDate( dateFieldName, containerDiv ) {
	var dateField = document.getElementById( dateFieldName );
	if( dateField.value != 'mm/dd/yyyy' ) {
		if( isDate( dateFieldName, containerDiv ) == false ) {
			dateField.focus();
			return false;
		}
		if( isPastDate( dateFieldName, containerDiv ) ) {
			dateField.focus();
			return false;
		}
	}
	clearErrorElements();
	return true;
}

function validateDOB( dateFieldName, containerDiv, paxType  ) {
	
	var futureDateMessage = "Date of birth cannot be future date";
	if ( paxType == 2 ) {
		futureDateMessage = "Policies regarding infants vary by cruise line. In all cases, infants may not be booked prior to their official date of birth and must be at least six months old at time of sailing.  If you wish to add an infant to your booking, you must do so prior to making final payment. For assistance, please call Costco Travel at 1-877-849-2730.";
	}
	
	var dateField = document.getElementById( dateFieldName );
	if( dateField.value != 'mm/dd/yyyy' ) {
		if( isDate( dateFieldName, containerDiv ) == false ) {
			dateField.focus();
			return false;
		}
		if( isFutureDate( dateFieldName ) ) {
			showErrorMessage( futureDateMessage, containerDiv, dateFieldName, '1px solid #7f9db9' );
			dateField.focus();
			dateField.select();
			return false;
		}
	}
	clearErrorElements();
	return true;
}

function isFutureDate( dateFieldName ) {
	var dateField = document.getElementById( dateFieldName );
	var selectedDate = new Date( dateField.value );
	var currentDate = new Date();
	currentDate.setHours( 0 );
	currentDate.setMinutes( 0 );
	currentDate.setSeconds( 0 );
	currentDate.setMilliseconds( 0 );
	if( selectedDate > currentDate ) {
		return true;
	}
	return false;
}

/* compare date with current date, returns true is */
function isPastDate( dateFieldName, containerDiv ) {
	var dateField = document.getElementById( dateFieldName );
	var selectedDate = new Date( dateField.value );
	var currentDate = new Date();
	currentDate.setHours( 0 );
	currentDate.setMinutes( 0 );
	currentDate.setSeconds( 0 );
	currentDate.setMilliseconds( 0 );
	if( selectedDate < currentDate ) {
		showErrorMessage('Please enter future date', containerDiv, dateFieldName, '1px solid #7f9db9' );
		dateField.focus();
		dateField.select();
		return true;
	}
	return false;
}

function isFloat(s)
{ 
	var reFloat = /^((\d+(\.\d*)?)|((\d*\.)?\d+))$/
    return reFloat.test(s)
}

/* Following code snippet has been taken as-is from Ultimate client-side Javascript client sniff, version 3.03 */
/* Made some minor modifications */

// Ultimate client-side JavaScript client sniff. Version 3.03
// (C) Netscape Communications 1999.  Permission granted to reuse and distribute.
// Revised 17 May 99 to add is.nav5up and is.ie5up (see below).
// Revised 21 Nov 00 to add is.gecko and is.ie5_5 Also Changed is.nav5 and is.nav5up to is.nav6 and is.nav6up
// Revised 22 Feb 01 to correct Javascript Detection for IE 5.x, Opera 4, 
//                      correct Opera 5 detection
//                      add support for winME and win2k
//                      synch with browser-type-oo.js
// Revised 26 Mar 01 to correct Opera detection
// Revised 02 Oct 01 to add IE6 detection

// Everything you always wanted to know about your JavaScript client
// but were afraid to ask ... "Is" is the constructor function for "is" object,
// which has properties indicating:
// (1) browser vendor:
//     is.nav, is.ie, is.opera, is.hotjava, is.webtv, is.TVNavigator, is.AOLTV
// (2) browser version number:
//     is.major (integer indicating major version number: 2, 3, 4 ...)
//     is.minor (float   indicating full  version number: 2.02, 3.01, 4.04 ...)
// (3) browser vendor AND major version number
//     is.nav2, is.nav3, is.nav4, is.nav4up, is.nav6, is.nav6up, is.gecko, is.ie3, 
//     is.ie4, is.ie4up, is.ie5, is.ie5up, is.ie5_5, is.ie5_5up, is.ie6, is.ie6up, is.hotjava3, is.hotjava3up
// (4) JavaScript version number:
//     is.js (float indicating full JavaScript version number: 1, 1.1, 1.2 ...)
// (5) OS platform and version:
//     is.win, is.win16, is.win32, is.win31, is.win95, is.winnt, is.win98, is.winme, is.win2k
//     is.os2
//     is.mac, is.mac68k, is.macppc
//     is.unix
//     is.sun, is.sun4, is.sun5, is.suni86
//     is.irix, is.irix5, is.irix6
//     is.hpux, is.hpux9, is.hpux10
//     is.aix, is.aix1, is.aix2, is.aix3, is.aix4
//     is.linux, is.sco, is.unixware, is.mpras, is.reliant
//     is.dec, is.sinix, is.freebsd, is.bsd
//     is.vms
//
// See http://www.it97.de/JavaScript/JS_tutorial/bstat/navobj.html and
// http://www.it97.de/JavaScript/JS_tutorial/bstat/Browseraol.html
// for detailed lists of userAgent strings.
//
// Note: you don't want your Nav4 or IE4 code to "turn off" or
// stop working when Nav5 and IE5 (or later) are released, so
// in conditional code forks, use is.nav4up ("Nav4 or greater")
// and is.ie4up ("IE4 or greater") instead of is.nav4 or is.ie4
// to check version in code which you want to work on future
// versions.


function Is ()
{   // convert all characters to lowercase to simplify testing
    var agt=navigator.userAgent.toLowerCase();

    // *** BROWSER VERSION ***
    // Note: On IE5, these return 4, so use is.ie5up to detect IE5.

    this.major = parseInt(navigator.appVersion);
    this.minor = parseFloat(navigator.appVersion);

    // Note: Opera and WebTV spoof Navigator.  We do strict client detection.
    // If you want to allow spoofing, take out the tests for opera and webtv.
    this.nav  = ((agt.indexOf('mozilla')!=-1) && (agt.indexOf('spoofer')==-1)
                && (agt.indexOf('compatible') == -1) && (agt.indexOf('opera')==-1)
                && (agt.indexOf('webtv')==-1) && (agt.indexOf('hotjava')==-1));
    this.nav2 = (this.nav && (this.major == 2));
    this.nav3 = (this.nav && (this.major == 3));
    this.nav4 = (this.nav && (this.major == 4));
    this.nav4up = (this.nav && (this.major >= 4));
    this.navonly      = (this.nav && ((agt.indexOf(";nav") != -1) ||
                          (agt.indexOf("; nav") != -1)) );
    this.nav6 = (this.nav && (this.major == 5));
    this.nav6up = (this.nav && (this.major >= 5));
    this.gecko = (agt.indexOf('gecko') != -1);


    this.ie     = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
    this.ie3    = (this.ie && (this.major < 4));
    this.ie4    = (this.ie && (this.major == 4) && (agt.indexOf("msie 4")!=-1) );
    this.ie4up  = (this.ie  && (this.major >= 4));
    this.ie5    = (this.ie && (this.major == 4) && (agt.indexOf("msie 5.0")!=-1) );
    this.ie5_5  = (this.ie && (this.major == 4) && (agt.indexOf("msie 5.5") !=-1));
    this.ie5up  = (this.ie  && !this.ie3 && !this.ie4);
    this.ie5_5up =(this.ie && !this.ie3 && !this.ie4 && !this.ie5);
    this.ie6    = (this.ie && (this.major == 4) && (agt.indexOf("msie 6.")!=-1) );
    this.ie6up  = (this.ie  && !this.ie3 && !this.ie4 && !this.ie5 && !this.ie5_5);
    this.ie7under  = (this.ie && (this.ie3 || this.ie4 || this.ie5 || this.ie5_5 || this.ie6));

    // KNOWN BUG: On AOL4, returns false if IE3 is embedded browser
    // or if this is the first browser window opened.  Thus the
    // variables is.aol, is.aol3, and is.aol4 aren't 100% reliable.
    this.aol   = (agt.indexOf("aol") != -1);
    this.aol3  = (this.aol && this.ie3);
    this.aol4  = (this.aol && this.ie4);
    this.aol5  = (agt.indexOf("aol 5") != -1);
    this.aol6  = (agt.indexOf("aol 6") != -1);

    this.opera = (agt.indexOf("opera") != -1);
    this.opera2 = (agt.indexOf("opera 2") != -1 || agt.indexOf("opera/2") != -1);
    this.opera3 = (agt.indexOf("opera 3") != -1 || agt.indexOf("opera/3") != -1);
    this.opera4 = (agt.indexOf("opera 4") != -1 || agt.indexOf("opera/4") != -1);
    this.opera5 = (agt.indexOf("opera 5") != -1 || agt.indexOf("opera/5") != -1);
    this.opera5up = (this.opera && !this.opera2 && !this.opera3 && !this.opera4);

    this.firefox = (agt.indexOf("firefox") != -1);

    this.safari = (agt.indexOf("safari") != -1);

    this.chrome = (agt.indexOf("chrome") != -1);

    this.webtv = (agt.indexOf("webtv") != -1); 

    this.TVNavigator = ((agt.indexOf("navio") != -1) || (agt.indexOf("navio_aoltv") != -1)); 
    this.AOLTV = this.TVNavigator;

    this.hotjava = (agt.indexOf("hotjava") != -1);
    this.hotjava3 = (this.hotjava && (this.major == 3));
    this.hotjava3up = (this.hotjava && (this.major >= 3));

    // *** JAVASCRIPT VERSION CHECK ***
    if (this.nav2 || this.ie3) this.js = 1.0;
    else if (this.nav3) this.js = 1.1;
    else if (this.opera5up) this.js = 1.3;
    else if (this.opera) this.js = 1.1;
    else if ((this.nav4 && (this.minor <= 4.05)) || this.ie4) this.js = 1.2;
    else if ((this.nav4 && (this.minor > 4.05)) || this.ie5) this.js = 1.3;
    else if (this.hotjava3up) this.js = 1.4;
    else if (this.nav6 || this.gecko) this.js = 1.5;
    // NOTE: In the future, update this code when newer versions of JS
    // are released. For now, we try to provide some upward compatibility
    // so that future versions of Nav and IE will show they are at
    // *least* JS 1.x capable. Always check for JS version compatibility
    // with > or >=.
    else if (this.nav6up) this.js = 1.5;
    // note ie5up on mac is 1.4
    else if (this.ie5up) this.js = 1.3

    // HACK: no idea for other browsers; always check for JS version with > or >=
    else this.js = 0.0;

    // *** PLATFORM ***
    this.win   = ( (agt.indexOf("win")!=-1) || (agt.indexOf("16bit")!=-1) );
    // NOTE: On Opera 3.0, the userAgent string includes "Windows 95/NT4" on all
    //        Win32, so you can't distinguish between Win95 and WinNT.
    this.win95 = ((agt.indexOf("win95")!=-1) || (agt.indexOf("windows 95")!=-1));

    // is this a 16 bit compiled version?
    this.win16 = ((agt.indexOf("win16")!=-1) || 
               (agt.indexOf("16bit")!=-1) || (agt.indexOf("windows 3.1")!=-1) || 
               (agt.indexOf("windows 16-bit")!=-1) );  

    this.win31 = ((agt.indexOf("windows 3.1")!=-1) || (agt.indexOf("win16")!=-1) ||
                    (agt.indexOf("windows 16-bit")!=-1));

    // NOTE: Reliable detection of Win98 may not be possible. It appears that:
    //       - On Nav 4.x and before you'll get plain "Windows" in userAgent.
    //       - On Mercury client, the 32-bit version will return "Win98", but
    //         the 16-bit version running on Win98 will still return "Win95".
    this.win98 = ((agt.indexOf("win98")!=-1) || (agt.indexOf("windows 98")!=-1));
    this.winnt = ((agt.indexOf("winnt")!=-1) || (agt.indexOf("windows nt")!=-1));
    this.win32 = (this.win95 || this.winnt || this.win98 || 
                    ((this.major >= 4) && (navigator.platform == "Win32")) ||
                    (agt.indexOf("win32")!=-1) || (agt.indexOf("32bit")!=-1));

    this.winme = ((agt.indexOf("win 9x 4.90")!=-1));
    this.win2k = ((agt.indexOf("windows nt 5.0")!=-1));

    this.os2   = ((agt.indexOf("os/2")!=-1) || 
                    (navigator.appVersion.indexOf("OS/2")!=-1) ||   
                    (agt.indexOf("ibm-webexplorer")!=-1));

    this.mac    = (agt.indexOf("mac")!=-1);
    // hack ie5 js version for mac
    if (this.mac && this.ie5up) this.js = 1.4;
    this.mac68k = (this.mac && ((agt.indexOf("68k")!=-1) || 
                               (agt.indexOf("68000")!=-1)));
    this.macppc = (this.mac && ((agt.indexOf("ppc")!=-1) || 
                                (agt.indexOf("powerpc")!=-1)));

    this.sun   = (agt.indexOf("sunos")!=-1);
    this.sun4  = (agt.indexOf("sunos 4")!=-1);
    this.sun5  = (agt.indexOf("sunos 5")!=-1);
    this.suni86= (this.sun && (agt.indexOf("i86")!=-1));
    this.irix  = (agt.indexOf("irix") !=-1);    // SGI
    this.irix5 = (agt.indexOf("irix 5") !=-1);
    this.irix6 = ((agt.indexOf("irix 6") !=-1) || (agt.indexOf("irix6") !=-1));
    this.hpux  = (agt.indexOf("hp-ux")!=-1);
    this.hpux9 = (this.hpux && (agt.indexOf("09.")!=-1));
    this.hpux10= (this.hpux && (agt.indexOf("10.")!=-1));
    this.aix   = (agt.indexOf("aix") !=-1);      // IBM
    this.aix1  = (agt.indexOf("aix 1") !=-1);    
    this.aix2  = (agt.indexOf("aix 2") !=-1);    
    this.aix3  = (agt.indexOf("aix 3") !=-1);    
    this.aix4  = (agt.indexOf("aix 4") !=-1);    
    this.linux = (agt.indexOf("inux")!=-1);
    this.sco   = (agt.indexOf("sco")!=-1) || (agt.indexOf("unix_sv")!=-1);
    this.unixware = (agt.indexOf("unix_system_v")!=-1); 
    this.mpras    = (agt.indexOf("ncr")!=-1); 
    this.reliant  = (agt.indexOf("reliantunix")!=-1);
    this.dec   = ((agt.indexOf("dec")!=-1) || (agt.indexOf("osf1")!=-1) || 
                  (agt.indexOf("dec_alpha")!=-1) || (agt.indexOf("alphaserver")!=-1) || 
                  (agt.indexOf("ultrix")!=-1) || (agt.indexOf("alphastation")!=-1)); 
    this.sinix = (agt.indexOf("sinix")!=-1);
    this.freebsd = (agt.indexOf("freebsd")!=-1);
    this.bsd = (agt.indexOf("bsd")!=-1);
    this.unix  = ((agt.indexOf("x11")!=-1) || this.sun || this.irix || this.hpux || 
                 this.sco ||this.unixware || this.mpras || this.reliant || 
                 this.dec || this.sinix || this.aix || this.linux || this.bsd || this.freebsd);

    this.vms   = ((agt.indexOf("vax")!=-1) || (agt.indexOf("openvms")!=-1));
}

function validateTextLength(field, length){
	clearErrorElements();
	var fieldText = field.value;
	var fieldName = field.name;
	var isValidLength = true; 
	
	if (fieldText.length < length){
		isValidLength = false;
	}
	
	if (!isValidLength){
		if (fieldName.indexOf('LastName') > -1){
			showErrorMessage('The last name should contain at least ' + length + ' characters.', 'dataContent', fieldName, '1px solid #7f9db9' );
			field.focus();
			return false;
		}
	}
	
	return true;
}

var is;
var isIE3Mac = false;
// this section is designed specifically for IE3 for the Mac

if ((navigator.appVersion.indexOf("Mac")!=-1) && (navigator.userAgent.indexOf("MSIE")!=-1) && 
(parseInt(navigator.appVersion)==3))
       isIE3Mac = true;
else   is = new Is(); 

/* End of code from Ultimate client-side Javascript client sniff, version 3.03 */
var browserVersionText = navigator.appVersion.split("MSIE")
var browserVersion = parseFloat(browserVersionText[1])
var mouseX;
var mouseY;
var errorElements = new Array();
var _eventListener = null;
var _formActionAfterCancel = null;
var _submittedForm = null;
var _disabledFormElements = new Array();
var _hiddenElements = new Array();
var numberOfAdImages = 8;
var isDragEventRegistered = false;

var searchingImage = new Image();
searchingImage.src = _webLoc + '/shared/images/core/searching.gif';

var adImage = new Image();
adImage.src = _webLoc + '/shared/images/banners and ads/208x91tripprotection.jpg';

var closeImage = new Image();
closeImage.src = _webLoc + '/shared/images/core/buttons/close.gif';

function MessageBoxRequest() {
	this.MESSAGE_TYPE_ERROR = 1;
	this.MESSAGE_TYPE_WARNING = 2;
	this.MESSAGE_TYPE_MESSAGE = 3;
	this.message = '';
	this.messageType = 1;
	this.errorElementNames = null;
	this.errorElementOriginalBorders = null;
	this.fadingElementName = null;
	this.fadingFactor = 100;
	this.uid = '';
	this.modalFrame = true;
}

function AsynchronousMultiRequestItem(url, queryString, paramArray, target, callbackFunctionName, callbackFunctionParams, trackingText, postCallbackScript) {
	/* Url to invoke */
	this.url = url;
	
	/* Parameter Key-Value list passed as a query string */
	this.queryString = queryString;
	
	/* Parameter Key-Value list passed as an array */
	this.paramArray = paramArray;
	
	/* Name of the target Div or Frame*/
	this.target = target;
	
	/* Callback function name */
	this.callbackFunctionName = callbackFunctionName;
		
	this.trackingText = trackingText;
	
	/*stores Javascript parameters that need to be passed to the callbackFunction*/  
	this.callbackFunctionParams = callbackFunctionParams;
	
	/* Script to be executed after callback function is called. 
	   "eval" of this script would be done 
	*/	
	this.postCallbackScript = postCallbackScript;
}

function showErrorMessage(message, fadingElementName, errorElementNames, originalBorders) {
	var messageBoxRequest = new MessageBoxRequest();
	messageBoxRequest.message = message;
	messageBoxRequest.fadingElementName = fadingElementName;
	messageBoxRequest.errorElementNames = errorElementNames;
	messageBoxRequest.errorElementOriginalBorders = originalBorders;

	displayMessageBox(messageBoxRequest);
}

function showWarningMessage(message, fadingElementName) {
	var messageBoxRequest = new MessageBoxRequest();
	messageBoxRequest.message = message;
	messageBoxRequest.messageType = messageBoxRequest.MESSAGE_TYPE_WARNING;
	messageBoxRequest.fadingElementName = fadingElementName;

	displayMessageBox(messageBoxRequest);
}

function showGeneralMessage(message, fadingElementName) {
	var messageBoxRequest = new MessageBoxRequest();
	messageBoxRequest.message = message;
	messageBoxRequest.messageType = messageBoxRequest.MESSAGE_TYPE_MESSAGE;
	messageBoxRequest.fadingElementName = fadingElementName;
	
	displayMessageBox(messageBoxRequest);
}

function showMessage(message, errorCode, fadingBlock) {
	if(message) {
		if(errorCode && errorCode != '') {
			showErrorMessage(message, fadingBlock);
			return true;
		}
		else {
			showGeneralMessage(message, fadingBlock);
			return true;
		}
	}
	return false;
}

function displayMessageBox(messageBoxRequest) {
	var messageBoxDiv = document.getElementById('_messageBoxDiv'); 
	var uid = UID();
	messageBoxRequest.uid = uid;

	if(!messageBoxDiv) {
 		messageBoxDiv = createPopupDiv('_messageBoxDiv', 0, 0, 300, 300, false, false);
		
		var div = document.createElement('DIV')
		div.className = 'h25';
		messageBoxDiv.insertBefore(div, null);
		
		var titleDiv = document.createElement('DIV')
		titleDiv.id = '_messageBoxTitle';
		titleDiv.className = 'fll p05';
		div.insertBefore(titleDiv, null);
		
		var closeDiv = document.createElement('DIV')
		closeDiv.className = 'flr p05';
		div.insertBefore(closeDiv, null);
		
		var anchor = document.createElement('A');
		anchor.id = '_messageBoxClose';
		anchor.href = 'javascript:;';
		closeDiv.insertBefore(anchor, null);
		
		var image = closeImage;
		image.alt = 'Close Button';
		anchor.insertBefore(image, null);
		
		var br = document.createElement('BR');
		div.insertBefore(br, null);
		
		var paragraph = document.createElement('P');
		paragraph.id = '_messageBoxText';
		messageBoxDiv.insertBefore(paragraph, null);		
	}
	
	if(messageBoxDiv) {
		messageBoxDiv.style.position = "absolute";
		messageBoxDiv.style.width = "300";
		messageBoxDiv.uid = uid;
		messageBoxDiv.verticalAlign = "middle";
		
		var messageBoxTitle = document.getElementById('_messageBoxTitle'); 
		var messageBoxClose = document.getElementById('_messageBoxClose'); 
		var messageBoxText = document.getElementById('_messageBoxText'); 
		
		var closeFunction = function() {
			hideMessageBox(messageBoxRequest.uid, messageBoxRequest.fadingElementName);
		};
		
		if(isIE()) {
			messageBoxClose.attachEvent("onclick", closeFunction);
			messageBoxText.innerHTML = messageBoxRequest.message;
		}
		else {
			messageBoxClose.addEventListener("click", closeFunction, true);
			messageBoxText.innerHTML = messageBoxRequest.message;
		}
				
		if(messageBoxRequest.messageType == messageBoxRequest.MESSAGE_TYPE_ERROR) {
			messageBoxDiv.className = 'errorMsg';
		}
		else if(messageBoxRequest.messageType == messageBoxRequest.MESSAGE_TYPE_WARNING) {
			messageBoxDiv.className = 'warningMsg';
			messageBoxTitle.innerText = 'Warning';
			messageBoxTitle.textContent = 'Warning';
		}
		else if(messageBoxRequest.messageType == messageBoxRequest.MESSAGE_TYPE_MESSAGE) {
			messageBoxDiv.className = 'generalMsg';
			messageBoxTitle.innerText = '';
			messageBoxTitle.textContent = '';
		}
				 
		messageBoxDiv.style.visibility = "visible";
		messageBoxDiv.style.display = "block";
		messageBoxDiv.style.zIndex = "300";

		if(messageBoxRequest.errorElementNames) {
			var errorElementNameArray = messageBoxRequest.errorElementNames.split(",");
			var errorElementOriginalBorderArray = null;
			if(messageBoxRequest.errorElementOriginalBorders) {
				errorElementOriginalBorderArray = messageBoxRequest.errorElementOriginalBorders.split(",");
			}
			if(errorElements) {
				for(var index = 0; index < errorElementNameArray.length; ++index) {
					var errorElementName = trim(errorElementNameArray[index]);
					var errorElement = document.getElementById(errorElementName);
					if(errorElement && messageBoxRequest.messageType == messageBoxRequest.MESSAGE_TYPE_ERROR) {
						var errorElementOriginalBorder = errorElement.style.border;
						if(errorElementOriginalBorderArray) {
							if(errorElementOriginalBorderArray.length > index) {
								errorElementOriginalBorder = trim(errorElementOriginalBorderArray[index]);
							}
						}
						errorElements.push({errorElementName:errorElementName, 
											borderStyle:errorElementOriginalBorder
											});
						errorElement.style.border = "2px double #FE4747";
					}
				}
			}
		}
		
		positionBlockCentrally('_messageBoxDiv');
		
		if(messageBoxRequest.fadingElementName) {
			fadeElement(messageBoxRequest.fadingElementName, messageBoxRequest.fadingFactor, messageBoxRequest.modalFrame);
		}
		
		//If the browser version is IE 6 or below, we have to hide the select boxes, because select boxes take the highest z-index and would
		//always display above the div
		if(is.ie7under) {
			var tagsToHide = new Array("select");
			hideElements(true, tagsToHide, '_messageBoxDiv');
		}
		//setTimeout("hideMessageBox('" + messageBoxRequest.uid + "','" + messageBoxRequest.fadingElementName + "')", 20000);
	}
}

function hideMessageBox(uid, fadingElementName) {
	var messageBoxDiv = document.getElementById('_messageBoxDiv'); 
	if(messageBoxDiv && (messageBoxDiv.uid == uid)) {
		messageBoxDiv.style.visibility = "hidden"; 
		messageBoxDiv.style.display = "none"; 
		messageBoxDiv.uid = "";
		
		if(fadingElementName) {
			clearFading(fadingElementName, false);
		}
	} 

	//If the browser version is IE 6 or below, we have to show the hidden select boxes
	if(is.ie7under) {
		var tagsToShow = new Array("select");
		hideElements(false, tagsToShow, '_messageBoxDiv');
	}
}

function clearErrorElements() {
	if(errorElements) {
		while(errorElements.length > 0) {
			var errorElementInfo = errorElements.pop();
			if(errorElementInfo) {
				var errorElementName = errorElementInfo.errorElementName;
				if(errorElementName) {
					var errorElement = document.getElementById(errorElementName);
					if(errorElement) {
						errorElement.style.border = errorElementInfo.borderStyle;						
					}
				}
			}
		}
	}
}

function isChildOf(childElement, parentElement){
 while(childElement && parentElement) {
 	childElement = childElement.parentNode;
 	if(childElement == parentElement) {
 		return true;
 	}
 }
 return false;
}
function hideElements(hidden, tags, blockName) {
	if(!blockName) {
		blockName = "_global";
	}
	
	if(arguments[0] == null) {
		hidden = true;
	}
	
	if(!tags) {
		tags = new Array("applet", "iframe", "select");
	}
		
	if(hidden) {
		var hiddenElementsForBlock = _hiddenElements[blockName];
		if(!hiddenElementsForBlock) {
			hiddenElementsForBlock = new Array();
		}
		for(var k = tags.length; k > 0;) {
			var elements = document.getElementsByTagName(tags[--k]);
			var previousElement = null;
			for(var i = elements.length; i > 0;){
				previousElement = elements[--i];
				var block = document.getElementById(blockName);				
				if(!isChildOf(previousElement, block)) {
					previousElement.style.visibility = "hidden";
					hiddenElementsForBlock[previousElement.id] = "1";
				}				
			}
		}
		
		_hiddenElements[blockName] = hiddenElementsForBlock;
	}
	else {
		var hiddenElementsForBlock = _hiddenElements[blockName];
		if(hiddenElementsForBlock) {
			for(var hiddenElementId in hiddenElementsForBlock) {
				var hiddenElement = document.getElementById(hiddenElementId);
				if(hiddenElement && !isElementHidden(hiddenElementId, blockName)) {
					hiddenElement.style.visibility = "visible";
				}
			}
		}
		_hiddenElements[blockName] = null;
	}
}

function isElementHidden(elementName, exceptByBlockName) {
	for(var blockName in _hiddenElements) {
		var hiddenElementsForBlock = _hiddenElements[blockName];
		if(hiddenElementsForBlock && hiddenElementsForBlock[elementName]) {
			if(!exceptByBlockName || blockName != exceptByBlockName){
				return true;
			}	
		}
	}
	
	return false;
}

function SplashScreenRequest() {
	this.splashScreenText = 'Loading...Please Wait...';
	this.showStopButton = false;
	this.formActionAfterCancel = '';
}

function changeAdImage(image) {
	if(image) {
		var randomNumber = Math.ceil(numberOfAdImages * Math.random());
		image.src = _webLoc + '/shared/images/core/bannersAndAds/waitingAd_' + randomNumber + '.jpg';
		image.alt = 'Banner';
	}
}

function displaySearchingPopup(splashScreenRequest) {
	var searchingPopupDiv = document.getElementById('_searchingPopupDiv');
	if(!searchingPopupDiv) {
		searchingPopupDiv = createPopupDiv('_searchingPopupDiv', 0, 0, -1, 700, false, false, 'popupDivSmall tac');
		searchingPopupDiv.style.padding = '25px 10px 10px 10px';	
		
		var div = document.createElement('DIV');
		div.className = 'popupBanner';
		searchingPopupDiv.insertBefore(div, null);
		
		var innerAdImage = new Image();				
		innerAdImage.id = '_adImage';
		innerAdImage.style.width = '208';
		innerAdImage.style.height= '91';
		changeAdImage(innerAdImage);
		innerAdImage.style.display = '';
		div.insertBefore(innerAdImage, null);
		
		var splashScreenTextDiv = document.createElement('DIV');
		splashScreenTextDiv.id = '_splashScreenTextDiv';
		splashScreenTextDiv.className = "pt45 fs10";
		splashScreenTextDiv.innerText = splashScreenRequest.splashScreenText;
		splashScreenTextDiv.textContent = splashScreenRequest.splashScreenText;
		searchingPopupDiv.insertBefore(splashScreenTextDiv, null);
		
		var loadingImageDiv = document.createElement('DIV');
		loadingImageDiv.id = 'loadingDivContainer';
		loadingImageDiv.className = 'pt15 pb15';
		searchingPopupDiv.insertBefore(loadingImageDiv, null);
		
		var innerSearchingImage = searchingImage;
		innerSearchingImage.id = '_searchingImage';
		innerSearchingImage.alt = 'Searching...';
		innerSearchingImage.style.width = '168';
		innerSearchingImage.style.height= '16';
		innerSearchingImage.style.display = '';
		loadingImageDiv.insertBefore(innerSearchingImage, null);
		
		var flashvars = false;
		var params = {
			wmode: "transparent",
			menu: "false"
		};		
		var atts = {
			id: "loadingDivContainer"
		};
		
    	swfobject.embedSWF(_sharedLoc + "/swf/searching.swf", "loadingDivContainer", "168", "16", "6.0.0.0", "", flashvars, params, atts);
		//document.body.insertBefore(searchingPopupDiv, document.body.firstChild);
		//addPopupDivToDocument(searchingPopupDiv);
	}
	if(searchingPopupDiv) {
		var splashScreenTextDiv = document.getElementById('_splashScreenTextDiv');
		splashScreenTextDiv.innerText = splashScreenRequest.splashScreenText;
		splashScreenTextDiv.textContent = splashScreenRequest.splashScreenText;
		
		searchingPopupDiv.style.visibility = 'visible';
		searchingPopupDiv.style.display = '';
		searchingPopupDiv.style.zIndex = '700';
			
		//var scrollTop = document.body.scrollTop;
		//var clientHeight = document.body.clientHeight;

		//var scrollLeft = document.body.scrollLeft;
		//var clientWidth = document.body.clientWidth;
	
		//renderingY = scrollTop + (clientHeight - searchingPopupDiv.offsetHeight) / 2;
		//renderingX = scrollLeft + (clientWidth - searchingPopupDiv.offsetWidth) / 2;

		//searchingPopupDiv.style.left = renderingX;
		//searchingPopupDiv.style.top = renderingY;
		
		positionBlockCentrally('_searchingPopupDiv');
		 
		//If the browser version is IE 6 or below, we have to hide the select boxes, because select boxes take the highest z-index and would
		//always display above the div
		if(is.ie7under) {
			var tagsToHide = new Array("select");
			hideElements(true, tagsToHide, '_searchingPopupDiv');
		}
	}
}

function hideSearchingPopup() {
	var searchingPopupDiv = document.getElementById('_searchingPopupDiv'); 
	if(searchingPopupDiv != null) { 
		searchingPopupDiv.style.visibility = "hidden"; 
		searchingPopupDiv.style.display = "none";		
		changeAdImage(document.getElementById('_adImage'));

		//If the browser version is IE 6 or below, we have to show the hidden select boxes
		if(is.ie7under) {
			var tagsToShow = new Array("select");
			hideElements(false, tagsToShow, '_searchingPopupDiv');
		}
	} 
}

function hideShowCovered(element){
	var tags=new Array("applet", "iframe", "select", "img");
	var p=getAbsolutePos(element);
	var EX1=p.x;
	var EX2=element.offsetWidth+EX1;
	var EY1=p.y;
	var EY2=element.offsetHeight+EY1;
	for(var k=tags.length;k>0;){
		var ar=document.getElementsByTagName(tags[--k]);
		var cc=null;
		for(var i=ar.length;i>0;){
			cc=ar[--i];
			p=getAbsolutePos(cc);
			var CX1=p.x;
			var CX2=cc.offsetWidth+CX1;
			var CY1=p.y;
			var CY2=cc.offsetHeight+CY1;
			if((CX1>EX2)||(CX2<EX1)||(CY1>EY2)||(CY2<EY1)){
				cc.style.visibility="visible";
			}
			else{
				cc.style.visibility="hidden";
			}
		}
	}
};

function disableFormElements(shouldDisable) {
	forms = document.forms;
	if(forms != null) {
		for(var i=0; i<forms.length; ++i) {
			form = forms[i];
			formElements = form.elements;
			for(element=0; element<formElements.length; element++){
				if(shouldDisable && formElements[element].disabled == true) {
					_disabledFormElements.push(formElements[element]);
				}
								
				formElements[element].disabled = shouldDisable;
			}		
		}
	}
	if(!shouldDisable) {
		for(var i=0; i<_disabledFormElements.length; ++i) {
			_disabledFormElements[i].disabled = true;
		}
	}	
	
	hideElements(shouldDisable);
	
	document.body.style.overflow = shouldDisable? 'hidden': 'scroll';	
}

function getAbsolutePos(element){
	var pos = {x:element.offsetLeft, y:element.offsetTop};
	
	if(element.offsetParent){
		var parentPos = getAbsolutePos(element.offsetParent);
		pos.x += parentPos.x;
		pos.y += parentPos.y;		
	}
	
	if(element != document.body && element != document.documentElement) {
		pos.x -= element.scrollLeft;
		pos.y -= element.scrollTop;
	}
	
	return pos;
}

function getPosRelativeToPage(element) {
	var pos1 = getAbsolutePos(element);
	var popupDivContainer = document.getElementById("popupDivContainer");
	var pos2 = getAbsolutePos(popupDivContainer);
	pos1.x = pos1.x - pos2.x;
	pos1.y = pos1.y - pos2.y;
	return pos1;
}

function getPageRect() {
	var popupDivContainer = document.getElementById("popupDivContainer");
	var popupContainerPos = getAbsolutePos(popupDivContainer);
	//var screenWidth = popupDivContainer.clientWidth - document.body.scrollLeft;
	
	var pageLeft = 0;
	var pageWidth = popupDivContainer.clientWidth;
	var scrollLeft = document.body.scrollLeft;	
	if( scrollLeft > 0 && (scrollLeft + document.body.clientWidth < pageWidth)) {
		pageLeft = scrollLeft;
		pageWidth = document.body.clientWidth;
	}else if(scrollLeft > 0 && (scrollLeft + document.body.clientWidth >= pageWidth)) {
		pageLeft = scrollLeft;
		pageWidth = pageWidth - scrollLeft;
	}else if(scrollLeft == 0 && (document.body.clientWidth - popupContainerPos.x < pageWidth)) {
		pageWidth = document.body.clientWidth - popupContainerPos.x;
	}
	
	var pageTop = 0;
	var pageHeight = popupDivContainer.clientHeight;
	var scrollTop = document.body.scrollTop;
	if( scrollTop > 0 && (scrollTop + document.body.clientHeight < pageHeight)) {
		pageTop = scrollTop;
		pageHeight = document.body.clientHeight;
	}else if(scrollTop > 0 && (scrollTop + document.body.clientHeight >= pageHeight)) {
		pageTop = scrollTop;
		pageHeight = pageHeight - scrollTop;
	}else if(scrollTop == 0 && (document.body.clientHeight - popupContainerPos.y < pageHeight)) {
		pageHeight = document.body.clientHeight - popupContainerPos.y;
	}
	
	//if(pageHeight > popupDivContainer.clientHeight) {
	//	pageHeight = popupDivContainer.clientHeight;
	//}
	//popupDivContainer.clientHeight - document.body.scrollTop;	
	var result = {x:pageLeft, y:pageTop, width:pageWidth, height:pageHeight};
	return result; 
}

function getAbsoluteLeft(objectId) {
	// Get an object left position from the upper left viewport corner
	// Tested with relative and nested objects
	o = document.getElementById(objectId)
	oLeft = o.offsetLeft            // Get left position from the parent object
	while(o.offsetParent!=null) {   // Parse the parent hierarchy up to the document element
		oParent = o.offsetParent    // Get parent object reference
		oLeft += oParent.offsetLeft // Add parent left position
		o = oParent
	}
	// Return left postion
	return oLeft
}

function getAbsoluteTop(objectId) {
	// Get an object top position from the upper left viewport corner
	// Tested with relative and nested objects
	o = document.getElementById(objectId)
	oTop = o.offsetTop            // Get top position from the parent object
	while(o.offsetParent!=null) { // Parse the parent hierarchy up to the document element
		oParent = o.offsetParent  // Get parent object reference
		oTop += oParent.offsetTop // Add parent top position
		o = oParent
	}
	// Return top position
	return oTop
}

function UID() {
	var time = new Date().getTime();
	return "" + time + "_" + (Math.random() * 999);
}

function fixPNG(myImage) {
    if( ( browserVersion >= 5.5 ) && ( browserVersion < 7 ) && ( document.body.filters ) ) {
       var imgID = (myImage.id) ? "id='" + myImage.id + "' " : ""
	   var imgClass = (myImage.className) ? "class='" + myImage.className + "' " : ""
	   var imgTitle = (myImage.title) ? 
		             "title='" + myImage.title  + "' " : "title='" + myImage.alt + "' "
	   var imgStyle = "display:inline-block;" + myImage.style.cssText
	   var strNewHTML = "<span " + imgID + imgClass + imgTitle
                  + " style=\"" + "width:" + myImage.width 
                  + "px; height:" + myImage.height 
                  + "px;" + imgStyle + ";"
                  + "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader"
                  + "(src=\'" + myImage.src + "\', sizingMethod='scale');\"></span>"
	   myImage.outerHTML = strNewHTML	  
    }
}

function expandCollaspeDiv(expandCollapseImageName, expandCollapseDivName, expandCollapseIcons) {	
	var expandCollapseDiv = document.getElementById(expandCollapseDivName) ;
	var expandCollapseImage = document.getElementById(expandCollapseImageName) ;
	
	if(expandCollapseImage) {
		var currentImageSource = expandCollapseImage.src;		
		var currentImageFileName = currentImageSource.substring(currentImageSource.lastIndexOf('/') + 1);
		var newImageSource;
		
		if(expandCollapseIcons) {
			for(var iconCounter = 0; iconCounter < expandCollapseIcons.length; ++iconCounter) {
				var iconFileName = expandCollapseIcons[iconCounter].substring(expandCollapseIcons[iconCounter].lastIndexOf('/') + 1);
				if(iconFileName != currentImageFileName) {
					newImageSource = expandCollapseIcons[iconCounter];
				}
			}
		}
		
		expandCollapseImage.src = newImageSource;
	}
	
	if(expandCollapseDiv) {
		(expandCollapseDiv.style.display == 'none') ? expandCollapseDiv.style.display = 'block' : expandCollapseDiv.style.display = 'none';
	}
}

function showBlock(elementName) {
	var element = document.getElementById(elementName);
	if(element) {
		element.style.display = 'block';
		element.style.visibility = 'visible';	
		//If the browser version is IE 6 or below, we have to hide the select boxes, because select boxes take the highest z-index and would
		//always display above the div
		if(is.ie7under) {
			var tagsToHide = new Array("select");
			hideElements(true, tagsToHide, elementName);
		}
	}
}

function isBlockVisible(elementName){
	var element = document.getElementById(elementName);
	if(element) {
		return element.style.display == 'block';
	}
}

function hideBlock(elementName) {
	var element = document.getElementById(elementName);
	if(element) {
		element.style.display = 'none';

		//If the browser version is IE 6 or below, we have to show the hidden select boxes
		if(is.ie7under) {
			var tagsToShow = new Array("select");
			hideElements(false, tagsToShow, elementName);
		}
	}
}

function positionBlockCentrally(elementName) {
	var element = document.getElementById(elementName);
	if(element) {
		var scrollTop = document.body.scrollTop;
		var clientHeight = document.body.clientHeight;

		var scrollLeft = document.body.scrollLeft;
		var clientWidth = document.body.clientWidth;
	
		var elementHeight = element.offsetHeight;
		try {
			elementHeight = (elementHeight == 0) ? parseInt(element.style.height) : elementHeight;
		}
		catch(e) {
		}
		
		var elementWidth = element.offsetWidth;
		try {
			elementWidth = (elementWidth == 0) ? parseInt(element.style.width) : elementWidth;
		}
		catch(e) {
		}
		
		var renderingY = scrollTop + (clientHeight - elementHeight) / 2;
		var renderingX = scrollLeft + (clientWidth - elementWidth) / 2;

		var popupDivContainer = document.getElementById("popupDivContainer");
		var popupDivContainerPos = getAbsolutePos(popupDivContainer);
		
		element.style.left = renderingX - popupDivContainerPos.x;
		element.style.top = renderingY - popupDivContainerPos.y;
	}	
}

function fadeElement(fadingElementName, fadingFactor, disable) {
	if(!fadingFactor) {
		fadingFactor = 30;
	}
	var fadingElement = document.getElementById(fadingElementName);
	if(fadingElement) {
		fadingElement.style.filter = 'alpha(opacity=' + fadingFactor + ')';
		fadingElement.style.opacity = '' + (fadingFactor / 100);
		fadingElement.style.MozOpacity = '' + (fadingFactor / 100);
	}
	
	if(disable != null) {
		disableElement(fadingElementName, disable);
	}
}

function disableElement(elementName, disable) {
	if(disable == null) {
		disable = true;
	}
	var coveringDiv = document.getElementById('_' + elementName + '_coveringDiv');
	if(disable) { 
		if(!coveringDiv) {
			coveringDiv = createPopupDiv('_' + elementName + '_coveringDiv', 0, 0, 0, 0, false, false, "");
		}
	}
		
	if(coveringDiv) {
		
		var baseElement = document.getElementById(elementName); 
		if(baseElement) {
			if(disable) {
				var baseElementHeight = baseElement.offsetHeight;
				try {
					baseElementHeight = (baseElementHeight == 0) ? parseInt(baseElement.style.height) : baseElementHeight;
				}
				catch(e) {
				}
				
				var baseElementWidth = baseElement.offsetWidth;
				try {
					baseElementWidth = (baseElementWidth == 0) ? parseInt(baseElement.style.width) : baseElementWidth;
				}
				catch(e) {
				}								

				coveringDiv.style.width = baseElementWidth;
				coveringDiv.style.height = baseElementHeight;
				var baseElementPos = getPosRelativeToPage(baseElement);
				coveringDiv.style.background = "#000000";
				coveringDiv.style.left = baseElementPos.x;
				coveringDiv.style.top = baseElementPos.y;
				coveringDiv.style.display = "block";
				coveringDiv.style.visibility = "visible";
				coveringDiv.style.zIndex = (baseElement.style.zIndex) ? (parseInt(baseElement.style.zIndex) + 1) : 199;
				fadeElement('_' + elementName + '_coveringDiv');
			}
			else {
				coveringDiv.style.visibility = "hidden";
				coveringDiv.style.display = "none";
				clearFading('_' + elementName + '_coveringDiv');
			}
		}		
	}	
}

function clearFading(fadingElementName, disable) {
	var fadingElement = document.getElementById(fadingElementName);
	if(fadingElement) {
		fadingElement.style.filter = '';
		fadingElement.style.opacity = '';
		fadingElement.style.MozOpacity = '';
	}
	
	if(disable != null) {
		disableElement(fadingElementName, disable);
	}
}

function removeElement( elementName ) {
	var element = document.getElementById( elementName );
	if( element ) {
		element.parentNode.removeChild(element);
		//document.body.removeChild( element );
	}
}

function setDragEvent( divId, event, divHeaderHeight ) {
	if( !isDragEventRegistered ) {
		if( isIE() ) {
			event = window.event;
		}
		var element = document.getElementById( divId );
		if( isNull( divHeaderHeight ) ) {
			divHeaderHeight = 40;
		}
		var elementAbsLoc = getAbsolutePos( element );
		var ptop  = elementAbsLoc.y;
		//var ptop  = element.offsetTop;
		getMouseXY( event );
		if( ( mouseY >= ptop ) && ( mouseY <= ( ptop + divHeaderHeight ) ) ) {
			element.style.cursor = 'move';
			document.onmousedown = function( event ) { initializeDragEvent( divId, event ); };
			document.onmouseup = function( event ) { removeDragEvent( divId, event, false ); };
			element.onmouseout = function( event ) { removeDragEvent( divId, event, true ); };
			stopEvent( event );
		} else {
			element.style.cursor = '';
			document.onmousedown = null;
			document.onmouseup = null;
		}
		element.onmousemove = function( event ) { setDragEvent( divId, event, divHeaderHeight ) };
	}
}

function initializeDragEvent( divId, event ) {
	var element = document.getElementById( divId );
	var elementRelLoc = getPosRelativeToPage(element);
	var elementAbsLoc = getAbsolutePos(element);
	//var pleft = document.getElementById( divId ).offsetLeft;
	//var ptop = document.getElementById( divId ).offsetTop;
	var pleft = elementRelLoc.x;
	var ptop = elementRelLoc.y;
	var aleft = elementAbsLoc.x;
	var atop = elementAbsLoc.y;
	var isIEBrowser = false;
	if( isIE() ) {
		isIEBrowser = true;
		event = window.event;
	}
	getMouseXY( event );
	var xcoor = mouseX;
	var ycoor = mouseY;
	
	_eventListener = function( event ) { dragElement( event, divId, aleft, atop, pleft, ptop, xcoor, ycoor ); };
	if( isIEBrowser ) {
		document.attachEvent( "onmousemove", _eventListener );
	} else {
		document.addEventListener( "mousemove", _eventListener, true );
	}
	element.onmouseout = null;
	isDragEventRegistered = true;
	element.onmousemove = null;
	document.onmousedown = null;
}

function removeDragEvent( divId, event, isMouseOut ) {
	var element = document.getElementById( divId );
	if( !( isMouseOut && isDragEventRegistered ) ) {
		if( isIE() ) {
			document.detachEvent( "onmousemove", _eventListener );
		} else {
	  		document.removeEventListener( "mousemove", _eventListener, true );
		}
		document.onmousedown = null;
		document.onmouseup = null;
		isDragEventRegistered = false;
	}
}
	
function dragElement( event, divId, aleft, atop, pleft, ptop, xcoor, ycoor ) {
	if( isIE() ) {
		event = window.event;
		if( event.button == 1 ) {
			getMouseXY( event );
		} else {
			removeDragEvent( divId, event, false );
			return;
		}
	} else {
		getMouseXY( event );
	}
	var xpos = pleft + ( mouseX - xcoor );
	var ypos = ptop + (mouseY - ycoor);
	var absXPos = aleft +  ( mouseX - xcoor );
	var absYPos = atop + (mouseY - ycoor);
	if( ( absXPos ) > 0 && ( ( document.getElementById( divId ).offsetWidth + xpos ) < document.body.offsetWidth ) && 
		( absYPos ) > 0 && ( ( document.getElementById( divId ).offsetHeight + ypos ) < document.body.scrollHeight ) ) {  
		document.getElementById( divId ).style.left = xpos;
		document.getElementById( divId ).style.top = ypos;
	} else if( ( absXPos ) > 0 && ( ( document.getElementById( divId ).offsetWidth + xpos ) > document.body.offsetWidth ) && 
	    ( absYPos ) > 0 && ( ( document.getElementById( divId ).offsetHeight + ypos ) < document.body.scrollHeight ) ) {
		document.getElementById( divId ).style.left = ( document.body.offsetWidth ) - ( document.getElementById( divId ).offsetWidth );
		document.getElementById( divId ).style.top = ypos;
	} else if( ( absXPos ) < 0 && ( absYPos ) > 0 && ( ( document.getElementById( divId ).offsetHeight + ypos ) < document.body.scrollHeight ) ) {
		document.getElementById( divId ).style.left = -( aleft - pleft );
		document.getElementById( divId ).style.top = ypos;
	}
}

function getMouseXY( event ) {
	if( isIE() ) {
		event = window.event;
		mouseX = event.clientX + document.body.scrollLeft;
		mouseY = event.clientY + document.body.scrollTop;
	} else {
		mouseX = event.pageX;
		mouseY = event.pageY;
	}
	stopEvent( event );
}

function stopEvent( event ) {
	if( isIE() ) {
		window.event.cancelBubble = true;
		window.event.returnValue = false;
	} else {
		event.stopPropagation();
		if( !is.opera ) {
			event.preventDefault();			
		}
		if( window.getSelection ) {
			var selectionObject = window.getSelection();
			if( selectionObject && selectionObject.removeAllRanges ) {
				selectionObject.removeAllRanges() ; 
			}
		}
	}
}

function showSuggestionBox(event, elementName, suggestions, styleSheetClass, alertMessage ) {
	if(!event) {
		event = window.event;
	}	
	var element = document.getElementById(elementName);
	if(element) {	
		var elementPos = getPosRelativeToPage(element);
		var suggestionBox = document.getElementById("_suggestionBox");
		if(!suggestionBox) {
			//suggestionBox = document.createElement('DIV');
			//suggestionBox.id = '_suggestionBox';
			//document.body.insertBefore(suggestionBox, document.body.firstChild);
			//addPopupDivToDocument(suggestionBox);			
			suggestionBox = createPopupDiv('_suggestionBox', 0, 0, 0, 300, false, false, "");		
		}
		//var elementPos = getAbsolutePos(element);
		if(suggestionBox) {
			suggestionBox.style.position = "absolute";
			suggestionBox.style.left = elementPos.x;
			suggestionBox.style.top = elementPos.y + element.offsetHeight;
			suggestionBox.style.width = element.offsetWidth;			
			suggestionBox.style.visibility = "visible";
			suggestionBox.style.display = "block";
			suggestionBox.style.zIndex = "300";		
			suggestionBox.innerHTML = "";
			var isSuggestions = false;
			if(suggestions) {
				var selectString = "<select id='_suggestionBoxSelect' multiple='true' " + 
										"onKeyDown='_suggestionBoxOnKeyDown(event, \"" + elementName + "\")' " + 
										"onChange='_suggestionBoxOnChange(\"" + elementName + "\")' " + 
										"onClick='_suggestionBoxOnClick(\"" + elementName + "\")' >";
										
				for(var index in suggestions ) {
					if( index.toString() != "toJSONString" ) {
						if(suggestions[index] != null ) {
							selectString += "<option value='" + index + "'>" + suggestions[index] + "</option>";
							isSuggestions = true;
						}
					} 
				}
				selectString += "</select>";
				
				//when no suggesions found set blank value to the assigned hidden fields and displayed messageg.
				if( !isSuggestions ){
					selectString = "<div class='fs11 p05 bgc05' align='left' border='1'>" + alertMessage + "</div>";
					clearHiddenFieldValuesWhenNoSuggesionsFound( elementName );			
				}
				
				suggestionBox.innerHTML = selectString;
			}
		
			var suggestionBoxSelect = document.getElementById("_suggestionBoxSelect");
			if(suggestionBoxSelect) {
				suggestionBoxSelect.style.height = suggestionBox.style.height;
				suggestionBoxSelect.className = styleSheetClass;
			}
			
			if( event && event.keyCode == 40 ) {
				_suggestionBoxTargetOnKeyDown(elementName);
			}
						
			if(isIE()) {
				document.attachEvent("onmousedown", _documentOnClick);				
			}
			else {
				document.addEventListener("mouseup", _documentOnClick, true);				
			}	
				
		}		
	}	
}

function hideSuggestionBox() {
	hideBlock("_suggestionBox");
}

function _suggestionBoxTargetOnKeyDown(elementName) {
	var suggestionBoxSelect = document.getElementById("_suggestionBoxSelect");
	if(suggestionBoxSelect && suggestionBoxSelect.length >= 1 ) {
		suggestionBoxSelect[0].selected = true;
		suggestionBoxSelect.focus();
		_suggestionBoxOnChange(elementName);
		return true;
	}	
}

function _suggestionBoxOnChange(elementName) {
	var element = document.getElementById(elementName);
	var suggestionBoxSelect = document.getElementById("_suggestionBoxSelect");
	if(element) {
		if(suggestionBoxSelect && suggestionBoxSelect.selectedIndex>=0) {
			var selectedText = suggestionBoxSelect[suggestionBoxSelect.selectedIndex].text;
			var selectedValue = suggestionBoxSelect[suggestionBoxSelect.selectedIndex].value;
			_setSuggestionToParentElement(element, selectedValue, selectedText);
		} 
	}
}

function _suggestionBoxOnClick(elementName) {
	_suggestionBoxOnChange(elementName);
	
	hideSuggestionBox();
}

function _suggestionBoxOnKeyDown(event, elementName) {
	if( event && event.keyCode == 13 ) {
		_suggestionBoxOnChange(elementName);
		_suggestionBoxOnClick();
	}	
}

function _setSuggestionToParentElement(parentElement, selectedKey, selectedValue) {
	if(parentElement) {
		parentElement.value = selectedValue;
		setSuggestionBoxSelectOptionValue( parentElement );
	}
}

function _documentOnClick(event) {
	if(!event) {
		event = window.event;
	}
	
	var targetElement = event.srcElement ? event.srcElement : event.target;
	if(!targetElement || !targetElement.id || targetElement.id.indexOf("_suggestionBox") != 0) {
		hideSuggestionBox();
	}
}

function computeDifferenceBetweenDates( fromDate, toDate ) {
	fromDate.setHours( 0 );
	fromDate.setMinutes( 0 );
	fromDate.setSeconds( 0 );
	fromDate.setMilliseconds( 0 );
	toDate.setHours( 0 );
	toDate.setMinutes( 0 );
	toDate.setSeconds( 0 );
	toDate.setMilliseconds( 0 );
	var milliSecondsInOneDay = 1000 * 60 * 60 * 24;
	return Math.round( ( toDate.getTime() - fromDate.getTime() ) / milliSecondsInOneDay );
}

function addDays(date, days){
	var newDate = new Date();
	newDate.setTime(date.getTime());
	newDate.setDate(date.getDate() + days);
	return newDate;
}

function showText(element, text) {
	if(element.value == '') {
		element.value = text;
	}
}

function clearText(element, text) {
	if(element.value == text) {
		element.value = '';
	}
}

function scrollWindowTop(divName) {
	if(divName && (document.getElementById(divName))) {
		document.getElementById(divName).scrollTop = 0;
	} else {
		window.scroll (0,0);
	}
}

function setFocus(element){
	if (element.value != ''){
		element.select();
	}
}

function getCheckedValue(radioObj) {
	if(!radioObj)
		return "";
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
			return radioObj.value;
		else
			return "";
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
			return radioObj[i].value;
		}
	}
	return "";
}

function createPopupDiv(divName, left, top, width, zIndex, isVisible, isDraggable,  className) {
	var popupDiv = document.getElementById(divName);
	if(!popupDiv){
		popupDiv = document.createElement('DIV');
		popupDiv.id = divName;
		if(isVisible){ 
			popupDiv.style.visibility = "visible";		
			popupDiv.style.display = "block";
		}else {
			popupDiv.style.visibility = "hidden";		
			popupDiv.style.display = "none";
		}
		popupDiv.style.position = "absolute";
		popupDiv.style.left = left;
		popupDiv.style.top = top;			 		
		if(width>=0) {
			popupDiv.style.width = width;
		}
		if(zIndex){
			popupDiv.style.zIndex = zIndex;
		}else {
			popupDiv.style.zIndex = "300";
		}	
		if(className || className=="") {
			popupDiv.className = className;
		}else {
			popupDiv.className="tal popupDivBig";
		}	
		popupDiv.innerHTML = '';
		if(isDraggable) {
			popupDiv.onmouseover = function( event ) { setDragEvent(divName, event ) };
		}
		var popupDivContainer = document.getElementById("popupDivContainer");	
		popupDivContainer.appendChild(popupDiv);
		
	}
	return popupDiv;
}

function loadBackgroundGradations() {
	//If the browser version is IE 6 or below, we have to hide the gradation on both the sides of the page
	if(is.ie7under) {
		document.getElementById("bgShadowLeft").className="bg-shadow-left-ie6";
		document.getElementById("bgShadowRight").className="bg-shadow-right-ie6";
	} else {
		document.getElementById("bgShadowLeft").className="bg-shadow-left";
		document.getElementById("bgShadowRight").className="bg-shadow-right";
	}
}

function showHideTooltip(srcElementId, toolTipId, event) {
	if(!event) {
		event = window.event;
	}
	
	var element = event.srcElement ? event.srcElement : event.target;
	with(document.getElementById(toolTipId)) {
		with(style) {
			if(event.type == "mouseout" || event.type == "blur") {
			      display = "none";
			} 
			else {
				display = "inline";
				var srcElement = document.getElementById(srcElementId);
				var relPos = getPosRelativeToPage(srcElement);
				//left = getAbsoluteLeft(srcElementId);
				//top = getAbsoluteTop(srcElementId) + 20;
				left = relPos.x;
				top = relPos.y + 20;
			}
		}
	}
}

function hasClassName(objElement, strClass) {
   if ( objElement.className ) {
      var arrList = objElement.className.split(' ');
      var strClassUpper = strClass.toUpperCase();
      for ( var i = 0; i < arrList.length; i++ ) {
    	  if ( arrList[i].toUpperCase() == strClassUpper ) {
    		  return true;
    	  }
      }
   }
   return false;
}

function modifyClassName(objElement, classExpression) {
	if ( objElement && objElement.className != undefined && classExpression) {	
		var arrList1 = classExpression.split(' ');
		var arrList2 = objElement.className.split(' ');
		
		var classNameAddList = [];
		var classNameRemoveList = [];
		
		for(var i=0; i< arrList1.length; i++) {
			var classPart1 = arrList1[i];
			var sign = classPart1.charAt(0);
			if(sign =='+') {
				var className = classPart1.substring(1);
				classNameAddList.push(className);
			}else if(sign == '-') {
				var className = classPart1.substring(1);
				classNameRemoveList.push(className);
			}
		}
		
		var classMap = [];
		for(var i=0; i< arrList2.length; i++) {
			classMap[arrList2[i]] = true;
		}
		
		for(var i=0; i< classNameAddList.length; i++) {
			classMap[classNameAddList[i]] = true;
		}
		
		for(var i=0; i< classNameRemoveList.length; i++) {
			classMap[classNameRemoveList[i]] = false;
		}
		
		var newClassArray = [];
		
		for(var key in classMap) {
			if(classMap.hasOwnProperty(key)) {
				if(classMap[key] == true) {
					newClassArray.push(key);
				}
			}
		}
		objElement.className = newClassArray.join(' ');
	}
}

function decodeHTML( encodedString ) {
	encodedString = encodedString.replace( /&lt;/g, '<' );
	encodedString = encodedString.replace( /&gt;/g, '>' );
	encodedString = encodedString.replace( /##34##/g, '\"' );  // replace ##34## with "
    encodedString = encodedString.replace( /##39##/g, '\'' );  // replace ##39## with '
    encodedString = encodedString.replace( /##60##/g, '<' );   // replace ##60## with <
    encodedString = encodedString.replace( /##62##/g, '>' );   // replace ##62## with >
    encodedString = encodedString.replace( /##33##/g, '!' );   // replace ##33## with !
    encodedString = encodedString.replace( /##37##/g, '%' );   // replace ##37## with %
    encodedString = encodedString.replace( /##58##/g, ':' );   // replace ##58##; with :
    encodedString = encodedString.replace( /##61##/g, '=' );   // replace ##61##; with =
    encodedString = encodedString.replace( /##145##/g, '`' );  // replace ##145##; with `
    encodedString = encodedString.replace( /##63##/g, '?' );   // replace ##63##; with ?
    encodedString = encodedString.replace( /##125##/g, '}' );  // replace ##125##; with }
    encodedString = encodedString.replace( /##123##/g, '{' );  // replace ##123##; with {
    encodedString = encodedString.replace( /##91##/g, '[' );  // replace ##91##; with [
    encodedString = encodedString.replace( /##93##/g, ']' );  // replace ##93##; with ]
    encodedString = encodedString.replace( /##40##/g, '(' );  // replace ##40##; with (
    encodedString = encodedString.replace( /##41##/g, ')' );  // replace ##41##; with )
    encodedString = encodedString.replace( /##42##/g, '\r' );  // replace ##42##; with \r
    encodedString = encodedString.replace( /##92##/g, '\\' );  // replace ##42##; with \
    encodedString = encodedString.replace( /##36##/g, '$' );  // replace ##36##; with $
    encodedString = encodedString.replace( /##38##/g, '\n' );  // replace ##38##; with \n
    encodedString = encodedString.replace( /##35##/g, '\&' );  // replace ##38##; with \&
	return encodedString;
}

function replaceOptions ( listName, optionsJSON, preservationType ) {
	var options = optionsJSON.parseJSON ();
	var list = document.getElementById ( listName );
	if ( list ) {
		var selectedOptions = {};
		if ( preservationType == 1 ) {
			var selIndex = list.selectedIndex;
			if ( selIndex > - 1 ) {
				selectedOptions [ "_" + list.options [ selIndex ].value ] = true;
			}
		} else if ( preservationType == 2 ) {
			for ( var i = 0; i < list.options.length; i++ ) {
				if ( list.options [ i ].selected ) {
					selectedOptions [ "_" + list.options [ i ].value ] = true;
				}
			}
		}
		list.length = 0;
		for ( var i = 0; i < options.length; i++ ) {
			var newOpt = new Option ( decodeHTML ( options [ i ].text ) , options [ i ].value );
			if ( ( options [ i ].selected == true ) || ( preservationType > 0 && selectedOptions [ "_" + options [ i ].value ] ) ) {
				newOpt.selected = true;
			}
			list.options [ i ] = newOpt;
		}
	}	
}

function loadImage(imageId, imageUrl) {
	var image = document.getElementById(imageId);
	
	if(image) {
		image.src = imageUrl;
	}
}
function trim(string) {
	if(string.length < 1) {
		return"";
	}
	string = rTrim(string);
	string = lTrim(string);

	if(string == "") {
		return "";
	} 
	else {
		return string;
	}
}

function rTrim(string){
	var spaceChar = String.fromCharCode(32);
	var tabChar = String.fromCharCode(9);
	var length = string.length;
	var strTemp = "";

	if(length < 1){
		return "";
	}
	
	var iTemp = length -1;
	while(iTemp > -1){
		if(string.charAt(iTemp) == spaceChar ||
			string.charAt(iTemp) == tabChar) {
		}
		else {
			strTemp = string.substring(0, iTemp +1);
			break;
		}
		iTemp = iTemp-1;
	}
	
	return strTemp;
}

function lTrim(string){
	var spaceChar = String.fromCharCode(32);
	var tabChar = String.fromCharCode(9);
	var length = string.length;
	var strTemp = "";
	
	if(length < 1){
		return "";
	}
	
	var iTemp = 0;
	while(iTemp < length){
		if(string.charAt(iTemp) == spaceChar ||
			string.charAt(iTemp) == tabChar) {
		}
		else {
			strTemp = string.substring(iTemp, length);
			break;
		}
		iTemp = iTemp + 1;
	}
	
	return strTemp;
}

function formatCurrency( currency ) {
	currency = currency.toString().replace( /$|\,/g,'' );
	var amount = parseFloat( currency );
	var sign = ( amount == ( amount = Math.abs( amount ) ) );
	amount = Math.floor( amount * 100 + 0.50000000001 );
	var cents = amount % 100;
	var formattedCentsValue = cents.toString();
	amount = Math.floor( amount / 100 ).toString();
	if( cents < 10 )
		formattedCentsValue = "0" + formattedCentsValue;
	for( var i = 0; i < Math.floor( ( amount.length - ( 1 + i ) ) / 3 ); i++ ) {
		amount = amount.substring( 0, amount.length - ( 4 * i + 3 ) ) + ',' + amount.substring( amount.length - ( 4 * i + 3 ) );
	}
	return ( ( ( sign ) ? '' : '-' ) + '$' + amount + '.' + formattedCentsValue );
}

function uppercase(object){
	object.value = object.value.toUpperCase();
}

function formatDecimal(object, numDecimals) {
    if(object) {
    	if( object.value != "" ){
        	object.value = parseFloat(object.value).toFixed(numDecimals);
    	}               
    }   
}/*
    json.js
    2007-08-19

    Public Domain

    This file adds these methods to JavaScript:

        array.toJSONString(whitelist)
        boolean.toJSONString()
        date.toJSONString()
        number.toJSONString()
        object.toJSONString(whitelist)
        string.toJSONString()
            These methods produce a JSON text from a JavaScript value.
            It must not contain any cyclical references. Illegal values
            will be excluded.

            The default conversion for dates is to an ISO string. You can
            add a toJSONString method to any date object to get a different
            representation.

            The object and array methods can take an optional whitelist
            argument. A whitelist is an array of strings. If it is provided,
            keys in objects not found in the whitelist are excluded.

        string.parseJSON(filter)
            This method parses a JSON text to produce an object or
            array. It can throw a SyntaxError exception.

            The optional filter parameter is a function which can filter and
            transform the results. It receives each of the keys and values, and
            its return value is used instead of the original value. If it
            returns what it received, then structure is not modified. If it
            returns undefined then the member is deleted.

            Example:

            // Parse the text. If a key contains the string 'date' then
            // convert the value to a date.

            myData = text.parseJSON(function (key, value) {
                return key.indexOf('date') >= 0 ? new Date(value) : value;
            });

    It is expected that these methods will formally become part of the
    JavaScript Programming Language in the Fourth Edition of the
    ECMAScript standard in 2008.

    This file will break programs with improper for..in loops. See
    http://yuiblog.com/blog/2006/09/26/for-in-intrigue/

    This is a reference implementation. You are free to copy, modify, or
    redistribute.

    Use your own copy. It is extremely unwise to load untrusted third party
    code into your pages.
*/

/*jslint evil: true */

// Augment the basic prototypes if they have not already been augmented.

if (!Object.prototype.toJSONString) {

    Array.prototype.toJSONString = function (w) {
        var a = [],     // The array holding the partial texts.
            i,          // Loop counter.
            l = this.length,
            v;          // The value to be stringified.

// For each value in this array...

        for (i = 0; i < l; i += 1) {
            v = this[i];
            switch (typeof v) {
            case 'object':

// Serialize a JavaScript object value. Ignore objects thats lack the
// toJSONString method. Due to a specification error in ECMAScript,
// typeof null is 'object', so watch out for that case.

                if (v) {
                    if (typeof v.toJSONString === 'function') {
                        a.push(v.toJSONString(w));
                    }
                } else {
                    a.push('null');
                }
                break;

            case 'string':
            case 'number':
            case 'boolean':
                a.push(v.toJSONString());

// Values without a JSON representation are ignored.

            }
        }

// Join all of the member texts together and wrap them in brackets.

        return '[' + a.join(',') + ']';
    };


    Boolean.prototype.toJSONString = function () {
        return String(this);
    };


    Date.prototype.toJSONString = function () {

// Eventually, this method will be based on the date.toISOString method.

        function f(n) {

// Format integers to have at least two digits.

            return n < 10 ? '0' + n : n;
        }

        return '"' + this.getUTCFullYear() + '-' +
                f(this.getUTCMonth() + 1)  + '-' +
                f(this.getUTCDate())       + 'T' +
                f(this.getUTCHours())      + ':' +
                f(this.getUTCMinutes())    + ':' +
                f(this.getUTCSeconds())    + 'Z"';
    };


    Number.prototype.toJSONString = function () {

// JSON numbers must be finite. Encode non-finite numbers as null.

        return isFinite(this) ? String(this) : 'null';
    };


    Object.prototype.toJSONString = function (w) {
        var a = [],     // The array holding the partial texts.
            k,          // The current key.
            i,          // The loop counter.
            v;          // The current value.

// If a whitelist (array of keys) is provided, use it assemble the components
// of the object.

        if (w) {
            for (i = 0; i < w.length; i += 1) {
                k = w[i];
                if (typeof k === 'string') {
                    v = this[k];
                    switch (typeof v) {
                    case 'object':

// Serialize a JavaScript object value. Ignore objects that lack the
// toJSONString method. Due to a specification error in ECMAScript,
// typeof null is 'object', so watch out for that case.

                        if (v) {
                            if (typeof v.toJSONString === 'function') {
                                a.push(k.toJSONString() + ':' +
                                       v.toJSONString(w));
                            }
                        } else {
                            a.push(k.toJSONString() + ':null');
                        }
                        break;

                    case 'string':
                    case 'number':
                    case 'boolean':
                        a.push(k.toJSONString() + ':' + v.toJSONString());

// Values without a JSON representation are ignored.

                    }
                }
            }
        } else {

// Iterate through all of the keys in the object, ignoring the proto chain
// and keys that are not strings.

            for (k in this) {
                if (typeof k === 'string' &&
                        Object.prototype.hasOwnProperty.apply(this, [k])) {
                    v = this[k];
                    switch (typeof v) {
                    case 'object':

// Serialize a JavaScript object value. Ignore objects that lack the
// toJSONString method. Due to a specification error in ECMAScript,
// typeof null is 'object', so watch out for that case.

                        if (v) {
                            if (typeof v.toJSONString === 'function') {
                                a.push(k.toJSONString() + ':' +
                                       v.toJSONString());
                            }
                        } else {
                            a.push(k.toJSONString() + ':null');
                        }
                        break;

                    case 'string':
                    case 'number':
                    case 'boolean':
                        a.push(k.toJSONString() + ':' + v.toJSONString());

// Values without a JSON representation are ignored.

                    }
                }
            }
        }

// Join all of the member texts together and wrap them in braces.

        return '{' + a.join(',') + '}';
    };


    (function (s) {

// Augment String.prototype. We do this in an immediate anonymous function to
// avoid defining global variables.

// m is a table of character substitutions.

        var m = {
            '\b': '\\b',
            '\t': '\\t',
            '\n': '\\n',
            '\f': '\\f',
            '\r': '\\r',
            '"' : '\\"',
            '\\': '\\\\'
        };


        s.parseJSON = function (filter) {
            var j;

            function walk(k, v) {
                var i;
                if (v && typeof v === 'object') {
                    for (i in v) {
                        if (Object.prototype.hasOwnProperty.apply(v, [i])) {
                            v[i] = walk(i, v[i]);
                        }
                    }
                }
                return filter(k, v);
            }


// Parsing happens in three stages. In the first stage, we run the text against
// a regular expression which looks for non-JSON characters. We are especially
// concerned with '()' and 'new' because they can cause invocation, and '='
// because it can cause mutation. But just to be safe, we will reject all
// unexpected characters.

// We split the first stage into 3 regexp operations in order to work around
// crippling deficiencies in Safari's regexp engine. First we replace all
// backslash pairs with '@' (a non-JSON character). Second we delete all of
// the string literals. Third, we look to see if only JSON characters
// remain. If so, then the text is safe for eval.

            if (/^[,:{}\[\]0-9.\-+Eaeflnr-u \n\r\t]*$/.test(this.
                    replace(/\\./g, '@').
                    replace(/"[^"\\\n\r]*"/g, ''))) {

// In the second stage we use the eval function to compile the text into a
// JavaScript structure. The '{' operator is subject to a syntactic ambiguity
// in JavaScript: it can begin a block or an object literal. We wrap the text
// in parens to eliminate the ambiguity.

                j = eval('(' + this + ')');

// In the optional third stage, we recursively walk the new structure, passing
// each name/value pair to a filter function for possible transformation.

                return typeof filter === 'function' ? walk('', j) : j;
            }

// If the text is not JSON parseable, then a SyntaxError is thrown.

            throw new SyntaxError('parseJSON');
        };


        s.toJSONString = function () {

// If the string contains no control characters, no quote characters, and no
// backslash characters, then we can simply slap some quotes around it.
// Otherwise we must also replace the offending characters with safe
// sequences.

            if (/["\\\x00-\x1f]/.test(this)) {
                return '"' + this.replace(/[\x00-\x1f\\"]/g, function (a) {
                    var c = m[a];
                    if (c) {
                        return c;
                    }
                    c = a.charCodeAt();
                    return '\\u00' +
                        Math.floor(c / 16).toString(16) +
                        (c % 16).toString(16);
                }) + '"';
            }
            return '"' + this + '"';
        };
    })(String.prototype);
}function ScriptBlock() {
	this.isSrc = false;
	this.text = '';
	this.scriptContainerText = '';
	this.position = -1;
}

function AsynchronousRequest() {
	
	/* Url to invoke */
	this.url = '';
	
	/* Parameter Key-Value list passed as an array */
	this.paramArray = '';
	
	/* Parameter Key-Value list passed as a query string */
	this.queryString = '';
	
	/* Name of the target Div or Frame*/
	this.target = '';
	
	/* If the target is frame, set this to true. Else, the target is assumed to be Div */
	this.isTargetFrame = false;

	/* Used to specify if Ajax or Hidden Frame mode of communication has to be used
		true = Ajax mode
		false = Hidden Frame Mode
	*/
	this.useAjax = true;
	
	/* If Hidden Frame mode is used, then supply the form object */
	this.form = null;
	
	/* Callback function name */
	this.callbackFunctionName = '';
	
	/* Script to be executed after callback function is called. 
		"eval" of this script would be done 
	*/
	this.postCallbackScript = null;
	
	/* Request object to be used to display Splash Screen */
	this.splashScreenRequest = null;
	
	/* Splash Screen display function to be invoked */
	this.splashScreenDisplayFunctionName = null;
	
	/* Splash Screen hide function to be invoked */
	this.splashScreenHideFunctionName = null;
	
	/* Deprecated. DO NOT USE */
	this.formName = '';
	
	/*stores Javascript parameters that need to be passed to the callbackFunction*/  
	this.callbackFunctionParams = null;
	
}

function CallbackObject(responseText, callbackFunctionName, callbackFunctionAdditionalParams) {
	this.responseText = responseText;
	this.pageContent = false;
	this.callbackFunctionParams = [];
	if(callbackFunctionName) {
		eval("this.callbackFunction = " + callbackFunctionName );
	}
	
	var errorCodeStartIndex = responseText.indexOf("_errorCode=");
	if(errorCodeStartIndex >=0) {
		var errorCodeStopIndex = responseText.indexOf(":", errorCodeStartIndex);
		var errorCodeLength = parseInt(responseText.substring(errorCodeStartIndex + 11, errorCodeStopIndex));
		var errorCode = parseInt(responseText.substr(errorCodeStopIndex + 1, errorCodeLength));
		this.errorCode = errorCode;						
	}
	
	var errorMessageStartIndex = responseText.indexOf("_errorMessage=");
	if(errorMessageStartIndex >=0) {
		var errorMessageStopIndex = responseText.indexOf(":", errorMessageStartIndex);
		var errorMessageLength = parseInt(responseText.substring(errorMessageStartIndex + 14, errorMessageStopIndex));
		var errorMessage = responseText.substr(errorMessageStopIndex + 1, errorMessageLength);
		this.errorMessage = errorMessage;						
	}
	
	var callbackFunctionParamsStartIndex = responseText.indexOf("_callbackFunctionParams=");  
	if(callbackFunctionParamsStartIndex != -1) {
		var callbackFunctionParams = eval("[" + responseText.substring(callbackFunctionParamsStartIndex + 24) + "]");
		this.callbackFunctionParams = callbackFunctionParams;
	}
	else {
		this.pageContent = true;
	}
	
	if(callbackFunctionAdditionalParams && callbackFunctionAdditionalParams.length > 0) {
		for(var i =0; i< callbackFunctionAdditionalParams.length; i++) {
			this.callbackFunctionParams.push(callbackFunctionAdditionalParams[i]);
		}
	}	
}

CallbackObject.prototype.hasError = function() {
	return (this.errorMessage ? true : false);	
}

CallbackObject.prototype.isPageContent = function() {
	return this.pageContent;
}

CallbackObject.prototype.applyCallback = function() {
	try {
		this.callbackFunction.apply(this, this.callbackFunctionParams);
	}
	catch(exception) {
	}	
}

function submitWithoutReload(asynchronousRequest) {
	
	showWaitingDiv = (asynchronousRequest.splashScreenRequest != null);
	
	if(showWaitingDiv) {
		if(asynchronousRequest.splashScreenDisplayFunctionName) {
			eval(asynchronousRequest.splashScreenDisplayFunctionName + "(asynchronousRequest.splashScreenRequest)");
		}
		else {
			displayWaitingDiv(asynchronousRequest.splashScreenRequest);
		}
	}
	else {
		_showWaitCursor();
	}

	if(asynchronousRequest.useAjax) {
       	var httpRequest = _getHttpRequest();
       	if (httpRequest) {
       		var queryString = "";
       		
       		if(asynchronousRequest.queryString != "") {
       			queryString = asynchronousRequest.queryString;
       		}
       		
       		if(asynchronousRequest.paramArray != null) {
		 		for (i=0; i<asynchronousRequest.paramArray.length; i++)
				{		
					if(queryString != "") {
						queryString += "&";
					}
					queryString += asynchronousRequest.paramArray[i][0] + "=" + asynchronousRequest.paramArray[i][1];
				}
			}
			       		
       		httpRequest.onreadystatechange = function() { _callbackAjax(httpRequest, asynchronousRequest); };
    	   	httpRequest.open('POST', asynchronousRequest.url, true);
    	   	httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
       		httpRequest.send(queryString);
       	}
	}
	else {
		if(asynchronousRequest.form) {
			_submitAsynchronousForm(asynchronousRequest);
		}
	}
		
	if(showWaitingDiv == true) {
		if(!asynchronousRequest.splashScreenDisplayFunctionName) {
			disableFormElements(true);
		}
	}	
}

function openUrlWithoutReload(asynchronousRequest) {
	showWaitingDiv = (asynchronousRequest.splashScreenRequest != null);
	
	if(showWaitingDiv) {
		if(asynchronousRequest.splashScreenDisplayFunctionName) {
			eval(asynchronousRequest.splashScreenDisplayFunctionName + "(asynchronousRequest.splashScreenRequest)");
		}
		else {
			displayWaitingDiv(asynchronousRequest.splashScreenRequest);
		}
	}
	else {
		_showWaitCursor();
	}

   	var httpRequest = _getHttpRequest();
   	if (httpRequest) {
	   	httpRequest.onreadystatechange = function() { _showUrlContents(httpRequest, asynchronousRequest ); };
	   	httpRequest.open('POST', asynchronousRequest.url, true);

		queryString = asynchronousRequest.queryString;
		
		if(asynchronousRequest.paramArray != null) {
			for (i=0; i<asynchronousRequest.paramArray.length; i++)
			{		
				if(queryString != "") {
					queryString += "&";
				}
				queryString += asynchronousRequest.paramArray[i][0] + "=" + asynchronousRequest.paramArray[i][1];
			}
		}

    	httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	   	httpRequest.send(queryString);
	}
}

function openScriptUrlWithoutReload(asynchronousRequest) {

	var scriptBlock = document.createElement('SCRIPT'); 
    scriptBlock.type = 'text/javascript'; 
    scriptBlock.src = asynchronousRequest.url; 

	var destinationBlock = document.getElementById(asynchronousRequest.target);
	if(destinationBlock != null && destinationBlock != 'undefined') {
		destinationBlock.appendChild(scriptBlock); 
	}
	else {
		document.body.appendChild(scriptBlock);
	}
}

function _submitAsynchronousForm(asynchronousRequest) {
	var innerDiv = document.createElement('Div');
	var innerFrameId = asynchronousRequest.form.name + "_InnerFrame";
	innerDiv.innerHTML = '<iframe id="' + innerFrameId + '" name="' + innerFrameId + '" width="0" height="0" frameborder="0" src="about:blank" style="display:none" onLoad="_frameLoaded(\'' + innerFrameId + '\')"></iframe>';
	document.body.appendChild(innerDiv);

	var innerFrame = document.getElementById(innerFrameId);
	if(innerFrame) {
		innerFrame.asynchronousRequest = asynchronousRequest;
	}
	
	asynchronousRequest.form.setAttribute('target', innerFrameId);
	asynchronousRequest.form.submit();
}

function _frameLoaded(innerFrameId) {
	var innerFrame = document.getElementById(innerFrameId);
	if(innerFrame) {
		var doc;
		if(innerFrame.contentDocument) {
		    doc = innerFrame.contentDocument;
		} 
		else if(innerFrame.contentWindow) {
		    doc = innerFrame.contentWindow.document;
		} 
		else {
		    doc = window.frames[innerFrameId].document;
		}
		
		if(doc.location.href == "about:blank") {
		    return;
		}
		
		var callbackFunctionParamsStartIndex = doc.body.innerHTML.indexOf("_callbackFunctionParams=");  
		var asynchronousRequest = innerFrame.asynchronousRequest;
		var callbackFunctionName = asynchronousRequest.callbackFunctionName;
		var postCallbackScript = asynchronousRequest.postCallbackScript;
		
		if(callbackFunctionParamsStartIndex == 0) {
			if(callbackFunctionName && callbackFunctionName != "") {
				callbackFunctionName = callbackFunctionName + "(";
				callbackFunctionName += doc.body.innerHTML.substring(24) + ")";
				eval(callbackFunctionName);
				
				if(postCallbackScript && (postCallbackScript != '')) {
					eval(postCallbackScript);
				}
			}
		}
		else {
			var httpRequest = new Object();
			httpRequest.readyState = 4;
			httpRequest.status = 200;
			httpRequest.responseText = doc.body.innerHTML;

			_showUrlContents(httpRequest, asynchronousRequest);
		}
	}
}

function _removeChildren(element) {
	while(element.lastChild) {
		element.removeChild(element.lastChild);
	}
}

function _getMethod(methodSignature)
{
	var method = null;
	
	try {
		method = eval(methodSignature);
	}
	catch (ex) {
	}

	return method;
}

function _callbackAsynchronousRequest(formName, showWaitingDiv) {
	if(showWaitingDiv != undefined && showWaitingDiv != null && showWaitingDiv == true) {
		hideWaitingDiv();
		disableFormElements(false);
	}
	_hideWaitCursor();
	var callbackFunction = _getMethod("callback_" + formName);
	if (callbackFunction != null)
	{
		var params = "";
		for (var i=2; i<arguments.length; i++)
		{
			if (i > 2) params += ", ";
			params += "arguments[" + i + "]";
		}
		
		//Invoke the callback function with parameters returned from the server
		eval("callbackFunction(" + params + ");");
	}
}

function _submitWithoutReload(callbackFunctionName, url, paramArray, useAjax, showWaitingDiv, resultBlockName, isFrame) {
	asynchronousRequest = new AsynchronousRequest();
	asynchronousRequest.callbackFunctionName = callbackFunctionName;
	asynchronousRequest.url = url;
	asynchronousRequest.paramArray = paramArray;
	asynchronousRequest.useAjax = useAjax;
	
	if(showWaitingDiv) {
		asynchronousRequest.splashScreenRequest = new SplashScreenRequest();
	}
	
	asynchronousRequest.target = resultBlockName;
	asynchronousRequest.isTargetFrame = isFrame;
	
	submitWithoutReload(asynchronousRequest);
}

function _callbackAjax(httpRequest, asynchronousRequest) {
   	if (httpRequest.readyState == 4) {
		if(asynchronousRequest.splashScreenRequest != null) {			
			if(asynchronousRequest.splashScreenHideFunctionName) {
				eval(asynchronousRequest.splashScreenHideFunctionName + "(asynchronousRequest.splashScreenRequest)");
			}
			else {
				hideWaitingDiv();
				disableFormElements(false);
			}
			
			asynchronousRequest.splashScreenRequest = null;
		}
		_hideWaitCursor();
       	if (httpRequest.status == 200) {
       		var callbackObject = new CallbackObject(httpRequest.responseText, asynchronousRequest.callbackFunctionName, asynchronousRequest.callbackFunctionParams);
       		if(!callbackObject.isPageContent()) {
       			//If the callback object doesn't have page content, it means that we only have to call the callback function with the parameters coming back from the 
       			//server invocation.
       			callbackObject.applyCallback();
       		}
       		else {
       			//If the callback object has a page content, then populate the page content into the target block.
       			_showUrlContents(httpRequest, asynchronousRequest);
       		}
       	} 
       	else {
           	//alert('There was a problem with the request.');
       	}
   	}
}

function _getHttpRequest() {
   	var httpRequest = false;
   	if (window.XMLHttpRequest) { // Mozilla, Safari,...
       	httpRequest = new XMLHttpRequest();
       	if (httpRequest.overrideMimeType) {
           	httpRequest.overrideMimeType('text/xml');
       	}
   	} 
   	else if (window.ActiveXObject) { // IE
       	try {
           	httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
       	} catch (e) {
           	try {
               	httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
           	} catch (e) {}
       	}
   	}
   	if (!httpRequest) {
       	alert('Cannot create an XMLHTTP instance');
       	return false;
   	}
   	return httpRequest;
}

function _showWaitCursor() {
	document.body.style.cursor = 'wait';
}

function _hideWaitCursor() {
	document.body.style.cursor = 'auto';
}

function _openUrlWithoutReload(url, queryString, resultBlockName, isFrame, showWaitingDiv, callbackFunctionName ) {
	asynchronousRequest = new AsynchronousRequest();
	asynchronousRequest.callbackFunctionName = callbackFunctionName;
	asynchronousRequest.url = url;
	
	if(showWaitingDiv) {
		asynchronousRequest.splashScreenRequest = new SplashScreenRequest();
	}
	
	asynchronousRequest.queryString = queryString;
	asynchronousRequest.target = resultBlockName;
	asynchronousRequest.isTargetFrame = isFrame;
	
	openUrlWithoutReload(asynchronousRequest);
}

function _showUrlContents(httpRequest, asynchronousRequest) {
   	if (httpRequest.readyState == 4) {
		if(asynchronousRequest.splashScreenRequest != null) {
			if(asynchronousRequest.splashScreenHideFunctionName) {
				eval(asynchronousRequest.splashScreenHideFunctionName + "(asynchronousRequest.splashScreenRequest)");
			}
			else {
				hideWaitingDiv();
				disableFormElements(false);
			}
		}
		_hideWaitCursor();

       	if (httpRequest.status == 200) {
       		var responseText = httpRequest.responseText;
       		
			
       		var callbackFunctionName = "";			
			if( asynchronousRequest.callbackFunctionName != null && asynchronousRequest.callbackFunctionName != "" ) {
				callbackFunctionName = asynchronousRequest.callbackFunctionName;
			}
			else if( asynchronousRequest.formName != null && asynchronousRequest.formName != "" ) {
				callbackFunctionName = "callback_" + asynchronousRequest.formName;
			}
			
			var callbackObject = new CallbackObject(responseText, callbackFunctionName, asynchronousRequest.callbackFunctionParams);
			
			if(callbackObject.isPageContent() && !callbackObject.hasError()) {
				//Target Frame or Div is populated with the page content only if there were no callback errors
				if(asynchronousRequest.isTargetFrame) {
					document.frames(asynchronousRequest.target).document.write(responseText);
					document.frames(asynchronousRequest.target).document.close();
				}
				else if(asynchronousRequest.target && asynchronousRequest.target != '') {
					//Is Div				
					_populateDiv(responseText, asynchronousRequest.target);
				}
			}
			
			//Invoke the callback function, if there was one defined
			callbackObject.applyCallback();
			
			//Invoke the post callback script, if there was one defined
			postCallbackScript = asynchronousRequest.postCallbackScript;
			if(postCallbackScript && (postCallbackScript != '')) {
				eval(postCallbackScript);
			}
       	} 
       	else {
           	//alert('There was a problem with the request.');
           	if(asynchronousRequest.isTargetFrame) {
				document.frames(asynchronousRequest.target).document.write(httpRequest.responseText);
				document.frames(asynchronousRequest.target).document.close();
			}			
       	}
   	}
}

function _populateDiv(responseText, divName) {
	var reContent = /(<script\b[\s\S]*?>([\s\S]*?)<\/script\b[\s]*?>)/ig;
	var reSrc = /(<script\b[^>]*?src[\s]*=[\s]*[\u0022\u0027]?([^\u0022\u0027]*)[\u0022\u0027]?[^>]*>[\s\S]*?<\/script\b[\s]*?>)/ig;
	var match;
	var scriptTexts = new Array();
	var scriptBlocks = new Array();
	
	while (match = reSrc.exec(responseText)) {
		var scriptBlock = new ScriptBlock();
		scriptBlock.isSrc = true;
		scriptBlock.text = match[2];
		scriptBlock.scriptContainerText = match[1];
		scriptBlock.position = responseText.indexOf(match[1]);					
		scriptBlocks.push(scriptBlock);
	}
	
	while (match = reContent.exec(responseText)) {
		if(_trim(match[2]) != '') {		
			var scriptBlock = new ScriptBlock();
			scriptBlock.isSrc = false;
			scriptBlock.text = match[2];
			scriptBlock.scriptContainerText = match[1];
			scriptBlock.position = responseText.indexOf(match[1]);
			scriptBlocks.push(scriptBlock);
		}				
	}
	
	scriptBlocks.sort(_sortScriptBlocks);
	
	var newResponseText = responseText;
	var divElement = document.getElementById(divName);
	if(divElement) {
		_removeChildren(divElement);
		
		for (var index = 0; index < scriptBlocks.length; index++){			
			newResponseText = newResponseText.replace(scriptBlocks[index].scriptContainerText, "");					
		}
								
		document.getElementById(divName).innerHTML = newResponseText;
		
		for (var index = 0; index < scriptBlocks.length; index++){									
			var newScript = document.createElement('script');
			newScript.type = "text/javascript";			
			
			if(scriptBlocks[index].isSrc) {
				newScript.src = scriptBlocks[index].text;
			}
			else {			
				newScript.text = scriptBlocks[index].text;
			}
			
			document.getElementById(divName).appendChild(newScript);
		}
	}
}

function _sortScriptBlocks(scriptBlock1, scriptBlock2) {
	var position1 = scriptBlock1.position;
	var position2 = scriptBlock2.position;
	
	return (position1 - position2);
}

function _trim(string) {
	if(string.length < 1) {
		return"";
	}
	string = _rTrim(string);
	string = _lTrim(string);

	if(string == "") {
		return "";
	} 
	else {
		return string;
	}
}

function _rTrim(string){
	var spaceChar = String.fromCharCode(32);
	var tabChar = String.fromCharCode(9);
	var length = string.length;
	var strTemp = "";

	if(length < 1){
		return "";
	}
	
	var iTemp = length -1;
	while(iTemp > -1){
		if(string.charAt(iTemp) == spaceChar ||
			string.charAt(iTemp) == tabChar) {
		}
		else {
			strTemp = string.substring(0, iTemp +1);
			break;
		}
		iTemp = iTemp-1;
	}
	
	return strTemp;
}

function _lTrim(string){
	var spaceChar = String.fromCharCode(32);
	var tabChar = String.fromCharCode(9);
	var length = string.length;
	var strTemp = "";
	
	if(length < 1){
		return "";
	}
	
	var iTemp = 0;
	while(iTemp < length){
		if(string.charAt(iTemp) == spaceChar ||
			string.charAt(iTemp) == tabChar) {
		}
		else {
			strTemp = string.substring(iTemp, length);
			break;
		}
		iTemp = iTemp + 1;
	}
	
	return strTemp;
}
window.pageHistory  = {
	currentHistoryCode: null,
	listener: null,
	storage: new Array(),
	hiddenIFrame: null,
	
	initialize: function() {
		//Create a hidden IFrame for IE
		if(is.ie) {
			this.createHiddenIFrame();
		}
		
		var pageHistoryObject = this;
		var verifyLocationFunction = function() {
			pageHistoryObject.verifyBrowserLocation();
		};
		
		setInterval(verifyLocationFunction, 100);
	},

	registerListener: function(listener) {
		this.listener = listener;
	},
	
	push: function(historyCode) {
		if(historyCode != this.currentHistoryCode) {
			if(is.ie && this.hiddenIFrame) {
				this.hiddenIFrame.src = "blank.html?" + historyCode;
			}
			window.location.hash = historyCode;
			this.currentHistoryCode = historyCode;
		}
	},
	
	store: function(key, data) {
		this.storage[key] = data;
	},
	
	getStorage: function(key) {
		return this.storage[key];
	},
	
	
	/*****Private Functions below this*****/
	
	verifyBrowserLocation: function() {
		var newHistoryCode = window.location.hash;
		var indexOfHash = newHistoryCode.indexOf("#");
		if(indexOfHash > -1) {
			newHistoryCode = newHistoryCode.substring(indexOfHash + 1);
		}
		
		if(this.currentHistoryCode && (newHistoryCode != this.currentHistoryCode)) {
			this.fireHistoryChange(newHistoryCode);
			this.currentHistoryCode = newHistoryCode;
		}
	},

	fireHistoryChange: function(newHistoryCode) {
		if(this.listener) {
			this.listener.call(null, newHistoryCode);
		}
	},
	
	createHiddenIFrame: function() {
		var iFrameId = "_pageHistoryHiddenIFrame";
		var iFrame = document.createElement("iframe");
		iFrame.id = iFrameId;
		iFrame.src = "blank.html";
		iFrame.frameborder = "0";
		iFrame.style.position = "absolute";
		iFrame.style.width = "1px";
		iFrame.style.height = "1px";
		iFrame.style.left = "-100px";
		iFrame.style.top = "-100px";
		
		document.appendChild(iFrame);
		
		this.hiddenIFrame = document.getElementById(iFrameId);
	},
	
	registerIFrameLocation: function(location) {
		var queryString = location.search;
		if(queryString) {
			var newHistoryCode = queryString;
			var indexOfQuestionMark = newHistoryCode.indexOf("?");
			if(indexOfQuestionMark > -1) {
				newHistoryCode = newHistoryCode.substring(indexOfQuestionMark + 1);
			}
			
			var currentHistoryCode = window.location.hash;
			var indexOfHash = currentHistoryCode.indexOf("#");
			if(indexOfHash > -1) {
				currentHistoryCode = currentHistoryCode.substring(indexOfHash + 1);
			}
			
			if(newHistoryCode != currentHistoryCode) {
				window.location.hash = newHistoryCode;
			}
		}
	}
}/* This file is used to store browser history constants, used for navigation
   to previous/next pages when the browser back/forward button are clicked */

/* Content pages */   
/* Codes 1 through 1000 */
var HISTORY_LANDING_URL = 0;
var HISTORY_HOME = 1;
var HISTORY_DESTINATION_HOME = 2;
var HISTORY_CRUISE_HOME = 3;
var HISTORY_ANCILLARY_HOME  =4;
var HISTORY_DESTINATION_LANDING = 5;
var HISTORY_REGION_LANDING = 6;
var HISTORY_AREA_LANDING = 7;
var HISTORY_CRUISE_DESTINATION_LANDING = 8;
var HISTORY_CRUISE_LINE_LANDING = 9;
var HISTORY_CRUISE_SHIP_LANDING = 10;
var HISTORY_ANCILLARY_LANDING = 11;
var HISTORY_ANCILLARY_CATEGORY_LANDING = 12;
var HISTORY_LAND_PACKAGE = 13;
var HISTORY_CRUISE_PACKAGE = 14;
var HISTORY_ANCILLARY_PACKAGE = 15;
var HISTORY_HOTEL = 16;
var HISTORY_RIGHT_CONTENT_HOTEL = 17;
var HISTORY_GENERAL_INFO = 18;
var HISTORY_SITE_MAP = 19;
var HISTORY_BLAST_OFFER_LANDING = 20;
var HISTORY_SWEEPSTAKES_LANDING = 21;

/* Search Pages */
/* Codes 1001 through 2000 */
var HISTORY_SEARCH_RESULT_ALL_PACKAGES = 1001;
var HISTORY_SEARCH_RESULT_PACKAGE_FLIGHT_HOTEL = 1002;
var HISTORY_SEARCH_RESULT_PACKAGE_TRANSPORTATION = 1003;

/* Cruise Search */
var HISTORY_CRUISE_SAILING_SEARCH_RESULTS = 1501;
var HISTORY_CRUISE_PASSENGER_INFO = 1502;
var HISTORY_CRUISE_CATEGORY_RESULTS = 1503;
var HISTORY_CRUISE_CABIN_RESULTS = 1504;

/* Booking Pages */
/* Codes 2001 through 3000 */
var HISTORY_BOOKING_RECAP = 2001;
var HISTORY_BOOKING_MEMBER_LOGIN = 2002;
var HISTORY_PASSENGER_DETAILS = 2003;
var HISTORY_SPECIAL_REQUESTS = 2004;
var HISTORY_SEAT_MAP_SELECTION = 2005;
var HISTORY_PAYMENT= 2006;
var HISTORY_PAYMENT_SUMMARY = 2007;
var HISTORY_ORDER_CONFIRMATION = 2008;
var HISTORY_ITINERARY_MEMBER_LOGIN = 2009;
var HISTORY_MEMBER_BOOKING_DETAILS = 2010;
var HISTORY_BOOKING_DETAILS = 2011;
var HISTORY_BALANCE_PAYMENT_SUMMARY = 2012;
var HISTORY_BALANCE_PAYMENT = 2013;

/* Crusie Booking */
var HISTORY_CRUISE_PASSENGER_DETAILS = 2501;
var HISTORY_CRUISE_SPECIAL_REQUESTS = 2502;
var HISTORY_CRUISE_BOOKING_RECAP = 2503;
var HISTORY_CRUISE_BOOKING_CONFIRMATION = 2504;function expandCollaspePlusMinus(expandCollapseImageName, expandCollapseDivName) {	
	expandCollaspeDiv(expandCollapseImageName, expandCollapseDivName, new Array("shared/images/core/buttons/plus.gif", "shared/images/core/buttons/minus.gif"));
}

function expandCollaspePlusMinusBig(expandCollapseImageName, expandCollapseDivName) {	
	expandCollaspeDiv(expandCollapseImageName, expandCollapseDivName, new Array("shared/images/core/buttons/plusBig.gif", "shared/images/core/buttons/minusBig.gif"));
}

function expandCollaspeUpDown(expandCollapseImageName, expandCollapseDivName) {	
	expandCollaspeDiv(expandCollapseImageName, expandCollapseDivName, new Array("shared/images/core/buttons/arrow-black-up.gif", "shared/images/core/buttons/arrow-black-dwn.gif"));
}

function expandCollaspeUpDownIti(expandCollapseImageName, expandCollapseDivName) {	
	expandCollaspeDiv(expandCollapseImageName, expandCollapseDivName, new Array("shared/images/core/buttons/arrow-black-up.gif", "shared/images/core/buttons/arrow-black-dwn.gif"));
}

/***********************************************
* Dock Content script- Created by and © Dynamicdrive.com
* This notice must stay intact for use
* Visit http://www.dynamicdrive.com/ for full script
***********************************************/

var offsetfromedge=0 //offset from window edge when content is "docked".
var dockarray=new Array() //array to cache dockit instances
var dkclear=new Array() //array to cache corresponding clearinterval pointers

function dockit(el, duration){
	this.source=document.all? document.all[el] : document.getElementById(el);
	this.source.height=this.source.offsetHeight;
	this.docheight=truebody().clientHeight;
	this.duration=duration;
	this.pagetop=0;
	this.elementoffset=this.getOffsetY();
	dockarray[dockarray.length]=this;
	var pointer=eval(dockarray.length-1);
	var dynexpress='dkclear['+pointer+']=setInterval("dockornot(dockarray['+pointer+'])",1);';
	dynexpress=(this.duration>0)? dynexpress+'setTimeout("clearInterval(dkclear['+pointer+']); dockarray['+pointer+'].source.style.top=0", duration*1000)' : dynexpress;
	eval(dynexpress);
}

dockit.prototype.getOffsetY=function(){
var totaloffset=parseInt(this.source.offsetTop);
var parentEl=this.source.offsetParent;
while (parentEl!=null){
totaloffset+=parentEl.offsetTop;
parentEl=parentEl.offsetParent;
}
return totaloffset;
}

function dockornot(obj){
	obj.pagetop=truebody().scrollTop;
	if (obj.pagetop>obj.elementoffset) //detect upper offset
	obj.source.style.top=obj.pagetop-obj.elementoffset+offsetfromedge+"px";
	else if (obj.pagetop+obj.docheight<obj.elementoffset+parseInt(obj.source.height)) //lower offset
	obj.source.style.top=obj.pagetop+obj.docheight-obj.source.height-obj.elementoffset-offsetfromedge+"px";
	else
	obj.source.style.top=0;
}

function truebody(){
	return (document.compatMode && document.compatMode!="BackCompat")? document.documentElement : document.body
}


/*****************************
* Script to Incriment the cost
******************************/

var cost = 1056;
var count = 0;
function timedCount(){
	document.getElementById('divPrice').innerHTML = 'US $' + cost ;
	cost = cost + 1;
	count = count + 1;
	if( count < 48 ) {
		setTimeout("timedCount()",1);
		} else {
			count = 0;
			}
		}/*! SWFObject v2.1 <http://code.google.com/p/swfobject/>
	Copyright (c) 2007-2008 Geoff Stearns, Michael Williams, and Bobby van der Sluis
	This software is released under the MIT License <http://www.opensource.org/licenses/mit-license.php>
*/

var swfobject = function() {
	
	var UNDEF = "undefined",
		OBJECT = "object",
		SHOCKWAVE_FLASH = "Shockwave Flash",
		SHOCKWAVE_FLASH_AX = "ShockwaveFlash.ShockwaveFlash",
		FLASH_MIME_TYPE = "application/x-shockwave-flash",
		EXPRESS_INSTALL_ID = "SWFObjectExprInst",
		
		win = window,
		doc = document,
		nav = navigator,
		
		domLoadFnArr = [],
		regObjArr = [],
		objIdArr = [],
		listenersArr = [],
		script,
		timer = null,
		storedAltContent = null,
		storedAltContentId = null,
		isDomLoaded = false,
		isExpressInstallActive = false;
	
	/* Centralized function for browser feature detection
		- Proprietary feature detection (conditional compiling) is used to detect Internet Explorer's features
		- User agent string detection is only used when no alternative is possible
		- Is executed directly for optimal performance
	*/	
	var ua = function() {
		var w3cdom = typeof doc.getElementById != UNDEF && typeof doc.getElementsByTagName != UNDEF && typeof doc.createElement != UNDEF,
			playerVersion = [0,0,0],
			d = null;
		if (typeof nav.plugins != UNDEF && typeof nav.plugins[SHOCKWAVE_FLASH] == OBJECT) {
			d = nav.plugins[SHOCKWAVE_FLASH].description;
			if (d && !(typeof nav.mimeTypes != UNDEF && nav.mimeTypes[FLASH_MIME_TYPE] && !nav.mimeTypes[FLASH_MIME_TYPE].enabledPlugin)) { // navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin indicates whether plug-ins are enabled or disabled in Safari 3+
				d = d.replace(/^.*\s+(\S+\s+\S+$)/, "$1");
				playerVersion[0] = parseInt(d.replace(/^(.*)\..*$/, "$1"), 10);
				playerVersion[1] = parseInt(d.replace(/^.*\.(.*)\s.*$/, "$1"), 10);
				playerVersion[2] = /r/.test(d) ? parseInt(d.replace(/^.*r(.*)$/, "$1"), 10) : 0;
			}
		}
		else if (typeof win.ActiveXObject != UNDEF) {
			var a = null, fp6Crash = false;
			try {
				a = new ActiveXObject(SHOCKWAVE_FLASH_AX + ".7");
			}
			catch(e) {
				try { 
					a = new ActiveXObject(SHOCKWAVE_FLASH_AX + ".6");
					playerVersion = [6,0,21];
					a.AllowScriptAccess = "always";	 // Introduced in fp6.0.47
				}
				catch(e) {
					if (playerVersion[0] == 6) {
						fp6Crash = true;
					}
				}
				if (!fp6Crash) {
					try {
						a = new ActiveXObject(SHOCKWAVE_FLASH_AX);
					}
					catch(e) {}
				}
			}
			if (!fp6Crash && a) { // a will return null when ActiveX is disabled
				try {
					d = a.GetVariable("$version");	// Will crash fp6.0.21/23/29
					if (d) {
						d = d.split(" ")[1].split(",");
						playerVersion = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)];
					}
				}
				catch(e) {}
			}
		}
		var u = nav.userAgent.toLowerCase(),
			p = nav.platform.toLowerCase(),
			webkit = /webkit/.test(u) ? parseFloat(u.replace(/^.*webkit\/(\d+(\.\d+)?).*$/, "$1")) : false, // returns either the webkit version or false if not webkit
			ie = false,
			windows = p ? /win/.test(p) : /win/.test(u),
			mac = p ? /mac/.test(p) : /mac/.test(u);
		/*@cc_on
			ie = true;
			@if (@_win32)
				windows = true;
			@elif (@_mac)
				mac = true;
			@end
		@*/
		return { w3cdom:w3cdom, pv:playerVersion, webkit:webkit, ie:ie, win:windows, mac:mac };
	}();

	/* Cross-browser onDomLoad
		- Based on Dean Edwards' solution: http://dean.edwards.name/weblog/2006/06/again/
		- Will fire an event as soon as the DOM of a page is loaded (supported by Gecko based browsers - like Firefox -, IE, Opera9+, Safari)
	*/ 
	var onDomLoad = function() {
		if (!ua.w3cdom) {
			return;
		}
		addDomLoadEvent(main);
		if (ua.ie && ua.win) {
			try {	 // Avoid a possible Operation Aborted error
				doc.write("<scr" + "ipt id=__ie_ondomload defer=true src=//:></scr" + "ipt>"); // String is split into pieces to avoid Norton AV to add code that can cause errors 
				script = getElementById("__ie_ondomload");
				if (script) {
					addListener(script, "onreadystatechange", checkReadyState);
				}
			}
			catch(e) {}
		}
		if (ua.webkit && typeof doc.readyState != UNDEF) {
			timer = setInterval(function() { if (/loaded|complete/.test(doc.readyState)) { callDomLoadFunctions(); }}, 10);
		}
		if (typeof doc.addEventListener != UNDEF) {
			doc.addEventListener("DOMContentLoaded", callDomLoadFunctions, null);
		}
		addLoadEvent(callDomLoadFunctions);
	}();
	
	function checkReadyState() {
		if (script.readyState == "complete") {
			script.parentNode.removeChild(script);
			callDomLoadFunctions();
		}
	}
	
	function callDomLoadFunctions() {
		if (isDomLoaded) {
			return;
		}
		if (ua.ie && ua.win) { // Test if we can really add elements to the DOM; we don't want to fire it too early
			var s = createElement("span");
			try { // Avoid a possible Operation Aborted error
				var t = doc.getElementsByTagName("body")[0].appendChild(s);
				t.parentNode.removeChild(t);
			}
			catch (e) {
				return;
			}
		}
		isDomLoaded = true;
		if (timer) {
			clearInterval(timer);
			timer = null;
		}
		var dl = domLoadFnArr.length;
		for (var i = 0; i < dl; i++) {
			domLoadFnArr[i]();
		}
	}
	
	function addDomLoadEvent(fn) {
		if (isDomLoaded) {
			fn();
		}
		else { 
			domLoadFnArr[domLoadFnArr.length] = fn; // Array.push() is only available in IE5.5+
		}
	}
	
	/* Cross-browser onload
		- Based on James Edwards' solution: http://brothercake.com/site/resources/scripts/onload/
		- Will fire an event as soon as a web page including all of its assets are loaded 
	 */
	function addLoadEvent(fn) {
		if (typeof win.addEventListener != UNDEF) {
			win.addEventListener("load", fn, false);
		}
		else if (typeof doc.addEventListener != UNDEF) {
			doc.addEventListener("load", fn, false);
		}
		else if (typeof win.attachEvent != UNDEF) {
			addListener(win, "onload", fn);
		}
		else if (typeof win.onload == "function") {
			var fnOld = win.onload;
			win.onload = function() {
				fnOld();
				fn();
			};
		}
		else {
			win.onload = fn;
		}
	}
	
	/* Main function
		- Will preferably execute onDomLoad, otherwise onload (as a fallback)
	*/
	function main() { // Static publishing only
		var rl = regObjArr.length;
		for (var i = 0; i < rl; i++) { // For each registered object element
			var id = regObjArr[i].id;
			if (ua.pv[0] > 0) {
				var obj = getElementById(id);
				if (obj) {
					regObjArr[i].width = obj.getAttribute("width") ? obj.getAttribute("width") : "0";
					regObjArr[i].height = obj.getAttribute("height") ? obj.getAttribute("height") : "0";
					if (hasPlayerVersion(regObjArr[i].swfVersion)) { // Flash plug-in version >= Flash content version: Houston, we have a match!
						if (ua.webkit && ua.webkit < 312) { // Older webkit engines ignore the object element's nested param elements
							fixParams(obj);
						}
						setVisibility(id, true);
					}
					else if (regObjArr[i].expressInstall && !isExpressInstallActive && hasPlayerVersion("6.0.65") && (ua.win || ua.mac)) { // Show the Adobe Express Install dialog if set by the web page author and if supported (fp6.0.65+ on Win/Mac OS only)
						showExpressInstall(regObjArr[i]);
					}
					else { // Flash plug-in and Flash content version mismatch: display alternative content instead of Flash content
						displayAltContent(obj);
					}
				}
			}
			else {	// If no fp is installed, we let the object element do its job (show alternative content)
				setVisibility(id, true);
			}
		}
	}
	
	/* Fix nested param elements, which are ignored by older webkit engines
		- This includes Safari up to and including version 1.2.2 on Mac OS 10.3
		- Fall back to the proprietary embed element
	*/
	function fixParams(obj) {
		var nestedObj = obj.getElementsByTagName(OBJECT)[0];
		if (nestedObj) {
			var e = createElement("embed"), a = nestedObj.attributes;
			if (a) {
				var al = a.length;
				for (var i = 0; i < al; i++) {
					if (a[i].nodeName == "DATA") {
						e.setAttribute("src", a[i].nodeValue);
					}
					else {
						e.setAttribute(a[i].nodeName, a[i].nodeValue);
					}
				}
			}
			var c = nestedObj.childNodes;
			if (c) {
				var cl = c.length;
				for (var j = 0; j < cl; j++) {
					if (c[j].nodeType == 1 && c[j].nodeName == "PARAM") {
						e.setAttribute(c[j].getAttribute("name"), c[j].getAttribute("value"));
					}
				}
			}
			obj.parentNode.replaceChild(e, obj);
		}
	}
	
	/* Show the Adobe Express Install dialog
		- Reference: http://www.adobe.com/cfusion/knowledgebase/index.cfm?id=6a253b75
	*/
	function showExpressInstall(regObj) {
		isExpressInstallActive = true;
		var obj = getElementById(regObj.id);
		if (obj) {
			if (regObj.altContentId) {
				var ac = getElementById(regObj.altContentId);
				if (ac) {
					storedAltContent = ac;
					storedAltContentId = regObj.altContentId;
				}
			}
			else {
				storedAltContent = abstractAltContent(obj);
			}
			if (!(/%$/.test(regObj.width)) && parseInt(regObj.width, 10) < 310) {
				regObj.width = "310";
			}
			if (!(/%$/.test(regObj.height)) && parseInt(regObj.height, 10) < 137) {
				regObj.height = "137";
			}
			doc.title = doc.title.slice(0, 47) + " - Flash Player Installation";
			var pt = ua.ie && ua.win ? "ActiveX" : "PlugIn",
				dt = doc.title,
				fv = "MMredirectURL=" + win.location + "&MMplayerType=" + pt + "&MMdoctitle=" + dt,
				replaceId = regObj.id;
			// For IE when a SWF is loading (AND: not available in cache) wait for the onload event to fire to remove the original object element
			// In IE you cannot properly cancel a loading SWF file without breaking browser load references, also obj.onreadystatechange doesn't work
			if (ua.ie && ua.win && obj.readyState != 4) {
				var newObj = createElement("div");
				replaceId += "SWFObjectNew";
				newObj.setAttribute("id", replaceId);
				obj.parentNode.insertBefore(newObj, obj); // Insert placeholder div that will be replaced by the object element that loads expressinstall.swf
				obj.style.display = "none";
				var fn = function() {
					obj.parentNode.removeChild(obj);
				};
				addListener(win, "onload", fn);
			}
			createSWF({ data:regObj.expressInstall, id:EXPRESS_INSTALL_ID, width:regObj.width, height:regObj.height }, { flashvars:fv }, replaceId);
		}
	}
	
	/* Functions to abstract and display alternative content
	*/
	function displayAltContent(obj) {
		if (ua.ie && ua.win && obj.readyState != 4) {
			// For IE when a SWF is loading (AND: not available in cache) wait for the onload event to fire to remove the original object element
			// In IE you cannot properly cancel a loading SWF file without breaking browser load references, also obj.onreadystatechange doesn't work
			var el = createElement("div");
			obj.parentNode.insertBefore(el, obj); // Insert placeholder div that will be replaced by the alternative content
			el.parentNode.replaceChild(abstractAltContent(obj), el);
			obj.style.display = "none";
			var fn = function() {
				obj.parentNode.removeChild(obj);
			};
			addListener(win, "onload", fn);
		}
		else {
			obj.parentNode.replaceChild(abstractAltContent(obj), obj);
		}
	} 

	function abstractAltContent(obj) {
		var ac = createElement("div");
		if (ua.win && ua.ie) {
			ac.innerHTML = obj.innerHTML;
		}
		else {
			var nestedObj = obj.getElementsByTagName(OBJECT)[0];
			if (nestedObj) {
				var c = nestedObj.childNodes;
				if (c) {
					var cl = c.length;
					for (var i = 0; i < cl; i++) {
						if (!(c[i].nodeType == 1 && c[i].nodeName == "PARAM") && !(c[i].nodeType == 8)) {
							ac.appendChild(c[i].cloneNode(true));
						}
					}
				}
			}
		}
		return ac;
	}
	
	/* Cross-browser dynamic SWF creation
	*/
	function createSWF(attObj, parObj, id) {
		var r, el = getElementById(id);
		if (el) {
			if (typeof attObj.id == UNDEF) { // if no 'id' is defined for the object element, it will inherit the 'id' from the alternative content
				attObj.id = id;
			}
			if (ua.ie && ua.win) { // IE, the object element and W3C DOM methods do not combine: fall back to outerHTML
				var att = "";
				for (var i in attObj) {
					if (attObj[i] != Object.prototype[i]) { // Filter out prototype additions from other potential libraries, like Object.prototype.toJSONString = function() {}
						if (i.toLowerCase() == "data") {
							parObj.movie = attObj[i];
						}
						else if (i.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword
							att += ' class="' + attObj[i] + '"';
						}
						else if (i.toLowerCase() != "classid") {
							att += ' ' + i + '="' + attObj[i] + '"';
						}
					}
				}
				var par = "";
				for (var j in parObj) {
					if (parObj[j] != Object.prototype[j]) { // Filter out prototype additions from other potential libraries
						par += '<param name="' + j + '" value="' + parObj[j] + '" />';
					}
				}
				el.innerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"' + att + '>' + par + '</object>';
				objIdArr[objIdArr.length] = attObj.id; // Stored to fix object 'leaks' on unload (dynamic publishing only)
				r = getElementById(attObj.id);	
			}
			else if (ua.webkit && ua.webkit < 312) { // Older webkit engines ignore the object element's nested param elements: fall back to the proprietary embed element
				var e = createElement("embed");
				e.setAttribute("type", FLASH_MIME_TYPE);
				for (var k in attObj) {
					if (attObj[k] != Object.prototype[k]) { // Filter out prototype additions from other potential libraries
						if (k.toLowerCase() == "data") {
							e.setAttribute("src", attObj[k]);
						}
						else if (k.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword
							e.setAttribute("class", attObj[k]);
						}
						else if (k.toLowerCase() != "classid") { // Filter out IE specific attribute
							e.setAttribute(k, attObj[k]);
						}
					}
				}
				for (var l in parObj) {
					if (parObj[l] != Object.prototype[l]) { // Filter out prototype additions from other potential libraries
						if (l.toLowerCase() != "movie") { // Filter out IE specific param element
							e.setAttribute(l, parObj[l]);
						}
					}
				}
				el.parentNode.replaceChild(e, el);
				r = e;
			}
			else { // Well-behaving browsers
				var o = createElement(OBJECT);
				o.setAttribute("type", FLASH_MIME_TYPE);
				for (var m in attObj) {
					if (attObj[m] != Object.prototype[m]) { // Filter out prototype additions from other potential libraries
						if (m.toLowerCase() == "styleclass") { // 'class' is an ECMA4 reserved keyword
							o.setAttribute("class", attObj[m]);
						}
						else if (m.toLowerCase() != "classid") { // Filter out IE specific attribute
							o.setAttribute(m, attObj[m]);
						}
					}
				}
				for (var n in parObj) {
					if (parObj[n] != Object.prototype[n] && n.toLowerCase() != "movie") { // Filter out prototype additions from other potential libraries and IE specific param element
						createObjParam(o, n, parObj[n]);
					}
				}
				el.parentNode.replaceChild(o, el);
				r = o;
			}
		}
		return r;
	}
	
	function createObjParam(el, pName, pValue) {
		var p = createElement("param");
		p.setAttribute("name", pName);	
		p.setAttribute("value", pValue);
		el.appendChild(p);
	}
	
	/* Cross-browser SWF removal
		- Especially needed to safely and completely remove a SWF in Internet Explorer
	*/
	function removeSWF(id) {
		var obj = getElementById(id);
		if (obj && (obj.nodeName == "OBJECT" || obj.nodeName == "EMBED")) {
			if (ua.ie && ua.win) {
				if (obj.readyState == 4) {
					removeObjectInIE(id);
				}
				else {
					win.attachEvent("onload", function() {
						removeObjectInIE(id);
					});
				}
			}
			else {
				obj.parentNode.removeChild(obj);
			}
		}
	}
	
	function removeObjectInIE(id) {
		var obj = getElementById(id);
		if (obj) {
			for (var i in obj) {
				if (typeof obj[i] == "function") {
					obj[i] = null;
				}
			}
			obj.parentNode.removeChild(obj);
		}
	}
	
	/* Functions to optimize JavaScript compression
	*/
	function getElementById(id) {
		var el = null;
		try {
			el = doc.getElementById(id);
		}
		catch (e) {}
		return el;
	}
	
	function createElement(el) {
		return doc.createElement(el);
	}
	
	/* Updated attachEvent function for Internet Explorer
		- Stores attachEvent information in an Array, so on unload the detachEvent functions can be called to avoid memory leaks
	*/	
	function addListener(target, eventType, fn) {
		target.attachEvent(eventType, fn);
		listenersArr[listenersArr.length] = [target, eventType, fn];
	}
	
	/* Flash Player and SWF content version matching
	*/
	function hasPlayerVersion(rv) {
		var pv = ua.pv, v = rv.split(".");
		v[0] = parseInt(v[0], 10);
		v[1] = parseInt(v[1], 10) || 0; // supports short notation, e.g. "9" instead of "9.0.0"
		v[2] = parseInt(v[2], 10) || 0;
		return (pv[0] > v[0] || (pv[0] == v[0] && pv[1] > v[1]) || (pv[0] == v[0] && pv[1] == v[1] && pv[2] >= v[2])) ? true : false;
	}
	
	/* Cross-browser dynamic CSS creation
		- Based on Bobby van der Sluis' solution: http://www.bobbyvandersluis.com/articles/dynamicCSS.php
	*/	
	function createCSS(sel, decl) {
		if (ua.ie && ua.mac) {
			return;
		}
		var h = doc.getElementsByTagName("head")[0], s = createElement("style");
		s.setAttribute("type", "text/css");
		s.setAttribute("media", "screen");
		if (!(ua.ie && ua.win) && typeof doc.createTextNode != UNDEF) {
			s.appendChild(doc.createTextNode(sel + " {" + decl + "}"));
		}
		h.appendChild(s);
		if (ua.ie && ua.win && typeof doc.styleSheets != UNDEF && doc.styleSheets.length > 0) {
			var ls = doc.styleSheets[doc.styleSheets.length - 1];
			if (typeof ls.addRule == OBJECT) {
				ls.addRule(sel, decl);
			}
		}
	}
	
	function setVisibility(id, isVisible) {
		var v = isVisible ? "visible" : "hidden";
		if (isDomLoaded && getElementById(id)) {
			getElementById(id).style.visibility = v;
		}
		else {
			createCSS("#" + id, "visibility:" + v);
		}
	}

	/* Filter to avoid XSS attacks 
	*/
	function urlEncodeIfNecessary(s) {
		var regex = /[\\\"<>\.;]/;
		var hasBadChars = regex.exec(s) != null;
		return hasBadChars ? encodeURIComponent(s) : s;
	}
	
	/* Release memory to avoid memory leaks caused by closures, fix hanging audio/video threads and force open sockets/NetConnections to disconnect (Internet Explorer only)
	*/
	var cleanup = function() {
		if (ua.ie && ua.win) {
			window.attachEvent("onunload", function() {
				// remove listeners to avoid memory leaks
				var ll = listenersArr.length;
				for (var i = 0; i < ll; i++) {
					listenersArr[i][0].detachEvent(listenersArr[i][1], listenersArr[i][2]);
				}
				// cleanup dynamically embedded objects to fix audio/video threads and force open sockets and NetConnections to disconnect
				var il = objIdArr.length;
				for (var j = 0; j < il; j++) {
					removeSWF(objIdArr[j]);
				}
				// cleanup library's main closures to avoid memory leaks
				for (var k in ua) {
					ua[k] = null;
				}
				ua = null;
				for (var l in swfobject) {
					swfobject[l] = null;
				}
				swfobject = null;
			});
		}
	}();
	
	
	return {
		/* Public API
			- Reference: http://code.google.com/p/swfobject/wiki/SWFObject_2_0_documentation
		*/ 
		registerObject: function(objectIdStr, swfVersionStr, xiSwfUrlStr) {
			if (!ua.w3cdom || !objectIdStr || !swfVersionStr) {
				return;
			}
			var regObj = {};
			regObj.id = objectIdStr;
			regObj.swfVersion = swfVersionStr;
			regObj.expressInstall = xiSwfUrlStr ? xiSwfUrlStr : false;
			regObjArr[regObjArr.length] = regObj;
			setVisibility(objectIdStr, false);
		},
		
		getObjectById: function(objectIdStr) {
			var r = null;
			if (ua.w3cdom) {
				var o = getElementById(objectIdStr);
				if (o) {
					var n = o.getElementsByTagName(OBJECT)[0];
					if (!n || (n && typeof o.SetVariable != UNDEF)) {
							r = o;
					}
					else if (typeof n.SetVariable != UNDEF) {
						r = n;
					}
				}
			}
			return r;
		},
		
		embedSWF: function(swfUrlStr, replaceElemIdStr, widthStr, heightStr, swfVersionStr, xiSwfUrlStr, flashvarsObj, parObj, attObj) {
			if (!ua.w3cdom || !swfUrlStr || !replaceElemIdStr || !widthStr || !heightStr || !swfVersionStr) {
				return;
			}
			widthStr += ""; // Auto-convert to string
			heightStr += "";
			if (hasPlayerVersion(swfVersionStr)) {
				setVisibility(replaceElemIdStr, false);
				var att = {};
				if (attObj && typeof attObj === OBJECT) {
					for (var i in attObj) {
						if (attObj[i] != Object.prototype[i]) { // Filter out prototype additions from other potential libraries
							att[i] = attObj[i];
						}
					}
				}
				att.data = swfUrlStr;
				att.width = widthStr;
				att.height = heightStr;
				var par = {}; 
				if (parObj && typeof parObj === OBJECT) {
					for (var j in parObj) {
						if (parObj[j] != Object.prototype[j]) { // Filter out prototype additions from other potential libraries
							par[j] = parObj[j];
						}
					}
				}
				if (flashvarsObj && typeof flashvarsObj === OBJECT) {
					for (var k in flashvarsObj) {
						if (flashvarsObj[k] != Object.prototype[k]) { // Filter out prototype additions from other potential libraries
							if (typeof par.flashvars != UNDEF) {
								par.flashvars += "&" + k + "=" + flashvarsObj[k];
							}
							else {
								par.flashvars = k + "=" + flashvarsObj[k];
							}
						}
					}
				}
				addDomLoadEvent(function() {
					createSWF(att, par, replaceElemIdStr);
					setVisibility(replaceElemIdStr, true);
					//if (att.id == replaceElemIdStr) {
					//	
					//}
				});
			}
			else if (xiSwfUrlStr && !isExpressInstallActive && hasPlayerVersion("6.0.65") && (ua.win || ua.mac)) {
				isExpressInstallActive = true; // deferred execution
				setVisibility(replaceElemIdStr, false);
				addDomLoadEvent(function() {
					var regObj = {};
					regObj.id = regObj.altContentId = replaceElemIdStr;
					regObj.width = widthStr;
					regObj.height = heightStr;
					regObj.expressInstall = xiSwfUrlStr;
					showExpressInstall(regObj);
				});
			}
		},
		
		getFlashPlayerVersion: function() {
			return { major:ua.pv[0], minor:ua.pv[1], release:ua.pv[2] };
		},
		
		hasFlashPlayerVersion: hasPlayerVersion,
		
		createSWF: function(attObj, parObj, replaceElemIdStr) {
			if (ua.w3cdom) {
				return createSWF(attObj, parObj, replaceElemIdStr);
			}
			else {
				return undefined;
			}
		},
		
		removeSWF: function(objElemIdStr) {
			if (ua.w3cdom) {
				removeSWF(objElemIdStr);
			}
		},
		
		createCSS: function(sel, decl) {
			if (ua.w3cdom) {
				createCSS(sel, decl);
			}
		},
		
		addDomLoadEvent: addDomLoadEvent,
		
		addLoadEvent: addLoadEvent,
		
		getQueryParamValue: function(param) {
			var q = doc.location.search || doc.location.hash;
			if (param == null) {
				return urlEncodeIfNecessary(q);
			}
			if (q) {
				var pairs = q.substring(1).split("&");
				for (var i = 0; i < pairs.length; i++) {
					if (pairs[i].substring(0, pairs[i].indexOf("=")) == param) {
						return urlEncodeIfNecessary(pairs[i].substring((pairs[i].indexOf("=") + 1)));
					}
				}
			}
			return "";
		},
		
		// For internal usage only
		expressInstallCallback: function() {
			if (isExpressInstallActive && storedAltContent) {
				var obj = getElementById(EXPRESS_INSTALL_ID);
				if (obj) {
					obj.parentNode.replaceChild(storedAltContent, obj);
					if (storedAltContentId) {
						setVisibility(storedAltContentId, true);
						if (ua.ie && ua.win) {
							storedAltContent.style.display = "block";
						}
					}
					storedAltContent = null;
					storedAltContentId = null;
					isExpressInstallActive = false;
				}
			} 
		}
	};
}();
var varLastActiveHotelTab = 'Overview';
var varLastActiveHotelPopupTab = 'PopupOverview';
var varLastActiveHotelInnerTab = 'PropFeatures';
var varLastActiveDestinationHomeTab = 'DestinationHomeOverview' ;
var varLastActiveDestinationTab = 'DestinationOverview' ;
var varLastActiveRegionTab = 'RegionOverview' ;
var varLastActiveAreaTab = 'AreaOverview' ;
var varLastActiveCruiseTab = 'CruiseWhyCruise' ;
var varLastActiveCruiseShipTab = 'ShipOverview' ;
var varLastActiveCityTab = 'City2'; 
var _leftBottomContentUrl = '';
var _leftBottomContentUrlQueryString = '';
var _rightCenterContentUrl = '';
var _rightRightContentUrl = '';
var _rightRightLocationContentUrl = '';
var _rightBottomContentUrl = '';
var _regionTabContentUrl = '';
var _hotelTabContentUrl = '';
var _hotelInnerTabContentUrl = '';
var _initializeRegionTab = false;
var _initializeHotelTab = false;
var _initializeHotelInnerTab = false;
var _region;
var _trackingText;
var _destinationCode = '';
var _regionCode = '';
var _packageId = '';
var _destinationName = '';
var _cruiseLineName = '';
var _shipName = '';
var _departureDate = '';
var varSearchMode = '';

/* The following variables are defined to be used for setting the booking and support 
*  phone numbers depending on the page the user is now		 
*/
var bookingPhoneNumber = "1-877-849-2730";
var supportPhoneNumber = "1-866-921-7925";
var bookingMessage = 'To book, call';
var supportMessage = 'For assistance, call';
/**************************************************************************************/

function initializeHotelTab() {
	varLastActiveHotelTab = 'Overview';
}

function initializeHotelInnerTab() {
	varLastActiveHotelInnerTab = 'PropFeatures';
}

function initializeDestinationHomeTab() {
	varLastActiveDestinationHomeTab = 'DestinationHomeOverview';
}

function initializeDestinationTab() {
	varLastActiveDestinationTab = 'DestinationOverview';
}

function initializeRegionTab() {
	varLastActiveRegionTab = 'RegionOverview';
}

function initializeAreaTab() {
	varLastActiveAreaTab = 'AreaOverview';
}

function initializeCruiseTab() {
	varLastActiveCruiseTab = 'CruiseWhyCruise';
}

function initializeCruiseShipTab() {
	varLastActiveCruiseShipTab = 'ShipOverview';
}

function activateHotelTab(tabName) {		
	
	var lastActiveHotelTab = document.getElementById('div' + varLastActiveHotelTab);
	if(lastActiveHotelTab) {
		lastActiveHotelTab.className = "tab01";
	}
	document.getElementById('div' + tabName).className = "tab-sel01";

	if(varLastActiveHotelTab != tabName) {
		varLastActiveHotelTab = tabName ;
	}
}

function activateHotelPopupTab(tabName) {			
	var lastActiveHotelTab = document.getElementById('div' + varLastActiveHotelPopupTab);
	if(lastActiveHotelTab) {
		lastActiveHotelTab.className = "tab01";
	}
	document.getElementById('div' + tabName).className = "tab-sel01";

	if(varLastActiveHotelPopupTab != tabName) {
		varLastActiveHotelPopupTab = tabName ;
	}
}

function activateHotelInnerTab(tabName) {	
	var lastActiveHotelInnerTab = document.getElementById('div' + varLastActiveHotelInnerTab);
	if(lastActiveHotelInnerTab) {
		lastActiveHotelInnerTab.className = "tab02" ;
	}
	document.getElementById('div' + tabName).className = "tab-sel02" ;
	
	if(varLastActiveHotelInnerTab != tabName) {
		varLastActiveHotelInnerTab = tabName ;
	}
}

function activateCityTab(tabName) {	
	var lastActiveCityTab = document.getElementById('div' + varLastActiveCityTab);
	if(lastActiveCityTab) {
		lastActiveCityTab.className = "tab02" ;
	}
	
	if (document.getElementById('div' + tabName)){
		document.getElementById('div' + tabName).className = "tab-sel02" ;
	}	
	
	if(varLastActiveCityTab != tabName) {
		varLastActiveCityTab = tabName ;
	}
}

function activateDestinationHomeTab(tabName) {	
	var lastActiveDestinationHomeTab = document.getElementById('div' + varLastActiveDestinationHomeTab);
	if(lastActiveDestinationHomeTab) {
		lastActiveDestinationHomeTab.className = "tab01" ;
	}
	document.getElementById('div' + tabName).className = "tab-sel01" ;
	
	if(varLastActiveDestinationHomeTab != tabName) {
		varLastActiveDestinationHomeTab = tabName ;
	}
	
	varSearchMode = "VacationPackage";
}

function activateDestinationTab(tabName) {	
	var lastActiveDestinationTab = document.getElementById('div' + varLastActiveDestinationTab);
	if(lastActiveDestinationTab) {
		lastActiveDestinationTab.className = "tab01" ;
	}
	document.getElementById('div' + tabName).className = "tab-sel01" ;
	
	if(varLastActiveDestinationTab != tabName) {
		varLastActiveDestinationTab = tabName ;
	}
	
	varSearchMode = "VacationPackage";
}

function activateRegionTab(tabName) {	
	var lastActiveRegionTab = document.getElementById('div' + varLastActiveRegionTab);
	if(lastActiveRegionTab) {
		lastActiveRegionTab.className = "tab01" ;
	}
	document.getElementById('div' + tabName).className = "tab-sel01" ;
	
	if(varLastActiveRegionTab != tabName) {
		varLastActiveRegionTab = tabName ;
	}
	varSearchMode = "VacationPackage";
}

function activateAreaTab(tabName) {	
	var lastActiveAreaTab = document.getElementById('div' + varLastActiveAreaTab);
	if(lastActiveAreaTab) {
		lastActiveAreaTab.className = "tab01" ;
	}
	document.getElementById('div' + tabName).className = "tab-sel01" ;
	
	if(varLastActiveAreaTab != tabName) {
		varLastActiveAreaTab = tabName ;
	}
	varSearchMode = "VacationPackage";
}

function activateCruiseTab(tabName) {	
	var lastActiveCruiseTab = document.getElementById('div' + varLastActiveCruiseTab);
	if(lastActiveCruiseTab) {
		lastActiveCruiseTab.className = "tab01" ;
	}
	document.getElementById('div' + tabName).className = "tab-sel01" ;
	
	if(varLastActiveCruiseTab != tabName) {
		varLastActiveCruiseTab = tabName ;
	}
	varSearchMode = "Cruise";
}

function activateCruiseShipTab(tabName) {	
	var lastActiveCruiseShipTab = document.getElementById('div' + varLastActiveCruiseShipTab);
	if(lastActiveCruiseShipTab) {
		lastActiveCruiseShipTab.className = "tab01" ;
	}
	document.getElementById('div' + tabName).className = "tab-sel01" ;
	
	if(varLastActiveCruiseShipTab != tabName) {
		varLastActiveCruiseShipTab = tabName ;
	}
	varSearchMode = "Cruise";
}

function loadHomePage()
{
	//Load the main content block with '/home' as the description to be passed into Google Analytics
	loadMainContent('mainContent.act', null, '/home');
	loadDestinationTopBandImage();
	
	//Add the pseudo code "1" to browser history
	addHistory(HISTORY_HOME);
	
	//Scroll to the top of the page
	window.scrollTo(0,0);
	setSupportPhoneNumber(bookingPhoneNumber);
	varSearchMode = "VacationPackage";
}

function loadDestinationHome() {
	var queryString = 'lbc=0&rc=8&ruc=0';
	
	//Load the main content block with '/vp/browse/destinationHome' as the description to be passed into Google Analytics
	loadMainContent('mainContent.act', queryString, '/vp/browse/destinationHome');
	loadDestinationTopBandImage();

	//Initialize the tab structure within bottom tab content div to display the first tab
	initializeDestinationHomeTab();

	//Add the pseudo code '2' to browser history
	addHistory(HISTORY_DESTINATION_HOME);

	//Scroll to the top of the page
	window.scrollTo(0,0);
	setSupportPhoneNumber(bookingPhoneNumber);
	varSearchMode = "VacationPackage";
}

function loadDestination(destination) {
	//Load the main content block with '/vp/browse/destination/<destinationCode>' as the description to be passed into Google Analytics
	loadMainContent('mainContent.act', 'destination=' + destination + '&lbc=1&rc=1&rbc=1', '/vp/browse/destination/' + destination);
	loadDestinationTopBandImage(destination);

	//Add the pseudo code "5_<destinationCode>" to browser history
	addHistory(HISTORY_DESTINATION_LANDING, destination);
	
	//Initialize the tab structure within bottom content div to display the first tab
	initializeDestinationTab();

	//Scroll to the top of the page
	window.scrollTo(0,0);
	setSupportPhoneNumber(bookingPhoneNumber);
	varSearchMode = "VacationPackage";
}

function loadDestinationHomeOverview() {
	loadVacationTabContent('vacationTabContent.act', 'vtc=12');
}

function loadDestinationHomeBeforeYouGo() {
	loadVacationTabContent('vacationTabContent.act', 'vtc=13');
}

function loadDestinationOverview(destination) {
	//Load the vacation tab content block with '/vp/browse/destinatonOverview/<destinationCode>' as the description to be passed into Google Analytics
	loadVacationTabContent('vacationTabContent.act', 'destination=' + destination, '/vp/browse/destinatonOverview/' + destination);
}

function loadDestinationBeforeYouGo(destination) {
	//Load the vacation tab content block with '/vp/browse/destinatonBeforeYouGo/<destinationCode>' as the description to be passed into Google Analytics
	loadVacationTabContent('vacationTabContent.act', 'destination=' + destination + '&vtc=1', '/vp/browse/destinatonBeforeYouGo/' + destination);
}

function loadDestinationTransfers(destination) {
	//Load the vacation tab content block with 	'/vp/browse/destinatonTransfers/' as the description to be passed into Google Analytics
	loadVacationTabContent('vacationTabContent.act', 'destination=' + destination + '&vtc=14', '/vp/browse/destinatonTransfers/' + destination);
}

function loadDestinationTopExperiences(destination) {
	//Load the vacation content block with '/vp/browse/destinatonTopExperiences/<destinationCode>' as the description to be passed into Google Analytics
	loadVacationTabContent('vacationTabContent.act', 'destination=' + destination + '&vtc=2', '/vp/browse/destinatonTopExperiences/' +  destination);
}

function loadDestinationPlanner(destination) {
	//Load the vacation content block with '/vp/browse/destinatonPlanner/<destinationCode>' as the description to be passed into Google Analytics
	loadVacationTabContent('vacationTabContent.act', 'destination=' + destination + '&vtc=3', '/vp/browse/destinatonPlanner/' +  destination);
}

function loadDestinationSightseeings(destination) {
	//Load the vacation content block with '/vp/browse/destinatonSightseeings/' as the description to be passed into Google Analytics
	loadVacationTabContent('vacationTabContent.act', 'destination=' + destination + '&vtc=17', '/vp/browse/destinatonSightseeings/' +  destination);
}

function loadRegion(destination, region) {
	//Load the main content block with '/vp/browse/regional/<destinationCode>/<regionCode>' as the description to be passed into Google Analytics
	loadMainContent('mainContent.act', 'destination=' + destination + '&region=' + region + '&lbc=1&rc=1&rcc=1&rbc=2', '/vp/browse/regional/' +  destination + '/' + region);
	loadDestinationTopBandImage(destination);

	//Add the pseudo code "6_<destinationCode>_<regionCode>" to browser history
	addHistory(HISTORY_REGION_LANDING, destination, region);

	//Initialize the tab structure within bottom content div to display the first tab
	initializeRegionTab();

	//Scroll to the top of the page
	window.scrollTo(0,0);
	setSupportPhoneNumber(bookingPhoneNumber);
	varSearchMode = "VacationPackage";
}

function loadRegionOverview(destination, region) {
	//Load the vacation tab content block with '/vp/browse/regionalOverview/<destinationCode>/<regionCode>' as the description to be passed into Google Analytics
	loadVacationTabContent('vacationTabContent.act', 'destination=' + destination + '&region=' + region + '&vtc=4', '/vp/browse/regionalOverview/' +  destination + '/' + region);
}

function loadRegionBeforeYouGo(destination, region) {
	//Load the vacation tab content block with '/vp/browse/regionalBeforeYouGo/<destinationCode>/<regionCode>' as the description to be passed into Google Analytics
	loadVacationTabContent('vacationTabContent.act', 'destination=' + destination + '&region=' + region + '&vtc=5', '/vp/browse/regionalBeforeYouGo/' +  destination + '/' + region);
}

function loadRegionTransfers(destination, region) {
	//Load the vacation tab content block with '/vp/browse/destinationTransfers/<destination>/<region>' as the description to be passed into Google Analytics
	loadVacationTabContent('vacationTabContent.act', 'destination=' + destination + '&region=' + region + '&vtc=15', '/vp/browse/destinationTransfers/' +  destination + '/' + region);
}

function loadRegionTopExperiences(destination, region) {
	//Load the vacation tab content block with  '/vp/browse/regionalTopExperiences/<destinationCode>/<regionCode>' as the description to be passed into Google Analytics
	loadVacationTabContent('vacationTabContent.act', 'destination=' + destination + '&region=' + region + '&vtc=6', '/vp/browse/regionalTopExperiences/' +  destination + '/' + region);
}

function loadRegionPlanner(destination, region) {
	//Load the vacation tab content block with '/vp/browse/regionalPlanner/<destinationCode>/<regionCode>' as the description to be passed into Google Analytics
	loadVacationTabContent('vacationTabContent.act', 'destination=' + destination + '&region=' + region + '&vtc=7', '/vp/browse/regionalPlanner/' +  destination + '/' + region );
}

function loadRegionSightseeings(destination, region) {
	//Load the vacation tab content block with '/vp/browse/destinationSightseeings/<destination>/<region>' as the description to be passed into Google Analytics
	loadVacationTabContent('vacationTabContent.act', 'destination=' + destination + '&region=' + region + '&vtc=18', '/vp/browse/destinationSightseeings/' +  destination + '/' + region);
}

function loadArea(destination, region, area) {
	//Load the main content block with '/vp/browse/area/<destinationCode>/<regionCode>/<areaCode>' as the description to be passed into Google Analytics
	loadMainContent('mainContent.act', 'destination=' + destination + '&region=' + region + '&area=' + area + '&lbc=1&rc=1&rcc=2&rbc=3', '/vp/browse/area/' +  destination + '/' + region + '/' + area);
	loadDestinationTopBandImage(destination);

	//Add the pseudo code "7_<destinationCode>_<regionCode>_<areaCode>" to browser history
	addHistory(HISTORY_AREA_LANDING, destination, region, area);

	//Initialize the tab structure within bottom content div to display the first tab
	initializeAreaTab();

	//Scroll to the top of the page
	window.scrollTo(0,0);
	setSupportPhoneNumber(bookingPhoneNumber);
	varSearchMode = "VacationPackage";
}

function loadAreaOverview(destination, region, area) {
	//Load the vacation tab content block with '/vp/browse/areaOverview/<destinationCode>/<regionCode>/<areaCode>' as the description to be passed into Google Analytics
	loadVacationTabContent('vacationTabContent.act', 'destination=' + destination + '&region=' + region + '&area=' + area + '&vtc=8', '/vp/browse/areaOverview/' +  destination + '/' + region + '/' + area);
}

function loadAreaBeforeYouGo(destination, region, area) {
	//Load the vacation tab content block with '/vp/browse/areaBeforeYouGo/<destinationCode>/<regionCode>/<areaCode>' as the description to be passed into Google Analytics
	loadVacationTabContent('vacationTabContent.act', 'destination=' + destination + '&region=' + region + '&area=' + area  + '&vtc=9', '/vp/browse/areaBeforeYouGo/' +  destination + '/' + region + '/' + area);
}

function loadAreaTransfers(destination, region, area) {
	//Load the vacation tab content block with '/vp/browse/destinationTransfers/<destination>/<region>/<area>/transfers' as the description to be passed into Google Analytics
	loadVacationTabContent('vacationTabContent.act', 'destination=' + destination + '&region=' + region + '&area=' + area  + '&vtc=16', '/vp/browse/destinationTransfers/' +  destination + '/' + region + '/' + area );
}

function loadAreaTopExperiences(destination, region, area) {
	//Load the vacation tab content block with '/vp/browse/areaTopExperiences/<destinationCode>/<regionCode>/<areaCode>' as the description to be passed into Google Analytics
	loadVacationTabContent('vacationTabContent.act', 'destination=' + destination + '&region=' + region + '&area=' + area  + '&vtc=10', '/vp/browse/areaTopExperiences/' +  destination + '/' + region + '/' + area);
}

function loadAreaPlanner(destination, region, area) {
	//Load the vacation tab content block with '/vp/browse/areaPlanner/<destinationCode>/<regionCode>/<areaCode>' as the description to be passed into Google Analytics
	loadVacationTabContent('vacationTabContent.act', 'destination=' + destination + '&region=' + region + '&area=' + area  + '&vtc=11', '/vp/browse/areaPlanner/' +  destination + '/' + region + '/' + area );
}

function loadAreaSightseeings(destination, region, area) {
	//Load the vacation tab content block with '/vp/browse/destinationSightseeings/<destination>/<region>/<area>/sightseeings' as the description to be passed into Google Analytics
	loadVacationTabContent('vacationTabContent.act', 'destination=' + destination + '&region=' + region + '&area=' + area  + '&vtc=19', '/vp/browse/destinationSightseeings/' +  destination + '/' + region + '/' + area);
}

function loadHotel(destination, cityCode, hotelId, region, area, displayOffer, packageId, packageName) {
	var queryString = 'lbc=1&rc=2';
	if(destination) {
		queryString += '&destination=' + destination;
	}
	if(cityCode) {
		queryString += '&cityCode=' + cityCode;
	}
	if(hotelId) {
		queryString += '&hotelId=' + hotelId;
	}
	if(region) {
		queryString += '&region=' + region;
	}
	if(area) {
		queryString += '&area=' + area;
	}
	if(displayOffer) {
		queryString += '&displayOffer=' + displayOffer;
	}
	if(packageId) {
		queryString += '&packageId=' + packageId;
	}
	if(packageName) {
		queryString += '&packageName=' + packageName;
	}

	if(true == displayOffer) {
		//Load the main content block with '/an/browse/hotelOffer/hotel/<destinationCode>/<cityCode>/<hotelId>' as the description to be passed into Google Analytics
		loadMainContent('mainContent.act', queryString, '/an/browse/hotelOffer/hotel/' +  destination + '/' + cityCode + '/' + hotelId);
	}
	else {
		//Load the main content block with '/an/browse/hotel/hotel/<destinationCode>/<cityCode>/<hotelId>' as the description to be passed into Google Analytics
		loadMainContent('mainContent.act', queryString, '/an/browse/hotel/hotel/' +  destination + '/' + cityCode + '/' + hotelId);
	}

	//Add the pseudo code "16_<destinationCode>_<cityCode>_<hotelId>_<regionCode>_<areaCode>_<displayOffer>_<packageId>_<packageName>" to browser history
	addHistory(HISTORY_HOTEL, destination, cityCode, hotelId, region, area, displayOffer, packageId, packageName);

	//Initialize the tab structure within hotel tab content div to display the first tab
	initializeHotelTab();

	//Initialize the tab structure within hotel inner tab content div to display the first tab
	initializeHotelInnerTab();

	//Scroll to the top of the page
	window.scrollTo(0,0);
	setSupportPhoneNumber(bookingPhoneNumber);
}

function loadRightContentHotel(destination, cityCode, hotelId, region, area, displayOffer, packageId, packageName) {
	var queryString = 'rc=2';
	if(destination) {
		queryString += '&destination=' + destination;
	}
	if(cityCode) {
		queryString += '&cityCode=' + cityCode;
	}
	if(hotelId) {
		queryString += '&hotelId=' + hotelId;
	}
	if(region) {
		queryString += '&region=' + region;
	}
	if(area) {
		queryString += '&area=' + area;
	}
	if(displayOffer) {
		queryString += '&displayOffer=' + displayOffer;
	}
	if(packageId) {
		queryString += '&packageId=' + packageId;
	}
	if(packageName) {
		queryString += '&packageName=' + packageName;
	}

	if(true == displayOffer) {
		//Load the right content block with '/an/browse/hotelOffer/hotel/<destinationCode>/<cityCode>/<hotelId>' as the description to be passed into Google Analytics
		loadRightContent('rightContent.act', queryString, '/an/browse/hotelOffer/hotel/' +  destination + '/' + cityCode + '/' + hotelId);
	}
	else {
		//Load the right content block with '/an/browse/hotel/hotel/<destinationCode>/<cityCode>/<hotelId>' as the description to be passed into Google Analytics
		loadRightContent('rightContent.act', queryString, '/an/browse/hotel/hotel/' +  destination + '/' + cityCode + '/' + hotelId);
	}

	//Add the pseudo code "17_<destinationCode>_<cityCode>_<hotelId>_<regionCode>_<areaCode>_<displayOffer>_<packageId>_<packageName>" to browser history
	addHistory(HISTORY_RIGHT_CONTENT_HOTEL, destination, cityCode, hotelId, region, area, displayOffer, packageId, packageName);

	//Initialize the tab structure within hotel tab content div to display the first tab
	initializeHotelTab();

	//Initialize the tab structure within hotel inner tab content div to display the first tab
	initializeHotelInnerTab();

	//Scroll to the top of the page
	window.scrollTo(0,0);
	setSupportPhoneNumber(bookingPhoneNumber);
}

function loadHotelPopup(destination, cityCode, hotelId){
		varLastActiveHotelPopupTab = 'PopupOverview';
		loadHotelPropertyPopupDiv('hotelTabContent.act', 'destination=' + destination + '&cityCode=' + cityCode + '&hotelId=' + hotelId + '&htc=0' + '&loadHotelHeader=true');
}

function loadHotelPopupOverview(destination, cityCode, hotelId, allInclusive, optionalAllInclusive, loadHotelHeader){	
	if(loadHotelHeader){
		varLastActiveHotelPopupTab = 'PopupOverview';
		//Load the hotel popup tab with '/an/browse/hotelOverview/hotel/<destinationCode>/<cityCode>/<hotelId>' as the description to be passed into Google Analytics
		loadHotelPropertyPopupDiv('hotelTabContent.act', 'destination=' + destination + '&cityCode=' + cityCode + '&hotelId=' + hotelId + '&htc=0' + '&allInclusive='+ allInclusive + '&optionalAllInclusive=' + optionalAllInclusive + '&loadHotelHeader=true', '/an/browse/hotelOverview/hotel/' +  destination + '/' + cityCode + '/' + hotelId);
	}else{
		//Load the hotel tab content with '/an/browse/hotelOverview/hotel/<destinationCode>/<cityCode>/<hotelId>' as the description to be passed into Google Analytics
		loadHotelTabContent('hotelTabContent.act', 'destination=' + destination + '&cityCode=' + cityCode + '&hotelId=' + hotelId + '&htc=0' + '&allInclusive='+ allInclusive + '&optionalAllInclusive=' + optionalAllInclusive, '/an/browse/hotelOverview/hotel/' +  destination + '/' + cityCode + '/' + hotelId);
		document.getElementById('hotelTabContent').scrollTop = 0;	
	}
}

function loadHotelPopupProperty(destination, cityCode, hotelId, allInclusive, optionalAllInclusive, loadHotelHeader){	
	if(loadHotelHeader){
		varLastActiveHotelPopupTab = 'PopupProperty';
		//Load the hotel popup tab with '/an/browse/hotelPropertyFeatures/hotel/<destinationCode>/<cityCode>/<hotelId>' as the description to be passed into Google Analytics
		loadHotelPropertyPopupDiv('hotelTabContent.act', 'destination=' + destination + '&cityCode=' + cityCode + '&hotelId=' + hotelId + '&htc=1'  + '&allInclusive='+ allInclusive + '&optionalAllInclusive=' + optionalAllInclusive + '&loadHotelHeader=true', '/an/browse/hotelPropertyFeatures/hotel/' +  destination + '/' + cityCode + '/' + hotelId);
	}else{
		//Load the hotel tab content with '/an/browse/hotelPropertyFeatures/hotel/<destinationCode>/<cityCode>/<hotelId>' as the description to be passed into Google Analytics
		loadHotelTabContent('hotelTabContent.act', 'destination=' + destination + '&cityCode=' + cityCode + '&hotelId=' + hotelId + '&htc=1' + '&allInclusive='+ allInclusive + '&optionalAllInclusive=' + optionalAllInclusive, '/an/browse/hotelPropertyFeatures/hotel/' +  destination + '/' + cityCode + '/' + hotelId);
		document.getElementById('hotelTabContent').scrollTop = 0;	
	}
}

function loadHotelPopupRooms(destination, cityCode, hotelId, allInclusive, optionalAllInclusive, loadHotelHeader){
	if(loadHotelHeader){
		varLastActiveHotelPopupTab = 'PopupRooms';
		//Load the hotel popup tab with '/an/browse/hotelRooms/hotel/<destinationCode>/<cityCode>/<hotelId>' as the description to be passed into Google Analytics
		loadHotelPropertyPopupDiv('hotelTabContent.act', 'destination=' + destination + '&cityCode=' + cityCode + '&hotelId=' + hotelId + '&htc=2' + '&allInclusive='+ allInclusive + '&optionalAllInclusive=' + optionalAllInclusive + '&loadHotelHeader=true', '/an/browse/hotelRooms/hotel/' +  destination + '/' + cityCode + '/' + hotelId);
	}else{
		//Load the hotel tab content with '/an/browse/hotelRooms/hotel/<destinationCode>/<cityCode>/<hotelId>' as the description to be passed into Google Analytics
		loadHotelTabContent('hotelTabContent.act', 'destination=' + destination + '&cityCode=' + cityCode + '&hotelId=' + hotelId + '&htc=2' + '&allInclusive='+ allInclusive + '&optionalAllInclusive=' + optionalAllInclusive, '/an/browse/hotelRooms/hotel/' +  destination + '/' + cityCode + '/' + hotelId);
		document.getElementById('hotelTabContent').scrollTop = 0;
	}
}

function loadHotelPopupAllInclusive(destination, cityCode, hotelId, allInclusive, optionalAllInclusive, loadHotelHeader){
	if(loadHotelHeader){
		varLastActiveHotelPopupTab = 'PopupAllInclusive';	
		//Load the hotel popup tab with '/an/browse/hotelAllInclusive/hotel/<destinationCode>/<cityCode>/<hotelId>' as the description to be passed into Google Analytics
		loadHotelPropertyPopupDiv('hotelTabContent.act', 'destination=' + destination + '&cityCode=' + cityCode + '&hotelId=' + hotelId + '&htc=3'  + '&allInclusive='+ allInclusive + '&optionalAllInclusive=' + optionalAllInclusive + '&loadHotelHeader=true', '/an/browse/hotelAllInclusive/hotel/' +  destination + '/' + cityCode + '/' + hotelId );
	}else{
		//Load the hotel tab content with '/an/browse/hotelAllInclusive/hotel/<destinationCode>/<cityCode>/<hotelId>' as the description to be passed into Google Analytics
		loadHotelTabContent('hotelTabContent.act', 'destination=' + destination + '&cityCode=' + cityCode + '&hotelId=' + hotelId + '&htc=3' + '&allInclusive='+ allInclusive + '&optionalAllInclusive=' + optionalAllInclusive, '/an/browse/hotelAllInclusive/hotel/' +  destination + '/' + cityCode + '/' + hotelId);				
	}
}

function loadHotelPopupPhotosMaps(destination, cityCode, hotelId, allInclusive, optionalAllInclusive, loadHotelHeader){
	if(loadHotelHeader){
		varLastActiveHotelPopupTab = 'PopupPhotosMaps';	
		//Load the hotel popup tab with '/an/browse/hotelPhotosMaps/hotel/<destinationCode>/<cityCode>/<hotelId>' as the description to be passed into Google Analytics
		loadHotelPropertyPopupDiv('hotelTabContent.act', 'destination=' + destination + '&cityCode=' + cityCode + '&hotelId=' + hotelId + '&htc=4'  + '&allInclusive='+ allInclusive + '&optionalAllInclusive=' + optionalAllInclusive + '&loadHotelHeader=true', '/an/browse/hotelPhotosMaps/hotel/' +  destination + '/' + cityCode + '/' + hotelId);
	}else{
		//Load the hotel tab content with '/an/browse/hotelPhotosMaps/hotel/<destinationCode>/<cityCode>/<hotelId>' as the description to be passed into Google Analytics
		loadHotelTabContent('hotelTabContent.act', 'destination=' + destination + '&cityCode=' + cityCode + '&hotelId=' + hotelId + '&htc=4' + '&allInclusive='+ allInclusive + '&optionalAllInclusive=' + optionalAllInclusive + '&showOpaqueWmode=true', '/an/browse/hotelPhotosMaps/hotel/' +  destination + '/' + cityCode + '/' + hotelId);
		document.getElementById('hotelTabContent').scrollTop = 0;
	}
}

function loadHotelPopupMaps(destination, cityCode, hotelId, allInclusive, optionalAllInclusive, loadHotelHeader){
	if(loadHotelHeader){
		varLastActiveHotelPopupTab = 'PopupMaps';	
		//Load the hotel popup tab with '/an/browse/hotelMaps/hotel/<destinationCode>/<cityCode>/<hotelId>' as the description to be passed into Google Analytics
		loadHotelPropertyPopupDiv('hotelTabContent.act', 'destination=' + destination + '&cityCode=' + cityCode + '&hotelId=' + hotelId + '&htc=8' + '&allInclusive='+ allInclusive + '&optionalAllInclusive=' + optionalAllInclusive + '&showOpaqueWmode=true&loadHotelHeader=true', '/an/browse/hotelMaps/hotel/' +  destination + '/' + cityCode + '/' + hotelId);
	}else{
		//Load the hotel tab content with '/an/browse/hotelMaps/hotel/<destinationCode>/<cityCode>/<hotelId>' as the description to be passed into Google Analytics
		loadHotelTabContent('hotelTabContent.act', 'destination=' + destination + '&cityCode=' + cityCode + '&hotelId=' + hotelId + '&allInclusive='+ allInclusive + '&optionalAllInclusive=' + optionalAllInclusive + '&htc=8&showOpaqueWmode=true', '/an/browse/hotelMaps/hotel/' +  destination + '/' + cityCode + '/' + hotelId);
		document.getElementById('hotelTabContent').scrollTop = 0;
	}
}

function loadHotelOverview(destination, cityCode, hotelId) {
	//Load the hotel tab content block with '/an/browse/hotelOverview/hotel/<destinationCode>/<cityCode>/<hotelId>' as the description to be passed into Google Analytics
	loadHotelTabContent('hotelTabContent.act', 'destination=' + destination + '&cityCode=' + cityCode + '&hotelId=' + hotelId, '/an/browse/hotelOverview/hotel/' +  destination + '/' + cityCode + '/' + hotelId);
}

function loadHotelProperty(destination, cityCode, hotelId) {
	//Load the hotel tab content block with '/an/browse/hotelPropertyFeatures/hotel/<destinationCode>/<cityCode>/<hotelId>' as the description to be passed into Google Analytics
	loadHotelTabContent('hotelTabContent.act', 'destination=' + destination + '&cityCode=' + cityCode + '&hotelId=' + hotelId + '&htc=1', '/an/browse/hotelPropertyFeatures/hotel/' +  destination + '/' + cityCode + '/' + hotelId);
}

function loadHotelRooms(destination, cityCode, hotelId) {
	//Load the hotel tab content block with '/an/browse/hotelRooms/hotel/<destinationCode>/<cityCode>/<hotelId>' as the description to be passed into Google Analytics
	loadHotelTabContent('hotelTabContent.act', 'destination=' + destination + '&cityCode=' + cityCode + '&hotelId=' + hotelId + '&htc=2', '/an/browse/hotelRooms/hotel/' +  destination + '/' + cityCode + '/' + hotelId);
}

function loadHotelAllInclusive(destination, cityCode, hotelId, optionalAllInclusive) {
	//Load the hotel tab content block with '/an/browse/hotelAllInclusive/hotel/<destinationCode>/<cityCode>/<hotelId>' as the description to be passed into Google Analytics
	loadHotelTabContent('hotelTabContent.act', 'destination=' + destination + '&cityCode=' + cityCode + '&hotelId=' + hotelId + '&htc=3&optionalAllInclusive=' + optionalAllInclusive, '/an/browse/hotelAllInclusive/hotel/' +  destination + '/' + cityCode + '/' + hotelId);
}

function loadHotelPhotosMaps(destination, cityCode, hotelId) {
	//Load the hotel tab content block with '/an/browse/hotelPhotosMaps/hotel/<destinationCode>/<cityCode>/<hotelId>' as the description to be passed into Google Analytics
	loadHotelTabContent('hotelTabContent.act', 'destination=' + destination + '&cityCode=' + cityCode + '&hotelId=' + hotelId + '&htc=4', '/an/browse/hotelPhotosMaps/hotel/' +  destination + '/' + cityCode + '/' + hotelId);
}

function loadHotelMaps(destination, cityCode, hotelId) {
	//Load the hotel tab content block with '/an/browse/hotelMaps/hotel/<destinationCode>/<cityCode>/<hotelId>' as the description to be passed into Google Analytics
	loadHotelTabContent('hotelTabContent.act', 'destination=' + destination + '&cityCode=' + cityCode + '&hotelId=' + hotelId + '&htc=8', '/an/browse/hotelMaps/hotel/' +  destination + '/' + cityCode + '/' + hotelId);
}

function loadHotelPropertyFeatures(destination, cityCode, hotelId) {
	//Load the hotel tab content block with '/an/browse/hotelPropertyFeatures/hotel/<destinationCode>/<cityCode>/<hotelId>' as the description to be passed into Google Analytics
	loadHotelInnerTabContent('hotelTabContent.act', 'destination=' + destination + '&cityCode=' + cityCode + '&hotelId=' + hotelId + '&htc=5', '/an/browse/hotelPropertyFeatures/hotel/' +  destination + '/' + cityCode + '/' + hotelId);
}

function loadHotelPropertyActivities(destination, cityCode, hotelId) {
	//Load the hotel tab content block with '/an/browse/hotelPropertyActivities/hotel/<destinationCode>/<cityCode>/<hotelId>' as the description to be passed into Google Analytics
	loadHotelInnerTabContent('hotelTabContent.act', 'destination=' + destination + '&cityCode=' + cityCode + '&hotelId=' + hotelId + '&htc=6', '/an/browse/hotelPropertyActivities/hotel/' +  destination + '/' + cityCode + '/' + hotelId);
}

function loadHotelPropertyDining(destination, cityCode, hotelId) {	
	//Load the hotel tab content block with '/an/browse/hotelPropertyDining/hotel/<destinationCode>/<cityCode>/<hotelId>' as the description to be passed into Google Analytics
	loadHotelInnerTabContent('hotelTabContent.act', 'destination=' + destination + '&cityCode=' + cityCode + '&hotelId=' + hotelId + '&htc=7', '/an/browse/hotelPropertyDining/hotel/' +  destination + '/' + cityCode + '/' + hotelId);
}

function loadRightContentPackage( destination, region, area, hotelId, packageId, cityCode, ancillary, ancillaryCategory, showBackButton ) {
	var queryString = 'h=0&lbc=0&rc=3&lc=4';

	if(destination) {
		queryString += '&destination=' + destination;
	}
	if(region) {
		queryString += '&region=' + region;
	}
	if(area) {
		queryString += '&area=' + area;
	}
	if(hotelId) {
		queryString += '&hotelId=' + hotelId;
	}
	if(packageId) {
		queryString += '&packageId=' + packageId;
	}
	if(cityCode) {
		queryString += '&cityCode=' + cityCode;
	}
	if(ancillary) {
		queryString += '&ancillary=' + ancillary;
	}
	if(ancillaryCategory) {
		queryString += '&ancillaryCategory=' + ancillaryCategory;
	}
	if( showBackButton ) {
		queryString += '&showBackButton=' + showBackButton;
	}
	
	//Load the main content block with '/vp/browse/package/<packageId>' as the description to be passed into Google Analytics
	loadMainContent('mainContent.act', queryString, '/vp/browse/package/' + packageId);
	//loadDestinationTopBandImage();
	//Add the pseudo code "13_<destinationCode>_<regionCode>_<areaCode>_<hotelId>_<packageId>_<cityCode>_<ancillaryCode>_<ancillaryCategoryCode>" to browser history
	addHistory(HISTORY_LAND_PACKAGE, destination, region, area, hotelId, packageId, cityCode, ancillary, ancillaryCategory);

	//Scroll to the top of the page
	window.scrollTo(0,0);
}

function loadNextLandPackage(destination, region, area, currentPackageIndex, nextPackageId) {
	var queryString = 'h=0&lbc=0&rc=17&lc=4';

	if(destination) {
		queryString += '&destination=' + destination;
	}
	if(region) {
		queryString += '&region=' + region;
	}
	if(area) {
		queryString += '&area=' + area;
	}
	if(currentPackageIndex) {
		queryString += '&currentPackageIndex=' + currentPackageIndex;
	}
	
	//Load the right content block with '/vp/browse/package/<packageId>' as the description to be passed into Google Analytics
	loadMainContent('mainContent.act', queryString, '/vp/browse/package/' + nextPackageId);
	//Add the pseudo code "13_<destinationCode>_<regionCode>_<areaCode>_<hotelId>_<packageId>_<cityCode>_<ancillaryCode>_<ancillaryCategoryCode>" to browser history
	addHistory(HISTORY_LAND_PACKAGE, destination, region, area, '', nextPackageId);
	//Scroll to the top of the page
	window.scrollTo(0,0);
}

function loadPreviousLandPackage(destination, region, area, currentPackageIndex, previousPackageId) {
	var queryString = 'h=0&lbc=0&rc=18&lc=4';

	if(destination) {
		queryString += '&destination=' + destination;
	}
	if(region) {
		queryString += '&region=' + region;
	}
	if(area) {
		queryString += '&area=' + area;
	}
	if(currentPackageIndex) {
		queryString += '&currentPackageIndex=' + currentPackageIndex;
	}
	
	//Load the right content block with '/vp/browse/package/<packageId>' as the description to be passed into Google Analytics
	loadMainContent('mainContent.act', queryString, '/vp/browse/package/' + previousPackageId);
	//Add the pseudo code "13_<destinationCode>_<regionCode>_<areaCode>_<hotelId>_<packageId>_<cityCode>_<ancillaryCode>_<ancillaryCategoryCode>" to browser history
	addHistory(HISTORY_LAND_PACKAGE, destination, region, area, '', previousPackageId);
	//Scroll to the top of the page
	window.scrollTo(0,0);
}

function loadTourPopup(sightseeingId) {
	loadSightseeingPopup(sightseeingId, '');
}

function loadSightseeingPopup(sightseeingId, itineraryCode){
	loadSightseeingPopupDiv('sightseeingContent.act', '&sightseeingId=' + sightseeingId + '&itineraryCode=' + itineraryCode + '&sc=1');

}

function loadCruise() {
	var queryString = 'lc=7&lbc=2&rc=1&rcc=3&rruc=2&rbc=4';

	//Load the main content block with '/cr/browse/cruiseHome/' as the description to be passed into Google Analytics
	loadMainContentWithWaitingDiv('mainContent.act', queryString, '/cr/browse/cruiseHome/');
	loadDestinationTopBandImage();

	//Initialize the tab structure within bottom tab content div to display the first tab
	initializeCruiseTab();

	//Add the pseudo code "3" to browser history
	addHistory(HISTORY_CRUISE_HOME);

	//Scroll to the top of the page
	window.scrollTo(0,0);
	setSupportPhoneNumber(bookingPhoneNumber);
	varSearchMode = "Cruise";
}

function loadCruiseDestination(cruiseDestination) {
	var queryString = 'lc=7&lbc=2&rc=8&ruc=2&cruiseDestination=' + cruiseDestination;

	//Load the main content block with '/cr/browse/cruiseDest///<cruiseDestinationCode>' as the description to be passed into Google Analytics
	//The three '/' are put on purpose as place holders to retain the general format
	loadMainContent('mainContent.act', queryString, '/cr/browse/cruiseDest///' + cruiseDestination);
	loadDestinationTopBandImage();

	//Add the pseudo code "8" to browser history
	addHistory(HISTORY_CRUISE_DESTINATION_LANDING, cruiseDestination);

	//Scroll to the top of the page
	window.scrollTo(0,0);
	setSupportPhoneNumber(bookingPhoneNumber);
	varSearchMode = "Cruise";
}

function loadCruiseWhyCruise() {
	//Load the cruise tab content block with '/cr/browse/cruiseWhyCruise/' as the description to be passed into Google Analytics
	loadCruiseTabContent('cruiseTabContent.act', null, '/cr/browse/cruiseWhyCruise/');
}

function loadCruiseCruiseLines() {
	//Load the cruise tab content block with '/cr/browse/cruiseLines/' as the description to be passed into Google Analytics
	loadCruiseTabContent('cruiseTabContent.act', 'ctc=1', '/cr/browse/cruiseLines/');
}

function loadCruiseSelectingAShip() {
	//Load the cruise tab content block with '/cr/browse/cruiseSelectingAShip/' as the description to be passed into Google Analytics
	loadCruiseTabContent('cruiseTabContent.act', 'ctc=2', '/cr/browse/cruiseSelectingAShip/');
}

function loadCruiseRatings() {
	//Load the cruise tab content block with '/cr/browse/cruiseRatings/' as the description to be passed into Google Analytics
	loadCruiseTabContent('cruiseTabContent.act', 'ctc=3', '/cr/browse/cruiseRatings/');
}

function loadCruiseKnowBeforeYouGo() {
	//Load the cruise tab content block with '/cr/browse/cruiseBeforeYouGo/' as the description to be passed into Google Analytics
	loadCruiseTabContent('cruiseTabContent.act', 'ctc=4', '/cr/browse/cruiseBeforeYouGo/');
}

function loadCruiseLine(cruiseLine, ancillary, ancillaryCategory) {
	var queryString = 'lc=7&lbc=2&rc=1&rcc=4&rruc=2&rbc=5&cruiseLine=' + cruiseLine+'&selectedTab=1';

	//Load the main content block with '/cr/browse/cruiseLines/<cruiseLineCode>' as the description to be passed into Google Analytics
	loadMainContentWithWaitingDiv ( 'mainContent.act', queryString, '/cr/browse/cruiseLines/' + cruiseLine);
	loadDestinationTopBandImage();

	//Add the pseudo code "9_<cruiseLineCode>_<ancillaryCode>_<ancillaryCategoryCode>" to browser history
	addHistory(HISTORY_CRUISE_LINE_LANDING, cruiseLine, ancillary, ancillaryCategory);

	//Scroll to the top of the page
	window.scrollTo(0,0);
	setSupportPhoneNumber(bookingPhoneNumber);
	varSearchMode = "Cruise";
}

function loadCruiseShip(cruiseLine, ship, ancillary, ancillaryCategory) {
	var queryString = 'lc=7&lbc=2&rc=8&ruc=4&rbc=6&cruiseLine=' + cruiseLine + '&ship=' + ship;

	//Load the main content block with '/cr/browse/cruiseShip/<cruiseLineCode>/<cruiseShipCode>' as the description to be passed into Google Analytics
	loadMainContentWithWaitingDiv('mainContent.act', queryString, '/cr/browse/cruiseShip/' + cruiseLine + '/' + ship);
	loadDestinationTopBandImage();

	//Add the pseudo code "10_<cruiseLineCode>_<shipCode>_<ancillaryCode>_<ancillaryCategoryCode>" to browser history
	addHistory(HISTORY_CRUISE_SHIP_LANDING, cruiseLine, ship, ancillary, ancillaryCategory);

	//Initialize the tab structure within bottom tab content div to display the first tab
	initializeCruiseShipTab();

	//Scroll to the top of the page
	window.scrollTo(0,0);
	setSupportPhoneNumber(bookingPhoneNumber);
	varSearchMode = "Cruise";
}

function loadCruiseShipOverview(cruiseLine, ship) {
	//Load the cruise tab content block with '/cr/browse/cruiseShipOverview/<cruiseLineCode>/<cruiseShipCode>' as the description to be passed into Google Analytics
	loadCruiseTabContent('cruiseTabContent.act', 'ctc=5&cruiseLine=' + cruiseLine + '&ship=' + ship, '/cr/browse/cruiseShipOverview/' + cruiseLine + '/' + ship);
}

function loadCruiseShipActivitiesAndEntertainment(cruiseLine, ship) {
	//Load the cruise tab content block with '/cr/browse/cruiseActivitiesAndEntertainment/<cruiseLineCode>/<cruiseShipCode>' as the description to be passed into Google Analytics
	loadCruiseTabContent('cruiseTabContent.act', 'ctc=6&cruiseLine=' + cruiseLine + '&ship=' + ship, '/cr/browse/cruiseActivitiesAndEntertainment/' + cruiseLine + '/' + ship);
}

function loadCruiseShipDining(cruiseLine, ship) {
	//Load the cruise tab content block with '/cr/browse/cruiseDining/<cruiseLineCode>/<cruiseShipCode>' as the description to be passed into Google Analytics
	loadCruiseTabContent('cruiseTabContent.act', 'ctc=7&cruiseLine=' + cruiseLine + '&ship=' + ship, '/cr/browse/cruiseDining/' + cruiseLine + '/' + ship);
}

function loadCruiseShipAllInclusive(cruiseLine, ship) {
	//Load the cruise tab content block with '/cr/browse/cruiseAllInclusive/<cruiseLineCode>/<cruiseShipCode>' as the description to be passed into Google Analytics
	loadCruiseTabContent('cruiseTabContent.act', 'ctc=8&cruiseLine=' + cruiseLine + '&ship=' + ship, '/cr/browse/cruiseAllInclusive/' + cruiseLine + '/' + ship);
}

function loadCruiseShipDeckPlan(cruiseLine, ship) {
	//Load the cruise tab content block with '/cr/browse/cruiseDeckPlan/<cruiseLineCode>/<cruiseShipCode>' as the description to be passed into Google Analytics
	loadCruiseTabContent('cruiseTabContent.act', 'ctc=9&cruiseLine=' + cruiseLine + '&ship=' + ship, '/cr/browse/cruiseDeckPlan/' + cruiseLine + '/' + ship);
}

function loadCruiseShipStateroom(cruiseLine, ship) {
	//Load the cruise tab content block with '/cr/browse/cruiseStateroom/<cruiseLineCode>/<cruiseShipCode>' as the description to be passed into Google Analytics
	loadCruiseTabContent('cruiseTabContent.act', 'ctc=10&cruiseLine=' + cruiseLine + '&ship=' + ship, '/cr/browse/cruiseStateroom/' + cruiseLine + '/' + ship);
}

function loadRightContentCruisePackage(cruiseLine, ship, packageId, ancillary, ancillaryCategory, cruiseDestination) {
	var queryString = 'h=0&lc=7&lbc=2&rc=4';
	
	if(cruiseLine) {
		queryString += '&cruiseLine=' + cruiseLine;
	}
	if(ship) {
		queryString += '&ship=' + ship;
	}
	if(packageId) {
		queryString += '&packageId=' + packageId;
	}
	if(ancillary) {
		queryString += '&ancillary=' + ancillary;
	}
	if(ancillaryCategory) {
		queryString += '&ancillaryCategory=' + ancillaryCategory;
	}
	if(cruiseDestination) {
		queryString += '&cruiseDestination=' + cruiseDestination;
	}
	
	//Load the right content block with '/cr/browse/cruisePackage////<packageId>' as the description to be passed into Google Analytics
	//The three '/' are put on purpose as place holders to retain the general format
	loadMainContent('mainContent.act', queryString, '/cr/browse/cruisePackage////' + packageId);
	//Add the pseudo code "14_<cruiseLineCode>_<shipCode>_<packageId>_<ancillaryCode>_<ancillaryCategoryCode>" to browser history
	addHistory(HISTORY_CRUISE_PACKAGE, cruiseLine, ship, packageId, ancillary, ancillaryCategory);

	//Scroll to the top of the page
	window.scrollTo(0,0);
}

function loadNextCruisePackage(cruiseDestination, cruiseLine, currentPackageIndex, nextPackageId) {
	var queryString = 'h=0&lbc=0&rc=19';

	if(cruiseDestination) {
		queryString += '&cruiseDestination=' + cruiseDestination;
	}
	if(cruiseLine) {
		queryString += '&cruiseLine=' + cruiseLine;
	}
	if(currentPackageIndex) {
		queryString += '&currentPackageIndex=' + currentPackageIndex;
	}
	
	//Load the right content block with '/cr/browse/cruisePackage////<packageId>' as the description to be passed into Google Analytics
	//The three '/' are put on purpose as place holders to retain the general format
	loadMainContent('mainContent.act', queryString,  '/cr/browse/cruisePackage////' + nextPackageId);
	//Add the pseudo code "14_<cruiseLineCode>_<shipCode>_<packageId>_<ancillaryCode>_<ancillaryCategoryCode>" to browser history
	addHistory(HISTORY_CRUISE_PACKAGE, cruiseLine, null, nextPackageId);
	//Scroll to the top of the page
	window.scrollTo(0,0);
}

function loadPreviousCruisePackage(cruiseDestination, cruiseLine, currentPackageIndex, nextPackageId) {
	var queryString = 'h=0&lbc=0&rc=20';

	if(cruiseDestination) {
		queryString += '&cruiseDestination=' + cruiseDestination;
	}
	if(cruiseLine) {
		queryString += '&cruiseLine=' + cruiseLine;
	}
	if(currentPackageIndex) {
		queryString += '&currentPackageIndex=' + currentPackageIndex;
	}
	
	//Load the right content block with '/cr/browse/cruisePackage////<packageId>' as the description to be passed into Google Analytics
	//The three '/' are put on purpose as place holders to retain the general format
	loadMainContent('mainContent.act', queryString, '/cr/browse/cruisePackage////' + nextPackageId);
	//Add the pseudo code "14_<cruiseLineCode>_<shipCode>_<packageId>_<ancillaryCode>_<ancillaryCategoryCode>" to browser history
	addHistory(HISTORY_CRUISE_PACKAGE, cruiseLine, null, nextPackageId);
	//Scroll to the top of the page
	window.scrollTo(0,0);
}

function loadAncillaryHome() {
	var queryString = '';

	if (varSearchMode == "Cruise"){
		queryString = 'lc=7&lbc=2';
	}
	else {
		queryString = 'lbc=0';
	}
	
	queryString += '&rc=8&ruc=1';

	//Load the main content block with '/an/browse/ancillaryHome/' as the description to be passed into Google Analytics
	loadMainContent('mainContent.act', queryString, '/an/browse/ancillaryHome/');
	loadDestinationTopBandImage();

	//Add the pseudo code "4" to browser history
	addHistory(HISTORY_ANCILLARY_HOME);

	//Scroll to the top of the page
	window.scrollTo(0,0);
	setSupportPhoneNumber(bookingPhoneNumber);
}

function loadAncillary(ancillary, searchMode) {
	var queryString = ''; 
	var trackingText;
	
	if (searchMode){
		varSearchMode = searchMode;
	}	

	if (varSearchMode == "Cruise"){
		queryString = 'lc=7&lbc=2';
	}
	else {
		queryString = 'lbc=0';
	}

	queryString += '&rc=6&ancillary=' + ancillary;
	
	if (ancillary == 'rentalCars'){
		//Load the main content block with '/rc/browse/rentalCarsHome/' as the description to be passed into Google Analytics
		trackingText = '/rc/browse/rentalCarsHome/';
	}	
	else{
		//Load the main content block with '/an/browse/ancillaryID//<ancillaryCode>' as the description to be passed into Google Analytics
		//The two '/' are put on purpose as place holders to retain the general format
		trackingText = 	'/an/browse/ancillaryID//' + ancillary;
	}	

	loadMainContent('mainContent.act', queryString, trackingText);
	loadDestinationTopBandImage();

	//Add the pseudo code "11_<ancillaryCode>" to browser history
	addHistory(HISTORY_ANCILLARY_LANDING, ancillary);

	//Scroll to the top of the page
	window.scrollTo(0,0);
	setSupportPhoneNumber(bookingPhoneNumber);
}

function loadAncillaryCategory(ancillary, ancillaryCategory, searchMode) {
	var queryString = '';
	var trackingText;

	if (searchMode){
		varSearchMode = searchMode; 
	}	
	
	if (varSearchMode == "Cruise"){
		queryString = 'lc=7&lbc=2';
	}
	else {
		queryString = 'lbc=0';
	}
	
	queryString += '&rc=7&ancillary=' + ancillary + '&ancillaryCategory=' + ancillaryCategory;
	
	if (ancillary == 'rentalCars'){
		//Load the main content block with '/rc/browse/rentalCarsBrand/' as the description to be passed into Google Analytics
		trackingText = '/rc/browse/rentalCarsBrand/' + ancillaryCategory;
	}	
	else{
		//Load the main content block with '/an/browse/ancillaryCategory//<ancillaryCode>/<ancillaryCategoryCode>' as the description to be passed into Google Analytics
		//The two '/' are put on purpose as place holders to retain the general format
		trackingText = '/an/browse/ancillaryCategory//' + ancillary + '/' + ancillaryCategory;
	}
	loadMainContent('mainContent.act', queryString, trackingText );
	loadDestinationTopBandImage();

	//Add the pseudo code "12_<ancillaryCode>_<ancillaryCategoryCode>" to browser history
	addHistory(HISTORY_ANCILLARY_CATEGORY_LANDING, ancillary, ancillaryCategory);

	//Scroll to the top of the page
	window.scrollTo(0,0);
	setSupportPhoneNumber(bookingPhoneNumber);
}

function loadRightContentAncillaryPackage(ancillary, ancillaryCategory, packageId) {
	var queryString = 'h=0';
	var trackingText;
	
	if (varSearchMode == "Cruise"){
		queryString += '&lc=7&lbc=2&rc=5';
	}
	else {
		queryString += '&lbc=0&rc=5';
	}

	
	if(ancillary) {
		queryString += '&ancillary=' + ancillary;
	}
	if(ancillaryCategory) {
		queryString += '&ancillaryCategory=' + ancillaryCategory;
	}
	if(packageId) {
		queryString += '&packageId=' + packageId;
	}
	
	if (ancillary == 'rentalCars'){
		//Load the main content block with '/rc/browse/rentalCarsOffer/<brand>/<packageId>' as the description to be passed into Google Analytics
		trackingText = '/rc/browse/rentalCarsOffer/' + ancillaryCategory + '/' + packageId;
	}	
	else{
		//Load the main content block with '/an/browse/ancillaryPackage//<packageId>' as the description to be passed into Google Analytics
		//The two '/' are put on purpose as place holders to retain the general format
		trackingText = '/an/browse/ancillaryPackage//' + packageId;
	}	
	loadMainContent('mainContent.act', queryString, trackingText);
	//Add the pseudo code "15_<ancillaryCode>_<ancillaryCategoryCode>_<packageId>" to browser history
	addHistory(HISTORY_ANCILLARY_PACKAGE, ancillary, ancillaryCategory, packageId);

	//Scroll to the top of the page
	window.scrollTo(0,0);
}

function loadBlastOffer(blastId) {
	var queryString = 'lbc=0&rc=8&ruc=3&blastId=' + blastId;

	//Load the main content block with '/em/email/blastOffer/<blastId>' as the description to be passed into Google Analytics
	loadMainContent('mainContent.act', queryString, '/em/email/blastOffer/' + blastId);
	loadDestinationTopBandImage();

	//Add the pseudo code "20_<blastId>" to browser history
	addHistory(HISTORY_BLAST_OFFER_LANDING, blastId);

	//Scroll to the top of the page
	window.scrollTo(0,0);
}

function loadSweepstakes(sweepstakesCode) {
	var queryString = 'lbc=3&rc=22&sweepstakesCode=' + sweepstakesCode;
	//Load the main content block with '/gi/generalInfo/sweepstakes/<sweepstakesCode>' as the description to be passed into Google Analytics
	loadMainContent('mainContent.act', queryString, '/gi/generalInfo/sweepstakes/' + sweepstakesCode);
	loadDestinationTopBandImage();
	
	//Add the pseudo code "21_<sweepstakesCode>" to browser history
	addHistory(HISTORY_SWEEPSTAKES_LANDING, sweepstakesCode);

	
	//Scroll to the top of the page
	window.scrollTo(0,0);
}

function loadGeneralInfo(generalInfoPath) {
	var queryString = '';
	
	if (varSearchMode == 'Cruise'){
		queryString += 'lc=7&lbc=2&';
	}	
	
	queryString += 'rc=9&giPath=' + generalInfoPath;

	//Load the right content block with '/gi/generalInfo/<generalInfoPath>/' as the description to be passed into Google Analytics
	loadMainContent('mainContent.act', queryString, '/gi/generalInfo/' + generalInfoPath);
	loadDestinationTopBandImage();

	//Add the pseudo code "18_<generalInfoPath>" to browser history
	addHistory(HISTORY_GENERAL_INFO, generalInfoPath);

	//Scroll to the top of the page
	window.scrollTo(0,0);
	setSupportPhoneNumber(bookingPhoneNumber);
}

function loadSiteMap() {
	var queryString = 'rc=10';

	//Load the right content block with '/gi/generalInfo/siteMap/' as the description to be passed into Google Analytics
	loadMainContent('mainContent.act', queryString, '/gi/generalInfo/siteMap/');
	loadDestinationTopBandImage();

	//Add the pseudo code "19" to browser history
	addHistory(HISTORY_SITE_MAP);

	//Scroll to the top of the page
	window.scrollTo(0,0);
	setSupportPhoneNumber(bookingPhoneNumber);
}

function loadExternalUrl(url) {
	if(confirm("Please note: The link you have selected will direct you to a provider's site.\nPlease review the Privacy Policy of that site, as it may differ from Costco Travel's.")) {
		pageTracker._trackPageview('home/externalUrl/' + url);
		window.open(url);
		return true;
	}
	else {
		return false;
	}
}
function loadMainContent(mainContentUrl, mainContentUrlQueryString, trackingText) {
	makeAjaxCall(mainContentUrl, mainContentUrlQueryString, null, 'mainContent', 'callbackLoadMainContent', trackingText);
}

function callbackLoadMainContent() {
	document.title = "Costco Travel";
}

function loadLeftContent(leftContentUrl, leftContentUrlQueryString) {
	makeAjaxCall(leftContentUrl, leftContentUrlQueryString, null, 'leftContent', 'callbackLoadLeftContent');
}

function callbackLoadLeftContent() {
	document.title = "Costco Travel";
}

function loadRightContent(rightContentUrl, rightContentUrlQueryString, trackingText) {
	makeAjaxCall(rightContentUrl, rightContentUrlQueryString, null, 'rightContent', 'callbackLoadRightContent', trackingText);
}

function callbackLoadRightContent() {
	document.title = "Costco Travel";
}

function loadLeftBottomContent(leftBottomContentUrl, leftBottomContentUrlQueryString, trackingText) {
	makeAjaxCall(leftBottomContentUrl, leftBottomContentUrlQueryString, null, 'leftBottomContent', 'callbackLoadLeftBottomContent', trackingText);
}

function callbackLoadLeftBottomContent() {
	document.title = "Costco Travel";
}

function loadRightAndLeftBottomContent(rightContentUrl, rightContentUrlQueryString, rightContentTrackingText, leftBottomContentUrl, leftBottomContentUrlQueryString, leftBottomContentTrackingText) {
	makeMultiAjaxCall(new Array(
								new AsynchronousMultiRequestItem(rightContentUrl, rightContentUrlQueryString, null, "rightContent", "callbackLoadRightContent", null, rightContentTrackingText),
								new AsynchronousMultiRequestItem(leftBottomContentUrl, leftBottomContentUrlQueryString, null, "leftBottomContent", "callbackLoadLeftBottomContent", null, leftBottomContentTrackingText)
							   )
					 );			
}

function loadVacationTabContent(vacationTabContentUrl, vacationTabContentUrlQueryString, trackingText) {
	makeAjaxCall(vacationTabContentUrl, vacationTabContentUrlQueryString, null, 'vacationTabContent', 'callbackLoadVacationTabContent', trackingText);
}

function callbackLoadVacationTabContent() {
	document.title = "Costco Travel";
}

function loadHotelPropertyPopupDiv(hotelTabContentUrl, hotelTabContentUrlQueryString, trackingText) {
	var hotelPropertyPopupDiv = document.getElementById('hotelPropertyPopupDiv');
	if(hotelPropertyPopupDiv == null){
		hotelPropertyPopupDiv = createPopupDiv('hotelPropertyPopupDiv', 0, 0, 700, 200, false, true,  "tal popupDivBig")
	}
	makeAjaxCall(hotelTabContentUrl, hotelTabContentUrlQueryString, null, 'hotelPropertyPopupDiv', 'callbackLoadHotelPropertyDiv', trackingText);
}

function callbackLoadHotelPropertyDiv() {
	document.title = "Costco Travel";	
	showBlock('hotelPropertyPopupDiv'); 
	positionBlockCentrally('hotelPropertyPopupDiv'); 
	disableElement( 'dataContent', true );
}

function loadSightseeingPopupDiv(sightseeingContentUrl, sightseeingContentUrlQueryString, trackingText) {
	var sightseeingPopupDiv = document.getElementById('sightseeingPopupDiv');
	if(sightseeingPopupDiv == null){
		sightseeingPopupDiv = createPopupDiv('sightseeingPopupDiv', 0, 0, 700, 200, false, true,  "tal popupDivBig")
	}
	makeAjaxCall(sightseeingContentUrl, sightseeingContentUrlQueryString, null, 'sightseeingPopupDiv', 'callbackLoadSightseeingPopupDiv', trackingText);
}

function callbackLoadSightseeingPopupDiv() {
	document.title = "Costco Travel";	
	showBlock('sightseeingPopupDiv'); 
	positionBlockCentrally('sightseeingPopupDiv'); 
	document.getElementById('sightseeingPopupContentDiv').scrollTop = 0;
	disableElement( 'dataContent', true );
}

function loadHotelTabContent(hotelTabContentUrl, hotelTabContentUrlQueryString, trackingText) {
	makeAjaxCall(hotelTabContentUrl, hotelTabContentUrlQueryString, null, 'hotelTabContent', 'callbackLoadHotelTabContent', trackingText);
}

function callbackLoadHotelTabContent() {
	document.title = "Costco Travel";	
}

function loadHotelInnerTabContent(hotelInnerTabContentUrl, hotelInnerTabContentUrlQueryString, trackingText) {
	makeAjaxCall(hotelInnerTabContentUrl, hotelInnerTabContentUrlQueryString, null, 'hotelInnerTabContent', 'callbackLoadHotelInnerTabContent', trackingText);
}

function callbackLoadHotelInnerTabContent() {
	document.title = "Costco Travel";
}

function loadCruiseTabContent(cruiseTabContentUrl, cruiseTabContentUrlQueryString, trackingText) {
	makeAjaxCall(cruiseTabContentUrl, cruiseTabContentUrlQueryString, null, 'cruiseTabContent', 'callbackLoadCruiseTabContent', trackingText);
}

function callbackLoadCruiseTabContent() {
	document.title = "Costco Travel";
}

function loadDefaultPage() {
	var uidQueryString = "&uid=" + UID();
	var asynchronousRequest = new AsynchronousRequest();
	asynchronousRequest.url = _webLoc + '/mainContent.act';
	asynchronousRequest.queryString = uidQueryString;
	asynchronousRequest.useAjax = true;
	asynchronousRequest.target = 'mainContent';
	asynchronousRequest.callbackFunctionName = 'callbackLoadDefaultPage';

	submitWithoutReload(asynchronousRequest);
}

function callbackLoadDefaultPage() {
	loadDestinationTopBandImage();	
	//Scroll to the top of the page
	window.scrollTo(0,0);
	setSupportPhoneNumber(bookingPhoneNumber);
}

function reloadSession() {
	var uidQueryString = "&uid=" + UID();
	var asynchronousRequest = new AsynchronousRequest();
	asynchronousRequest.url = _webLoc + '/mainContent.act';
	asynchronousRequest.queryString = uidQueryString;
	asynchronousRequest.useAjax = true;
	asynchronousRequest.target = 'mainContent';
	asynchronousRequest.callbackFunctionName = 'callbackReloadSession';

	submitWithoutReload(asynchronousRequest);
}

function callbackReloadSession() {
	showErrorMessage('Your session has timed out. Please begin your search again.', 'dataContent');
	loadDestinationTopBandImage();	
	//Scroll to the top of the page
	window.scrollTo(0,0);
	setSupportPhoneNumber(bookingPhoneNumber);
}

function makeAjaxCall(url, queryString, paramArray, target, callbackFunctionName, trackingText, jsParamArray ) {
	var uidQueryString = "&uid=" + UID();
	var asynchronousRequest = new AsynchronousRequest();
	asynchronousRequest.url = _webLoc + '/' + url;
	asynchronousRequest.queryString = queryString + uidQueryString;
	asynchronousRequest.paramArray = paramArray;
	asynchronousRequest.useAjax = true;
	asynchronousRequest.target = target;
	asynchronousRequest.callbackFunctionName = callbackFunctionName;
	asynchronousRequest.callbackFunctionParams = jsParamArray;
	
	if(trackingText && (trackingText != '')) {
		asynchronousRequest.postCallbackScript = "pageTracker._trackPageview('" + trackingText + "')";
	}
		
	
	submitWithoutReload(asynchronousRequest);
}

function makeAjaxCallWithWaitingDiv(url, queryString, paramArray, target, callbackFunctionName, jsParamArray, trackingText, splashScreenText) {
    var uidQueryString = "&uid=" + UID();
	var asynchronousRequest = new AsynchronousRequest();
	asynchronousRequest.url = _webLoc + '/' + url;
	asynchronousRequest.queryString = queryString + uidQueryString;
	asynchronousRequest.paramArray = paramArray;
	asynchronousRequest.useAjax = true;
	asynchronousRequest.target = target;
	asynchronousRequest.callbackFunctionName = callbackFunctionName;
	asynchronousRequest.callbackFunctionParams = jsParamArray;
	
	if(trackingText && (trackingText != '')) {
		asynchronousRequest.postCallbackScript = "pageTracker._trackPageview('" + trackingText + "')";
	}
	
    var splashScreenRequest = new SplashScreenRequest();
    if(splashScreenText && splashScreenText!= "") {
        splashScreenRequest.splashScreenText = splashScreenText;        
    }else {
	   splashScreenRequest.splashScreenText = "Please Wait...";
    }
	asynchronousRequest.splashScreenRequest = splashScreenRequest;
	asynchronousRequest.splashScreenDisplayFunctionName = "displaySearchingPopup";
	asynchronousRequest.splashScreenHideFunctionName = "hideSearchingPopup";	
	submitWithoutReload(asynchronousRequest);
} 


function makeAjaxCallWithRequest(asynchronousRequest, trackingText) {
	var uidQueryString = "&uid=" + UID();
	if(asynchronousRequest != null) {
		asynchronousRequest.queryString = asynchronousRequest.queryString + uidQueryString;

		if(trackingText && (trackingText != '')) {
			asynchronousRequest.postCallbackScript = "pageTracker._trackPageview('" + trackingText + "')";
		}
		
		submitWithoutReload(asynchronousRequest);
	}
}

function makeMultiAjaxCall(requestItems, showSplashScreen, splashScreenText) {
	if(requestItems && requestItems.length) {		
		var asynchronousMultiRequestItems = new Array();
		for(var i=0; i<requestItems.length; i++) {
			var asynchronousMultiRequestItem = requestItems[i];
			if(asynchronousMultiRequestItem.url) {		
				if(!asynchronousMultiRequestItem.queryString) {
					asynchronousMultiRequestItem.queryString = "";
				}else {
					asynchronousMultiRequestItem.queryString = escape(asynchronousMultiRequestItem.queryString);
				}
				
				if(!asynchronousMultiRequestItem.paramArray) {				
					asynchronousMultiRequestItem.paramArray = new Array();
				}
							
				if( asynchronousMultiRequestItem.trackingText && asynchronousMultiRequestItem.trackingText != "" ) {
					asynchronousMultiRequestItem.postCallbackScript = "pageTracker._trackPageview('" + asynchronousMultiRequestItem.trackingText + "')";
				}
				asynchronousMultiRequestItems.push(asynchronousMultiRequestItem)
			}
		}
		
		if(asynchronousMultiRequestItems.length > 0) {
			var uidQueryString = "&uid=" + UID();
			var asynchronousRequest = new AsynchronousRequest();
			asynchronousRequest.url = _webLoc + '/' + 'multiRequestDispatcher.act';
			asynchronousRequest.queryString = 'requestString=' + asynchronousMultiRequestItems.toJSONString() + uidQueryString;
			asynchronousRequest.useAjax = true;
			asynchronousRequest.callbackFunctionName = 'callbackMakeMultiAjaxCall';
			asynchronousRequest.callbackFunctionParams = new Array(asynchronousMultiRequestItems);
			
			if(showSplashScreen == true) {
				var splashScreenRequest = new SplashScreenRequest();
			    if(splashScreenText && splashScreenText!= "") {
			        splashScreenRequest.splashScreenText = splashScreenText;        
			    }else {
				   splashScreenRequest.splashScreenText = "Please Wait...";
			    }
				asynchronousRequest.splashScreenRequest = splashScreenRequest;
				asynchronousRequest.splashScreenDisplayFunctionName = "displaySearchingPopup";
				asynchronousRequest.splashScreenHideFunctionName = "hideSearchingPopup";
			}
			submitWithoutReload(asynchronousRequest);
		}
	}
}

function callbackMakeMultiAjaxCall(asynchronousMultiRequestItems) {
	var responseText = this.responseText;
	for(var i=0; i<asynchronousMultiRequestItems.length; i++) {
		var asynchronousMultiRequestItem = asynchronousMultiRequestItems[i];
		var lengthSepPos = responseText.indexOf("::");
		var length = parseInt(responseText.substring(0, lengthSepPos));
		var response = responseText.substr(lengthSepPos+2, length);
		responseText = responseText.substring(length + lengthSepPos+2);
		
		if(asynchronousMultiRequestItem.target && asynchronousMultiRequestItem.target != '') {
			_populateDiv(response, asynchronousMultiRequestItem.target);
		}
		
		var callbackFunctionParams = "";
		if(asynchronousMultiRequestItem.callbackFunctionParams) {
			for(var j =0; j< asynchronousMultiRequestItem.callbackFunctionParams.length; j++) {
				callbackFunctionParams = callbackFunctionParams + "asynchronousMultiRequestItem.callbackFunctionParams[" + j + "]";
				if(j < asynchronousMultiRequestItem.callbackFunctionParams.length -1) {
					callbackFunctionParams += ", ";			
				}
			}
		}
		
		if( asynchronousMultiRequestItem.callbackFunctionName != null && asynchronousMultiRequestItem.callbackFunctionName != "") {
			try {
				var callbackObject = {};
				callbackObject.responseText = response;
				eval("callbackObject.callbackFunction = " + asynchronousMultiRequestItem.callbackFunctionName );
				eval("callbackObject.callbackFunction" + "(" + callbackFunctionParams + ")");
			}
			catch(exception) {
			}				
		}
					
		postCallbackScript = asynchronousMultiRequestItem.postCallbackScript;
		if(postCallbackScript && (postCallbackScript != '')) {
			eval(postCallbackScript);
		}
	}
}

function trackPage(trackingText) {
	pageTracker._trackPageview(trackingText);
}

function loadDestinationTopBandImage(imageCode) {
	/*var topBandImage1 = document.getElementById("topBandImage_1");
	var topBandImage2 = document.getElementById("topBandImage_2");
	var topBandImage3 = document.getElementById("topBandImage_3");
	var topBandImage4 = document.getElementById("topBandImage_4");
	
	if(!imageCode) {
		imageCode = "common";
	}

	topBandImage1.src = _webLoc + "/shared/images/topBand/" + imageCode + "_01.jpg";
	topBandImage2.src = _webLoc + "/shared/images/topBand/" + imageCode + "_02.jpg";
	topBandImage3.src = _webLoc + "/shared/images/topBand/" + imageCode + "_03.jpg";
	topBandImage4.src = _webLoc + "/shared/images/topBand/" + imageCode + "_04.jpg";*/
}

function addDefaultHistory() {
	var location = window.location.toString();
	var locationTokens = location.split("#");
	if(locationTokens && (locationTokens.length == 1 || locationTokens[1] == HISTORY_LANDING_URL)) {
		//Set the first landing page as default history, so the first click on browser back button always
		//takes the user back to the landing page
		addHistoryWithData(HISTORY_LANDING_URL, window.location.toString());
	}	
}

function windowOnLoad() {
	//initialize pageHistory object
	window.pageHistory.initialize();
	
	//subscribe browser history change events
	window.pageHistory.registerListener(historyChange);
	
	var location = window.location.toString();
	var locationTokens = location.split("#");
	if(locationTokens) {
		if(locationTokens.length > 1) {
			historyChange(locationTokens[locationTokens.length - 1]);
		}
		addDefaultHistory();
	}
	loadBackground();		
}
			
function addHistory(historyCode) {
	var location = historyCode;
	if(arguments.length > 1) {
		for(var index = 1; index < arguments.length; ++index) {
			location += "_";
			if(arguments[index]) {
				location += arguments[index];
			}
		}
	}
	window.pageHistory.push(location);
}
	
function addHistoryWithData(historyCode, historyStorageData) {
	var location = historyCode;
	if(arguments.length > 2) {
		for(var index = 2; index < arguments.length; ++index) {
			location += "_";
			if(arguments[index]) {
				location += arguments[index];
			}
		}
	}
	
	window.pageHistory.push(location);

	window.pageHistory.store(location + "_storage", historyStorageData);
}			

function historyChange(newLocation, historyData) {
	var tokens;
	
	if(newLocation == '') {
		//loadHomePage();
		return;
	}
	
	if(newLocation) {
		tokens = newLocation.split('_');
	}
	
	if(tokens) {
		var historyCode = parseInt(tokens[0]);
		var storageData = window.pageHistory.getStorage(newLocation + "_storage");
		switch(historyCode) {
			case HISTORY_LANDING_URL: {
				if(storageData) {
					window.location.href = storageData;
					if(is.chrome || is.safari) {
						window.location.reload();
					}
				}
				break;
			}
			case HISTORY_HOME: {
				loadHomePage();
				break;
			}
			case HISTORY_DESTINATION_HOME: {
				loadDestinationHome();
				break;
			}
			case HISTORY_DESTINATION_LANDING: {
				loadDestination(tokens[1]);
				break;
			}
			case HISTORY_REGION_LANDING: {
				loadRegion(tokens[1], tokens[2]);
				break;
			}
			case HISTORY_AREA_LANDING: {
				loadArea(tokens[1], tokens[2], tokens[3]);
				break;
			}
			case HISTORY_CRUISE_HOME: {
				loadCruise();
				break;
			}
			case HISTORY_CRUISE_DESTINATION_LANDING: {
				loadCruiseDestination(tokens[1]);
				break;
			}
			case HISTORY_CRUISE_LINE_LANDING: {
				loadCruiseLine(tokens[1]);
				break;
			}
			case HISTORY_CRUISE_SHIP_LANDING: {
				loadCruiseShip(tokens[1], tokens[2]);
				break;
			}
			case HISTORY_ANCILLARY_HOME: {
				loadAncillaryHome();
				break;
			}
			case HISTORY_ANCILLARY_LANDING: {
				loadAncillary(tokens[1]);
				break;
			}
			case HISTORY_ANCILLARY_CATEGORY_LANDING: {
				loadAncillaryCategory(tokens[1], tokens[2]);
				break;
			}
			case HISTORY_LAND_PACKAGE: {
				loadRightContentPackage(tokens[1], tokens[2], tokens[3], tokens[4], tokens[5], tokens[6], tokens[7], tokens[8], false);
				break;
			}
			case HISTORY_CRUISE_PACKAGE: {
				loadRightContentCruisePackage(tokens[1], tokens[2], tokens[3], tokens[4], tokens[5]);
				break;
			}
			case HISTORY_ANCILLARY_PACKAGE: {
				loadRightContentAncillaryPackage(tokens[1], tokens[2], tokens[3]);
				break;
			}
			case HISTORY_HOTEL: {
				loadHotel(tokens[1], tokens[2], tokens[3], tokens[4], tokens[5], tokens[6]);
				break;
			}
			case HISTORY_RIGHT_CONTENT_HOTEL: {
				loadRightContentHotel(tokens[1], tokens[2], tokens[3], tokens[4], tokens[5], tokens[6]);
				break;
			}
			case HISTORY_GENERAL_INFO: {
				loadGeneralInfo(tokens[1]);
				break;
			}
			case HISTORY_SITE_MAP: {
				loadSiteMap();
				break;
			}
			case HISTORY_BLAST_OFFER_LANDING: {
				loadBlastOffer(tokens[1]);
				break;
			}
			case HISTORY_SWEEPSTAKES_LANDING: {
				loadSweepstakes(tokens[1]);
				break;
			}
			case HISTORY_SEARCH_RESULT_ALL_PACKAGES: {
				if(storageData) {
					searchAllPackagesForDestinationAndRegion(storageData.queryString, storageData.showSplashScreen);
				}
				else {
					reLoadPackageResults();
				}
				break;
			}
			case HISTORY_SEARCH_RESULT_PACKAGE_FLIGHT_HOTEL: {
				loadSearchResults_1();
				break;
			}
			case HISTORY_SEARCH_RESULT_PACKAGE_TRANSPORTATION: {
				loadSearchResults_2();
				break;
			}
			case HISTORY_BOOKING_RECAP: {
				loadBookingRecap();
				break;
			}
			case HISTORY_PASSENGER_DETAILS: {
				loadPassengerInformation();
				break;
			}
			case HISTORY_SPECIAL_REQUESTS: {
				loadSpecialRequests();
				break;
			}
			case HISTORY_SEAT_MAP_SELECTION: {
				loadFlightSeatMapForBooking();
				break;
			}
			case HISTORY_PAYMENT: {
				loadPaymentInformation();
				break;
			}
			case HISTORY_PAYMENT_SUMMARY: {
				loadPaymentConfirmation();
				break;
			}
			case HISTORY_BALANCE_PAYMENT: {
			    loadBalancePayment();
			    break;
			}
			case HISTORY_BALANCE_PAYMENT_SUMMARY: {
			    loadBalancePaymentConfirmation();
			    break;
			}
			case HISTORY_ORDER_CONFIRMATION: {
				if(storageData) {
					loadBooking(storageData.bookingId);
				}
				else {
					loadBooking('');
				}
				break;
			}
			case HISTORY_CRUISE_SAILING_SEARCH_RESULTS : { 
				loadCruiseResults();
				break;
			}
			case HISTORY_CRUISE_PASSENGER_INFO : {
				reLoadCruisePassengerDetailPage();
				break;
			}
			case HISTORY_CRUISE_CATEGORY_RESULTS : {
				reLoadCruiseCategoryResults();
				break;
			}
			case HISTORY_CRUISE_CABIN_RESULTS : {
				if( storageData && ( storageData.cruiseCategoryItemUid ) ) {
					reLoadCruiseCabinResults( storageData.cruiseCategoryItemUid );
				} else {
					reLoadCruiseCabinResults();
				}
				break;
			}
			case HISTORY_CRUISE_PASSENGER_DETAILS : {
				reLoadCruisePassengerDetails();
				break;
			}
			case HISTORY_CRUISE_SPECIAL_REQUESTS : {
				reLoadCruiseSpecialRequests();
				break;
			}
			case HISTORY_CRUISE_BOOKING_RECAP : {
				loadBookingRecapPage();
				break;
			}
			case HISTORY_CRUISE_BOOKING_CONFIRMATION : {
				if(storageData) {
					loadBooking(storageData.bookingId);
				}
				else {
					loadBooking('');
				}
				break;
			}
		}
	}
	document.title = "Costco Travel";
}

function displayGenTermsConditions() {
	document.getElementById( "displayGenTermsConditionsDiv" ).style.display = "block"; 
	document.getElementById( "displayEuroTermsConditionsDiv" ).style.display = "none";
}

function displayEuroTermsConditions() {
	document.getElementById( "displayGenTermsConditionsDiv" ).style.display = "none"; 
	document.getElementById( "displayEuroTermsConditionsDiv" ).style.display = "block";
}

function landMarkOnClick(target) {
	eval(target);
}

function loadMainContentWithWaitingDiv(mainContentUrl, mainContentUrlQueryString, trackingText) {
	disableElement ( 'dataContent' , true );
	makeAjaxCallWithWaitingDiv( mainContentUrl, mainContentUrlQueryString, null, 'mainContent', 'callbackLoadMainContentWithWaitingDiv',null,trackingText  );
}

function callbackLoadMainContentWithWaitingDiv(){
	disableElement ( 'dataContent' , false );
	document.title = "Costco Travel";
}

/*
	Keep the following as the last entry in this file. Add all functions above this comment
*/

window.onload = windowOnLoad;

function HotelInfo() {
	this.hotelId = "";
	this.hotelName = "";
	this.rating = "";
	this.cityCode = "";
	this.hasOffer = false;
	this.displayMode = 0;
	this.marker = "";
}

function displayHotelResults() {
	var hotelsTableDiv = document.getElementById("hotelsTableDiv");
	var innerHTML = "<table border=\"0\" width=\"100%\" cellspacing=\"0\" cellpadding=\"2\" class=\"fs11\">";
	var allHotels = new Array(2);
	allHotels[0] = markedHotelInfos;
	allHotels[1] = unMarkedHotelInfos;
	
	if(hotelsTableDiv != null && hotelsTableDiv != 'undefined') {
		for(var hotelsIndex = 0; hotelsIndex < 2; ++hotelsIndex) {
			if(allHotels[hotelsIndex] && allHotels[hotelsIndex].length > 0) {						
				if(hotelsIndex == 1 && (allHotels[0] && allHotels[0].length > 0)) {
					innerHTML = innerHTML + "<tr>";
					innerHTML = innerHTML + "<td colspan=\"2\" class=\"tal bgc04 bob02 p05 fs11 b\">Other " + unMarkedHotelSource + " Hotels</td>"
					innerHTML = innerHTML + "</tr>";
				}
				
				for(var hotelIndex = hotelResultsStartIndex; (hotelIndex < allHotels[hotelsIndex].length); ++hotelIndex) {
					var hotelInfo = allHotels[hotelsIndex][hotelIndex];
					if(hotelInfo.displayMode == 0) {
						var hotelMarker = hotelInfo.marker;
						if(hotelMarker && hotelMarker != '') {
							hotelMarker = "<span class='hotelMarker'>" + hotelMarker + "</span>&nbsp;";
						}
						
						var specialOffer = "";
						if(hotelInfo.hasOffer) {
							specialOffer = "<img src='" + _webLoc + "/shared/images/core/buttons/specialOfferIcon.gif' alt='Special Offer Icon' valign='bottom' width='47' height='12'"; 
						}
		     		
		     			var hotelIcons = specialOffer ? specialOffer : '&nbsp;';
						innerHTML = innerHTML + "<tr>";
						innerHTML = innerHTML + "<td class=\"tar pt07 fs10\">(" + hotelInfo.rating + ")";
		     			if(hotelIndex == allHotels[hotelsIndex].length - 1) {
		     				innerHTML = innerHTML + "<br/><br/>";
		     			}
		     			innerHTML = innerHTML + "</td>";
		    			innerHTML = innerHTML + "</tr>";
		     			innerHTML = innerHTML + "<tr>";
		     			innerHTML = innerHTML + "<td class=\"tal\"><a href=\"javascript:;\" onClick=\"javascript:loadRightContentHotel('" + destination + "','" + hotelInfo.cityCode + "','" + hotelInfo.hotelId + "','" + region + "','" + area + "');\" class=\"link01\" >" + hotelMarker + hotelInfo.hotelName + "</a></td>";
		    			innerHTML = innerHTML + "</tr>";
			    		if(hotelInfo.hasOffer) {
			    			innerHTML = innerHTML + "<tr>";
			    			innerHTML = innerHTML + "<td class=\"tal pb07\" valign=\"top\"><a href=\"javascript:;\" onClick=\"javascript:loadRightContentHotel('" + destination + "','" + hotelInfo.cityCode + "','" + hotelInfo.hotelId + "','" + region + "','" + area + "',true);\" >" + hotelIcons + "</a></td>";
			    			innerHTML = innerHTML + "</tr>";
			    		}
			    		innerHTML = innerHTML + "<tr>";
			    		innerHTML = innerHTML + "<td class=\"bob02\"><img src='" + _webLoc + "/shared/images/core/spacer.gif' alt='' width='1' height='1' /></td>";
			    		innerHTML = innerHTML + "</tr>";
		    		}
				}
			}
		}
		innerHTML = innerHTML + "</table>";
		hotelsTableDiv.innerHTML = innerHTML;
	}
}
var displayStartIndex = 0;
var numberOfOffersToDisplay = 3;
var totalOffers = 0;

function loadNextLandingPageOffers() {
	if(totalOffers > (displayStartIndex + numberOfOffersToDisplay)) {
		displayStartIndex += numberOfOffersToDisplay;
		
		displayOffers(displayStartIndex, numberOfOffersToDisplay, totalOffers);
	}
}	

function loadPreviousLandingPageOffers() {
	if(totalOffers > (displayStartIndex - numberOfOffersToDisplay)) {
		displayStartIndex -= numberOfOffersToDisplay;
		var displayEndIndex = displayStartIndex + numberOfOffersToDisplay - 1;
		
		displayOffers(displayStartIndex, numberOfOffersToDisplay, totalOffers);
	}
}	

function displayOffers(displayStartIndex, numberOfOffersToDisplay, totalOffers) {
	var displayEndIndex = displayStartIndex + numberOfOffersToDisplay - 1;
	
	//First, hide all offers
	for(var offerIndex = 1; offerIndex <= totalOffers; ++offerIndex) {
		var offerDiv = document.getElementById("offerDiv_" + offerIndex);
		
		if(offerDiv) {
			offerDiv.style.display = "none";
		}
	}
	
	//Display offers on the current page
	var displayIndex = displayStartIndex;
	for(; displayIndex <= displayEndIndex; ++displayIndex) {
		var offerDiv = document.getElementById("offerDiv_" + (displayIndex + 1));
		
		if(offerDiv) {
			offerDiv.style.display = "";
		}
	}
	
	var nextOfferDiv = document.getElementById("nextOffer");
	var previousOfferDiv = document.getElementById("previousOffer");
	var filmStripDiv = document.getElementById("filmStrip");
	
	if((displayEndIndex >= (totalOffers - 1)) && (displayStartIndex == 0)) {
		if(filmStripDiv) {
			filmStripDiv.style.display = "none";
		}
	}
	else {
		if(filmStripDiv) {
			filmStripDiv.style.display = "";
		}

		if(displayEndIndex >= (totalOffers - 1)) {
			if(nextOfferDiv) {
				nextOfferDiv.style.display = "none";
			}
		}
		else {
			if(nextOfferDiv) {
				nextOfferDiv.style.display = "";
			}
		}
		
		if(displayStartIndex == 0) {
			if(previousOfferDiv) {
				previousOfferDiv.style.display = "none";
			}
		}
		else {
			if(previousOfferDiv) {
				previousOfferDiv.style.display = "";
			}
		}
	}
}

function validateAndSaveSweepstakeDetails() {
	var sweepstakesCode = document.getElementById("sweepstakesCode").value;
	var membershipNumber = document.getElementById("membershipNumber").value;
	var firstName = document.getElementById("firstName").value;
	var lastName = document.getElementById("lastName").value;
	var street1 = document.getElementById("street1").value;
	var street2 = document.getElementById("street2").value;
	var city = document.getElementById("city").value;
	var state = document.getElementById("state").value;
	var country = document.getElementById("country").value;
	var phone = document.getElementById( "primaryPhoneStateCode").value + document.getElementById( "primaryPhoneCityCode").value + document.getElementById( "primaryPhone").value;
	var email = document.getElementById("email").value;
	var termsAndConditionsChecked = document.getElementById("termsAndConditions").checked;
	
	if( !validateField( 'firstName' , 'Please enter your first name.' ) ) {
		return false;
	}
	
	if( !validateField( 'lastName' , 'Please enter your last name.' ) ) {
		return false;
	}
	
	if( !( validateField( 'street1' , 'Please enter street.' ) ) ) {
		return false;
	}
	
	if( !validateField( 'city' , 'Please enter city.' ) ) {
		return false;
	}
	
	if( !validateField( 'state' , 'Please select a state.' ) ) {
		return false;
	}
	
	if( !validateField( 'zip' , 'Please enter valid zip.' ) ) {
		return false;
	}
	
	if( !validateField( 'primaryPhoneStateCode' , 'Please enter valid primary phone.' ) ) {
		return false;
	}
	
	if( !validateField( 'primaryPhoneCityCode' , 'Please enter valid primary phone.' ) ) {
		return false;
	}
	
	if( !validateField( 'primaryPhone' , 'Please enter valid primary phone.' ) ) {
		return false;
	}
	
	if( !validateField( 'email' , 'Please enter your e-mail address.' ) || !validateEmail('email', 'dataContent')) {
		return false;
	}
	
	if(!termsAndConditionsChecked) {
		showErrorMessage('Please accept the terms and conditions', 'dataContent', "termsAndConditions", '1px solid #7f9db9');
		return false;
	}
	
	var queryString = "ss=3";
	queryString += "&sweepstakesCode="  + sweepstakesCode;	
	queryString += "&membershipNumber=" + membershipNumber;
	queryString += "&firstName=" 	    + firstName;
	queryString += "&lastName=" 	    + lastName;
	queryString += "&street1=" 	   	    + street1;
	queryString += "&street2=" 	  	    + street2;
	queryString += "&city=" 		    + city;
	queryString += "&state=" 		    + state;
	queryString += "&country=" 		    + country;
	queryString += "&phone=" 		    + phone;
	queryString += "&email=" 		    + email;
	
	makeAjaxCallWithWaitingDiv( 'sweepstakesContent.act', queryString, null, null, 'callbackValidateAndSaveSweepstakeDetails');
}

function callbackValidateAndSaveSweepstakeDetails(errorCode, errorMessage) {
	if(errorCode != null) {
		showMessage(errorMessage, errorCode, 'dataContent' );
	}else {
		loadSweepstakesSuccessPopup();
	}
	return true;	
}

function loadSweepstakesSuccessPopup() {
	sweepstakesSuccessPopupDiv = document.getElementById("sweepstakesSuccessPopupDiv");
	if(!sweepstakesSuccessPopupDiv) {
		sweepstakesSuccessPopupDiv = createPopupDiv( "sweepstakesSuccessPopupDiv", 0, 0, 410, 300, false, true,  "tal popupDivBig" );
	}

	makeAjaxCall( 'sweepstakesContent.act', 'ss=4', null, "sweepstakesSuccessPopupDiv", 'callbackLoadSweepstakesSuccessPopup');
}

function callbackLoadSweepstakesSuccessPopup() {
	document.title = "Costco Travel";	
	showBlock('sweepstakesSuccessPopupDiv'); 
	positionBlockCentrally('sweepstakesSuccessPopupDiv'); 
	disableElement( 'dataContent', true );
}

function hideSweepstakesSuccessPopupDiv() {
	hideBlock('sweepstakesSuccessPopupDiv');
	disableElement( 'dataContent', false);
	loadHomePage();
}var _selectedCityTab = 1;
var NUMBER_OF_PACKAGE_RESULTS_WITH_LIP_PER_PAGE = 5;
var NUMBER_OF_PACKAGE_RESULTS_WITHOUT_LIP_PER_PAGE = 5;
var OPERATOR_TYPE_EQUAL_TO = 0;
var OPERATOR_TYPE_GREATER_THAN  = 1;
var PACKAGE_DISPLAY_TYPE_AGENT_AND_CONSUMER = 0;
var PACKAGE_DISPLAY_TYPE_AGENT_ONLY = 1;
var PACKAGE_DISPLAY_TYPE_CONSUMER_ONLY = 2;
var DEFAULT_MULTI_DESTINATIONS = new Array('australia', 'europe', 'newZealand', 'fiji', 'tahitianIslands', 'cookIslands');

function showPackagesWithLeadInPrice( pageNumber ) {
	window.scrollTo( 0, 0 );
	var packageResults = _packagesWithCityIndex[ _selectedCityTab - 1 ];
	if( isNull( packageResults ) ) {
		document.getElementById( "searchResults" ).innerHTML = "<div class='tal p10 pb15 tc02 b'>No packages were found for the given search criteria. Please select a different date and/or two or more rooms, or select the single- or multi-destination tab.</div>";
		return;    		
	}
	var numberOfPackages = packageResults.length;
	if( numberOfPackages == 0  ) {
		document.getElementById( "searchResults" ).innerHTML = "<div class='tal p10 pb15 tc02 b'>No packages were found for the given search criteria. Please select a different date and/or two or more rooms, or select the single- or multi-destination tab.</div>";
		return;    		
	}
	document.getElementById( "searchResults" ).innerHTML = "";
	packageResults.sort( sortPackageResults );
	for( var packageCounter = ( pageNumber * NUMBER_OF_PACKAGE_RESULTS_WITH_LIP_PER_PAGE - NUMBER_OF_PACKAGE_RESULTS_WITH_LIP_PER_PAGE ); packageCounter < ( pageNumber*NUMBER_OF_PACKAGE_RESULTS_WITH_LIP_PER_PAGE ); packageCounter++ ) {
		if( packageCounter < numberOfPackages  ) {
			loadSearchResultsDiv( packageResults[ packageCounter ] );
		}
	}

	var numberOfPages = document.getElementById( "numberOfPages" ).value;
	document.getElementById( "selectedPage" ).value = pageNumber;
	showPagination(pageNumber, numberOfPages, "top");
	showPagination(pageNumber, numberOfPages, "bottom");
}
/*
 * Sort Package results based LIP and package display type.
 */
function sortPackageResults( firstPackageInfo, secondPackageInfo ) {
    if( ( firstPackageInfo.displayType == PACKAGE_DISPLAY_TYPE_AGENT_AND_CONSUMER || firstPackageInfo.displayType == PACKAGE_DISPLAY_TYPE_CONSUMER_ONLY ) && ( secondPackageInfo.displayType == PACKAGE_DISPLAY_TYPE_AGENT_ONLY ) ) {
   		return -1;
    } else if( ( firstPackageInfo.displayType == PACKAGE_DISPLAY_TYPE_AGENT_ONLY ) && ( secondPackageInfo.displayType == PACKAGE_DISPLAY_TYPE_AGENT_AND_CONSUMER || secondPackageInfo.displayType == PACKAGE_DISPLAY_TYPE_CONSUMER_ONLY  ) ) {
    	return 1;
    } else if( ( !( firstPackageInfo.isRequiredHotelAvailable ) && secondPackageInfo.isRequiredHotelAvailable ) ) {
    	return 1;
    } else if( ( firstPackageInfo.isRequiredHotelAvailable && !( secondPackageInfo.isRequiredHotelAvailable ) ) ) {
    	return -1;
    } else if( ( !( firstPackageInfo.isRequiredFlightAvailable ) && secondPackageInfo.isRequiredFlightAvailable ) ) {
    	return 1;
    } else if( ( firstPackageInfo.isRequiredFlightAvailable && !( secondPackageInfo.isRequiredFlightAvailable ))  ) {
    	return -1;
    } else {
    	if( !isNull( firstPackageInfo.leadInPrice ) ) {
    		return ( firstPackageInfo.leadInPrice - secondPackageInfo.leadInPrice );
    	} else {
    		return 0;
    	}
    }
}

function showPagination( pageNumber, numberOfPages, paginationType ) {
	if( document.getElementById( paginationType + "previous" ) != null ) {
		if( pageNumber > 1 ) {
			document.getElementById( paginationType + "previous" ).style.display = "inline";
		} else {
		 	document.getElementById( paginationType + "previous" ).style.display = "none";
		}
	}
	if( document.getElementById( paginationType + "next" ) != null ) {
		if( pageNumber == numberOfPages ) {
			document.getElementById( paginationType + "next" ).style.display = "none";
		} else {
			document.getElementById( paginationType + "next" ).style.display = "inline";
		}
	}
	for( var pageIndex = 1 ; pageIndex <= numberOfPages ; pageIndex++ ) {
		if( document.getElementById( paginationType + "anchorId_" + pageIndex )!= null ){
			document.getElementById( paginationType + "anchorId_" + pageIndex ).className = "pagenos";
		}
	}
	if( document.getElementById( paginationType + "anchorId_" + pageNumber )!= null ){
		document.getElementById( paginationType + "anchorId_" + pageNumber ).className = "pagenos-sel";
	}
}

function moveNext() {
	window.scrollTo( 0, 0 );
	var pageNumber = document.getElementById( "selectedPage" ).value
	pageNumber = 1+ parseInt( pageNumber );
	if( _selectedCityTab == 1 && isBookablePackage ) {
    	showPackagesWithLeadInPrice( pageNumber );
	} else {
		showPackagesWithoutLeadInPrice( pageNumber );
	}
}

function movePrevious(){
	window.scrollTo( 0, 0 );
	var pageNumber = document.getElementById( "selectedPage" ).value;
	pageNumber =  parseInt( pageNumber )-1;
	if( _selectedCityTab == 1 && isBookablePackage ) {
    	showPackagesWithLeadInPrice( pageNumber );
	} else {
		showPackagesWithoutLeadInPrice( pageNumber );
	}
}

function loadSearchResultsDiv( packageInfo ) {

	// search result for a package.
	var searchResult = packageInfo.searchResult;
	// array of product results. 
	var hotel = searchResult.hotel;
	var flight = searchResult.flight;
	var car = searchResult.car;
	var tour = searchResult.tour;
	var transfer = searchResult.transfer;
	var greeting = searchResult.greeting;
	
	_packageId = packageInfo.packageId;
	_destinationCode = searchResult.destination;
	_regionCode = searchResult.region;

	//Itinerary Component Div
	var itineraryComponentTitleDiv = document.createElement( 'DIV' );
	itineraryComponentTitleDiv.className = "itineraryComponentTitleBg";

	var flightComponentIconDiv = null;
	var hotelComponentIconDiv = null; 
	var carComponentIconDiv = null;
	var sightSeeingComponentIconDiv = null;

	//If flight present, create flight icon.
	if( flight.length > 0 ) {
		flightComponentIconDiv = document.createElement( 'DIV' );
		flightComponentIconDiv.className = "itineraryComponentTitleIcon mr-10";

		var flightIconImage = document.createElement( 'IMG' );
		flightIconImage.src = _webLoc + "/shared/images/core/icons/flightIcon.gif";
		flightIconImage.alt = "Flight Icon";

		flightComponentIconDiv.appendChild( flightIconImage );
	}

	// If hotel present, create hotel icon.
	if( hotel.length > 0 ) {
		hotelComponentIconDiv = document.createElement( 'DIV' );
		hotelComponentIconDiv.className = "itineraryComponentTitleIcon mr-10";

		var hotelIconImage = document.createElement( 'IMG' );
		hotelIconImage.src = _webLoc + "/shared/images/core/icons/hotelIcon.gif";
		hotelIconImage.alt = "Hotel Icon";

		hotelComponentIconDiv.appendChild( hotelIconImage );	
	}

	// If car present, create car icon.
	if( car.length > 0 ) {
		carComponentIconDiv = document.createElement( 'DIV' );
		carComponentIconDiv.className = "itineraryComponentTitleIcon mr-10";

		var carIconImage = document.createElement( 'IMG' );
		carIconImage.src = _webLoc + "/shared/images/core/icons/carIcon.gif";
		carIconImage.alt = "Car Icon";

		carComponentIconDiv.appendChild( carIconImage );
	}
	
	// If greeting present, create greeting icon.
	if( greeting.length > 0 ) {
		greetingComponentIconDiv = document.createElement( 'DIV' );
		greetingComponentIconDiv.className = "itineraryComponentTitleIcon mr-10";

		var greetingIconImage = document.createElement( 'IMG' );
		greetingIconImage.src = _webLoc + "/shared/images/core/icons/greetingIcon.gif";
		greetingIconImage.alt = "Greeting Icon";

		greetingComponentIconDiv.appendChild( greetingIconImage );
	}
	
	// If transfer present, create transfer icon.
	if( transfer.length > 0 ) {
		transferComponentIconDiv = document.createElement( 'DIV' );
		transferComponentIconDiv.className = "itineraryComponentTitleIcon mr-10";

		var transferIconImage = document.createElement( 'IMG' );
		transferIconImage.src = _webLoc + "/shared/images/core/icons/transferIcon.gif";
		transferIconImage.alt = "Transfer Icon";

		transferComponentIconDiv.appendChild( transferIconImage );
	}
	
	// If tour present, create tour/sightseeing icon.
	if( tour.length > 0 ) {
		sightSeeingComponentIconDiv = document.createElement( 'DIV' );
		sightSeeingComponentIconDiv.className = "itineraryComponentTitleIcon mr-10";

		var sightSeeingIconImage = document.createElement( 'IMG' );
		sightSeeingIconImage.src = _webLoc + "/shared/images/core/icons/sightseeingIcon.gif";
		sightSeeingIconImage.alt = "Sightseeing Icon";

		sightSeeingComponentIconDiv.appendChild( sightSeeingIconImage );
	}

	if( flight.length > 0 ) {
		itineraryComponentTitleDiv.appendChild( flightComponentIconDiv );		 
	}
	if( hotel.length > 0 ) {
		itineraryComponentTitleDiv.appendChild( hotelComponentIconDiv );	
	}
	if( car.length > 0 ) {
		itineraryComponentTitleDiv.appendChild( carComponentIconDiv );	
	}
	if( greeting.length > 0 ) {
		itineraryComponentTitleDiv.appendChild( greetingComponentIconDiv );
	}
	if( transfer.length > 0 ) {
		itineraryComponentTitleDiv.appendChild( transferComponentIconDiv );
	}
	if( tour.length > 0 ) {
		itineraryComponentTitleDiv.appendChild( sightSeeingComponentIconDiv );	
	}

	//Package Price Div
	var packagePriceDiv = document.createElement( 'DIV' );
	packagePriceDiv.className = "itineraryComponentTitleRight fs12";
	var packagePriceSpan = document.createElement( 'SPAN' );
	packagePriceSpan.className = "fs10 nob";
	packagePriceSpan.appendChild( document.createTextNode( "Total Package Price " ) );
	packagePriceDiv.appendChild( packagePriceSpan );
	if ( packageInfo.isRequiredFlightAvailable && packageInfo.isRequiredHotelAvailable ){
		packagePriceDiv.appendChild( document.createTextNode( formatCurrency( parseFloat( packageInfo.leadInPrice ).toFixed( 2 ) ) ) );
	} else{
		packagePriceDiv.appendChild( document.createTextNode( "N/A" ));
	}
	
	itineraryComponentTitleDiv.appendChild( packagePriceDiv );
	
	//itineraryComponent BR
	var itineraryComponentTitleBR = document.createElement( "BR" );
	itineraryComponentTitleBR.clear = "all";
	itineraryComponentTitleDiv.appendChild( itineraryComponentTitleBR );
	
	// Div for all component.
	var mainDiv = document.createElement( 'DIV' );
	mainDiv.className = "bo07 p10";

	loadPackageResultDiv( mainDiv, packageInfo );

	if( !( isNull( packageInfo.hotelId ) ) ) {
		loadHotelTabsDiv( mainDiv, packageInfo.hotelId );
	}

	var afterHotelTabsBR = document.createElement( 'BR' );
	afterHotelTabsBR.clear = "all";
	mainDiv.appendChild( afterHotelTabsBR );

	var hotelSpacerImgDiv = document.createElement( 'DIV' );
	hotelSpacerImgDiv.className = "divider mt-07 pb10 ml156";

	var hotelSpacerImg = document.createElement( 'IMG' );
	hotelSpacerImg.src = _webLoc + "/shared/images/core/spacer.gif";
	hotelSpacerImg.alt = "";
	hotelSpacerImgDiv.appendChild( hotelSpacerImg );
	mainDiv.appendChild( hotelSpacerImgDiv );

	if( hotel.length > 0 ) {
		loadHotelResultDiv( mainDiv, hotel );

		//add divider between flight and hotel.
		var fltSpacerImgDiv = document.createElement( 'DIV' );
		fltSpacerImgDiv.className = "divider p05";
	
		var flightSpacerImg = document.createElement( 'IMG' );
		flightSpacerImg.src = _webLoc + "/shared/images/core/spacer.gif";
		flightSpacerImg.alt = "";
		fltSpacerImgDiv.appendChild( flightSpacerImg );
		mainDiv.appendChild( fltSpacerImgDiv );
	}
	
	if( flight.length > 0 ) {
		loadFlightResultDiv( mainDiv, flight[0], packageInfo );	

		// add divider between flight and car. 
		var carSpacerImgDiv = document.createElement( 'DIV' );
		carSpacerImgDiv.className = "divider p05";
		
		var carSpacerImg = document.createElement( 'IMG' );
		carSpacerImg.src = _webLoc + "/shared/images/core/spacer.gif";
		carSpacerImg.alt = "";
		carSpacerImgDiv.appendChild( carSpacerImg );
		mainDiv.appendChild( carSpacerImgDiv );
	}

	if( greeting.length > 0 ) {
		loadTransferResultDiv( mainDiv, greeting[0], false );

		// add divider between car and greeting. 
		var greetingSpacerImgDiv = document.createElement( 'DIV' );
		greetingSpacerImgDiv.className = "divider p05";
		
		var greetingSpacerImg = document.createElement( 'IMG' );
		greetingSpacerImg.src = _webLoc + "/shared/images/core/spacer.gif";
		greetingSpacerImg.alt = "";
		greetingSpacerImgDiv.appendChild( greetingSpacerImg );
		mainDiv.appendChild( greetingSpacerImgDiv );
	}
	
	if( car.length > 0 ) {
		loadCarResultDiv( mainDiv, car[0] );
	}
	
	if( transfer.length > 0 ) {
		var transferSpan = document.createElement( "SPAN" );
		transferSpan.className = "b";
		transferSpan.appendChild( document.createTextNode( "Airport Transfer(s) Included." ) );
		mainDiv.appendChild( transferSpan );
	}
	
	if( tour.length > 0 ) {
		// add divider between transfer and tour. 
		var transferSpacerImgDiv = document.createElement( 'DIV' );
		transferSpacerImgDiv.className = "divider p05";

		var transferSpacerImg = document.createElement( 'IMG' );
		transferSpacerImg.src = _webLoc + "/shared/images/core/spacer.gif";
		transferSpacerImg.alt = "";
		transferSpacerImgDiv.appendChild( transferSpacerImg );
		mainDiv.appendChild( transferSpacerImgDiv );

		loadTourResultDiv( mainDiv, tour );
	}

	document.getElementById( "searchResults" ).appendChild( itineraryComponentTitleDiv );	
	document.getElementById( "searchResults" ).appendChild( mainDiv );
	
	var dividerDiv = document.createElement( "DIV" );
	dividerDiv.className = "divider pt10 pb05";
	var dividerImage = document.createElement( "IMG" );
	dividerImage.src = _webLoc + "/shared/images/core/spacer.gif";
	dividerImage.alt = "";
	dividerDiv.appendChild( dividerImage );
	
	document.getElementById( "searchResults" ).appendChild( dividerDiv );
}

/*
 * Loads package information into package results section.
 */
function loadPackageResultDiv( mainDiv, packageInfo ) {
	
	var packageId = decodeHTML( packageInfo.packageId );
	
	// Package thumbnail image Div.
	var packageImageDiv = document.createElement( 'DIV' );
	packageImageDiv.className = "fll";
	
	//Package Image Link.
	var packageImageLink = document.createElement( 'A' );
	packageImageLink.href ="javascript:;";
	packageImageLink.onclick = function() { parent.loadRightContentPackage( selectedDestinationCode, selectedRegionCode, null, null, packageId, null, null, null, true); } ;
	
	//Package Image.
	var packageImage = document.createElement( 'IMG' );
	packageImage.src = _webLoc + "/shared/images/package/destination/" + packageId + "/" + packageId + "_F_1.jpg";
	packageImage.alt = decodeHTML( packageInfo.signLine1 ) + " Thumbnail";
	packageImage.width = "146";
	packageImage.height = "85";
	packageImageLink.appendChild( packageImage );
	
	packageImageDiv.appendChild( packageImageLink );
	
	//Appending Package Image Div.
	mainDiv.appendChild( packageImageDiv );
	
	//Package Information Table
	var packageDetailDiv = document.createElement( 'DIV' );
	packageDetailDiv.className = "fll w514";
	var packageDetailTable = document.createElement( 'TABLE' );
	packageDetailTable.cellPadding = "0";
	packageDetailTable.cellSpacing = "0";
	packageDetailTable.border = "0";
	packageDetailTable.className = "fs11 wp100";
	var packageDetailTBody = document.createElement( 'TBODY' );
	var packageDetailTr = document.createElement( 'TR' );
	var packageDetailTd1 = document.createElement( 'TD' );
	packageDetailTd1.className = "w352 h61 valt pl10";
	//Package Name with Link.
	var packageNameLink = document.createElement( 'A' );
	packageNameLink.href ="javascript:;";
	packageNameLink.onclick = function() { parent.loadRightContentPackage( selectedDestinationCode, selectedRegionCode, null, null, packageId, null, null, null, true ); } ;
	packageNameLink.className ="title fs14";

	//Package Name( SignLine1 ) Text node.
	packageNameLink.appendChild( document.createTextNode( decodeHTML( packageInfo.signLine1 ) ) );
	packageDetailTd1.appendChild( packageNameLink );
	
	var packageNameLinkBR1 = document.createElement( 'br' );
	packageDetailTd1.appendChild( packageNameLinkBR1 );

	//Package Name( signLine2 ) Text node.
	packageDetailTd1.appendChild( document.createTextNode( decodeHTML( packageInfo.signLine2 ) ) );

	var packageNameLinkBR2 = document.createElement( 'br' );
	packageDetailTd1.appendChild( packageNameLinkBR2 );

	//Package Name( signLine3 ) Text node.
	packageDetailTd1.appendChild( document.createTextNode( decodeHTML( packageInfo.signLine3 ) ) );

	var packageNameLinkBR3 = document.createElement( 'br' );
	packageDetailTd1.appendChild( packageNameLinkBR3 );

	//Package Name( signLine4 ) Text node.
	packageDetailTd1.appendChild( document.createTextNode( decodeHTML( packageInfo.signLine4 ) ) );
	
	var packageDetailTd2 = document.createElement( 'TD' );
	packageDetailTd2.className = "valt tar";

	//Display of Book It button or Call center phone Image.
	if( packageInfo.displayType != PACKAGE_DISPLAY_TYPE_AGENT_ONLY ) {
		var bookButtonImageLink = document.createElement( 'A' );
		bookButtonImageLink.href ="javascript:;";
		
		var bookButtonImage = document.createElement( 'IMG' );
		bookButtonImage.src = _webLoc + "/shared/images/core/buttons/continue-red-btn.gif";
		bookButtonImage.alt = "Continue Button";
		bookButtonImageLink.appendChild( bookButtonImage );
		bookButtonImageLink.href = "javascript:;";
		
		if ( packageInfo.isRequiredFlightAvailable ){
			bookButtonImageLink.onclick = function() { proceedToSearchResults( packageId ); };
		} else {	
			bookButtonImageLink.onclick = function() { loadSearchPopupOrSearchResults( packageId ); };
		}    		
		
		packageDetailTd2.appendChild( bookButtonImageLink );
	} else {
		var callCenterImage = document.createElement( 'IMG' );
		callCenterImage.src = _webLoc + "/shared/images/core/icons/cta.gif";
		callCenterImage.alt = "To Book Call 1-877-849-2790 Thumbnail";
    	callCenterImage.width = "129";
    	callCenterImage.height = "33";
    	
		packageDetailTd2.appendChild( callCenterImage );
	}
	
	packageDetailTr.appendChild( packageDetailTd1 );
	packageDetailTr.appendChild( packageDetailTd2 );
	packageDetailTBody.appendChild( packageDetailTr );
	packageDetailTable.appendChild( packageDetailTBody );
	packageDetailDiv.appendChild( packageDetailTable ); 

	mainDiv.appendChild( packageDetailDiv );
	
	var afterPackageDetailBR = document.createElement( 'BR' );
	mainDiv.appendChild( afterPackageDetailBR );
}

/*
 *  Loads information about hotel in package results hotel section.
 */
function loadHotelTabsDiv( mainDiv, hotelId ) {
	var allInclusive;
	var optionalAllInclusive; 

	//Display of Hotel Tabs
	var hotelTabsDiv = document.createElement( 'DIV' );
	hotelTabsDiv.className = "flr mt-07 pb02";

	//Hotel Overview Tab
	var overViewTabDiv = document.createElement( 'DIV' );
	overViewTabDiv.className = "tab01";

	var overViewLink = document.createElement( 'A' );
	overViewLink.href ="javascript:;";
	overViewLink.id = "divOverview";

	overViewLink.onclick = function() { loadHotelPopupOverview( selectedDestinationCode, cityCode, hotelId, allInclusive, optionalAllInclusive, true ); };
	overViewLink.appendChild( document.createTextNode( "Overview" ) );
	overViewTabDiv.appendChild( overViewLink );

	//Hotel Property Tab
	var propertyTabDiv = document.createElement( 'DIV' );
	propertyTabDiv.className = "tab01";

	var propertyLink = document.createElement( 'A' );
	propertyLink.href ="javascript:;";
	propertyLink.id = "divProperty";

	propertyLink.onclick = function() { loadHotelPopupProperty( selectedDestinationCode, cityCode, hotelId, allInclusive, optionalAllInclusive, true ); };
	propertyLink.appendChild( document.createTextNode( "Property" ) );
	propertyTabDiv.appendChild( propertyLink );

	//Hotel rooms Tab
	var roomsTabDiv = document.createElement( 'DIV' );
	roomsTabDiv.className = "tab01";

	var roomsLink = document.createElement( 'A' );
	roomsLink.href ="javascript:;";
	roomsLink.id = "divRooms";

	roomsLink.onclick = function() { loadHotelPopupRooms( selectedDestinationCode, cityCode, hotelId, allInclusive, optionalAllInclusive, true ); };
	roomsLink.appendChild( document.createTextNode( "Rooms" ) );
	roomsTabDiv.appendChild( roomsLink );

	if( allInclusive ) {
		//Hotel All-Inclusive Tab 
		//Add condition when to display this inclusive tab.
		var allInclusiveTabDiv = document.createElement( 'DIV' );
		allInclusiveTabDiv.className = "tab01";

		var allInclusiveLink = document.createElement( 'A' );
		allInclusiveLink.href ="javascript:;";
		allInclusiveLink.id = "divAllInclusive";

		allInclusiveLink.onclick = function() { loadHotelPopupAllInclusive( selectedDestinationCode, cityCode, hotelId, allInclusive, optionalAllInclusive, true ); };
		allInclusiveLink.appendChild( document.createTextNode( "All-Inclusive" ) );
		allInclusiveTabDiv.appendChild( allInclusiveLink );
	}

	//Hotel Photos Tab
	var photosMapsTabDiv = document.createElement( 'DIV' );
	photosMapsTabDiv.className = "tab01";

	var photosMapsLink = document.createElement( 'A' );
	photosMapsLink.href ="javascript:;";
	photosMapsLink.id = "divPhotosMaps";

	photosMapsLink.onclick = function() { loadHotelPopupPhotosMaps( selectedDestinationCode, cityCode, hotelId, allInclusive, optionalAllInclusive, true ); };
	photosMapsLink.appendChild( document.createTextNode( "Photos" ) );
	photosMapsTabDiv.appendChild( photosMapsLink );

	//Hotel Maps Tab
	var mapsTabDiv = document.createElement( 'DIV' );
	mapsTabDiv.className = "tab01";

	var mapsLink = document.createElement( 'A' );
	mapsLink.href ="javascript:;";
	mapsLink.id = "divMaps";

	mapsLink.onclick = function() { loadHotelPopupMaps( selectedDestinationCode, cityCode, hotelId, allInclusive, optionalAllInclusive, true ); };
	mapsLink.appendChild( document.createTextNode( "Map" ) );
	mapsTabDiv.appendChild( mapsLink );

	//Appending All hotel tabs div to hotel main tab div.
	hotelTabsDiv.appendChild( overViewTabDiv );
	hotelTabsDiv.appendChild( propertyTabDiv );
	hotelTabsDiv.appendChild( roomsTabDiv );
	if( allInclusive ) {
		hotelTabsDiv.appendChild( allInclusiveTabDiv );
	}
	hotelTabsDiv.appendChild( photosMapsTabDiv );
	hotelTabsDiv.appendChild( mapsTabDiv );

	var afterAllHotelTabsBR = document.createElement( 'BR' );
	afterAllHotelTabsBR.clear = "all";
	hotelTabsDiv.appendChild( afterAllHotelTabsBR );

	//Main Div.	
	mainDiv.appendChild( hotelTabsDiv );	
}

/*
 * Loads hotel results information into package results section.
 */
function loadHotelResultDiv( mainDiv, hotelResults ) {
	var firstHotelResult = hotelResults[0];

	//Hotel Detail Information
	var hotelDetailDiv = document.createElement( 'DIV' );
	hotelDetailDiv.className = "mt05 lh15";

	//This div displays Hotel Name, Category and Hotel Options
	var hotelInfoDiv = document.createElement( 'DIV' );
	hotelInfoDiv.className = "fll w340";

	//Hotel Name Display 
	var hotelNameSpan = document.createElement( 'SPAN' );
	hotelNameSpan.className = "fs12 b";
	hotelNameSpan.appendChild( document.createTextNode( decodeHTML( firstHotelResult.hotelName ) ) );
	hotelInfoDiv.appendChild( hotelNameSpan );
	hotelInfoDiv.appendChild( document.createTextNode( " (" + firstHotelResult.rating  + ")" ) );
	
	var hotelNameBR = document.createElement( 'BR' );
	hotelInfoDiv.appendChild( hotelNameBR );

	//Room Category Display
	for( var roomIndex = 0 ; roomIndex < hotelResults.length ; roomIndex++ ) {
		var hotelResult = hotelResults[ roomIndex ];
		hotelInfoDiv.appendChild( document.createTextNode( "Room " + ( ( roomIndex == 0 ) ? "One" : ( roomIndex == 1 ) ? "Two" : "" ) + " Category: " ) );
		var hotelCategorySpan = document.createElement( 'SPAN' );
		hotelCategorySpan.className = "b";
		hotelCategorySpan.appendChild( document.createTextNode( decodeHTML( hotelResult.hotelCategory ) ) );
		hotelInfoDiv.appendChild( hotelCategorySpan );

		var hotelRoomCategoryBR = document.createElement( 'BR' );
		hotelInfoDiv.appendChild( hotelRoomCategoryBR );

		//Hotel Options Display/
		var hotelOptions = hotelResult.options; 
		if( hotelOptions.length > 0 ) {
			var hotelOptionsDiv = document.createElement( "DIV" );
			hotelOptionsDiv.className = "pl10";
			for( var optionIndex = 0; optionIndex < hotelOptions.length; optionIndex++ ) {
				var hotelOption = document.createElement( "LI" );
				hotelOption.appendChild( document.createTextNode( decodeHTML( hotelOptions[ optionIndex ].option ) ) );
				hotelOptionsDiv.appendChild( hotelOption );
			}
			hotelInfoDiv.appendChild( hotelOptionsDiv );	
		}

		if( hotelResult.cashCardAmount > 0 ) {
			var cashCardDiv = document.createElement( "DIV" );
			cashCardDiv.className = "pl10";
			var cashCardDesc = document.createElement( "LI" );
			cashCardDesc.appendChild( document.createTextNode( "$" + hotelResult.cashCardAmount + " Costco Cash Card" ) );
			cashCardDiv.appendChild( cashCardDesc );
			hotelInfoDiv.appendChild( cashCardDiv );	
		}

		var valueAdds = hotelResult.valueAdds; 
		if( valueAdds.length > 0 ) {
			var valueAddDiv = document.createElement( "DIV" );
			valueAddDiv.className = "pl10";
			for( var valueAddIndex = 0; valueAddIndex < valueAdds.length; valueAddIndex++ ) {
				var valueAddDesc = document.createElement( "LI" );
				valueAddDesc.appendChild( document.createTextNode( decodeHTML( valueAdds[ valueAddIndex ].description ) ) );
				valueAddDiv.appendChild( valueAddDesc );
			}
			hotelInfoDiv.appendChild( valueAddDiv );	
		}

		var services = hotelResult.services; 
		if( services.length > 0 ) {
			var servicesDiv = document.createElement( "DIV" );
			servicesDiv.className = "pl10";
			for( var serviceIndex = 0; serviceIndex < services.length; serviceIndex++ ) {
				var serviceDesc = document.createElement( "LI" );
				serviceDesc.appendChild( document.createTextNode( decodeHTML( services[ serviceIndex ].description ) ) );
				servicesDiv.appendChild( serviceDesc );
			}
			hotelInfoDiv.appendChild( servicesDiv );	
		}
	}

	//Hotel CheckIn and checkOut Dates Div
	var hotelDatesDiv = document.createElement( 'DIV' );
	hotelDatesDiv.className = "flr w320";

	//Hotel Check-In Display
	var checkInSpan = document.createElement( 'SPAN' );
	checkInSpan.className = "b";
	hotelDatesDiv.appendChild( document.createTextNode( "Check In: " ) );
	checkInSpan.appendChild( document.createTextNode( firstHotelResult.checkinDate ) );
	hotelDatesDiv.appendChild( checkInSpan );

	//Separation between check-in date and checkout date.
	var separationImg = document.createElement( 'IMG' );
	separationImg.src = _webLoc + "/shared/images/core/spacer.gif";
	separationImg.alt = "";
	separationImg.width = "5";
	hotelDatesDiv.appendChild( separationImg );

	//Hotel Check out Display
	var checkOutSpan = document.createElement( 'SPAN' );
	checkOutSpan.className = "b";
	hotelDatesDiv.appendChild( document.createTextNode( " Check Out: " ));
	checkOutSpan.appendChild( document.createTextNode( firstHotelResult.checkoutDate ) );
	hotelDatesDiv.appendChild( checkOutSpan );

	//BR after Check-in and Check out dates.
	var afterHotelDatesBR = document.createElement( 'BR' );
	afterHotelDatesBR.clear = "all";

	//Appending hotel information div and hotel check in and check out dates div. 
	hotelDetailDiv.appendChild( hotelInfoDiv );
	hotelDetailDiv.appendChild( hotelDatesDiv );
	hotelDetailDiv.appendChild( afterHotelDatesBR );

	mainDiv.appendChild( hotelDetailDiv );

	var spacerImgDiv = document.createElement( 'DIV' );
	var spacerImg = document.createElement( 'IMG' );
	spacerImg.src = _webLoc + "/shared/images/core/spacer.gif";
	spacerImg.alt = "";
	spacerImgDiv.appendChild( spacerImg );
	mainDiv.appendChild( spacerImgDiv );
}

function proceedToSearchResults( packageId ) {
	var queryString = 'pr=1';
	queryString += "&packageId=" + packageId;
	_packageId = packageId;

	var asynchronousRequest = new AsynchronousRequest();
	asynchronousRequest.url = _webLoc + '/packageResults.act';
	asynchronousRequest.queryString = queryString;
	asynchronousRequest.useAjax = true;
	asynchronousRequest.target = 'mainContent';
	asynchronousRequest.callbackFunctionName = 'callbackProceedToSearchResults';

	var splashScreenRequest = new SplashScreenRequest();
	splashScreenRequest.splashScreenText = "Please Wait...";
	asynchronousRequest.splashScreenRequest = splashScreenRequest;
	asynchronousRequest.splashScreenDisplayFunctionName = "displaySearchingPopup";
	asynchronousRequest.splashScreenHideFunctionName = "hideSearchingPopup";

	disableElement( 'dataContent', true );
	//Submit Ajax call with '/vp/booking/searchDestination///<packageId>' as the description to be passed into Google Analytics
	//The three '/' are put on purpose as place holders to retain the general format
	makeAjaxCallWithRequest( asynchronousRequest, '/vp/booking/searchDestination///' + packageId);
}

function callbackProceedToSearchResults( message, errorCode ) {
	disableElement( 'dataContent', false );
	showMessage( message, errorCode, 'dataContent' );
	return true;
}

/*
 * Loads flight information into package search result section. 
 */
function loadFlightResultDiv( mainDiv, flightResult, packageInfo ) {
    var outboundItinerary = flightResult.outboundItinerary;
	var inboundItinerary = flightResult.inboundItinerary;

	var flightTable = document.createElement( "TABLE" );
	flightTable.className = "wp95 fs11";
	flightTable.cellPadding = '2';
	flightTable.cellSpacing = '1';
	flightTable.border="0";
	
	var flightTableTBody = document.createElement( "TBODY" );
	
	var totalOutboundSegments = outboundItinerary.length;
	var totalInboundSegments = inboundItinerary.length;
	
	if( totalOutboundSegments  > 0 ) {
		var arrivalCity = outboundItinerary[ totalOutboundSegments-1 ].arrivalCity;
		var departureCity = outboundItinerary[0].departureCity;
		var flightCode = outboundItinerary[0].flightCode;
		var airLineName = outboundItinerary[0].airLineName
		var departueTime  = outboundItinerary[totalOutboundSegments-1].arrivalDateAndTime;
		var serviceClassDescription = outboundItinerary[0].serviceClassDescription;

		//Onward Journey Information
		var outboundItineraryRow = document.createElement( "TR" );
		
		var airLineLogoTD = document.createElement( "TD" );
		airLineLogoTD.className = "tac fs10 w55";
		airLineLogoTD.rowSpan = 2;

		//Flight Icon
		var flightIcon = document.createElement( 'IMG' );
		flightIcon.src = _webLoc + "/shared/images/core/logos/air/" + flightCode + ".gif";
		flightIcon.alt = airLineName;
		airLineLogoTD.appendChild( flightIcon );
	
		//BR after Check-in and Check out dates.
		var airLineLogoBR = document.createElement( 'BR' );
		airLineLogoTD.appendChild( airLineLogoBR );
		airLineLogoTD.appendChild( document.createTextNode( airLineName ) );
		
		var flightSegmentCityTD = document.createElement( "TD" );
		flightSegmentCityTD.className = "w220 b";
		flightSegmentCityTD.appendChild( document.createTextNode( departureCity + " to " + arrivalCity  ) );
		
		
			//Show Flight Connection Link if more than one segment present.
		var connectionTD = document.createElement( "TD" );
		connectionTD.className = "fs10";
		if( totalOutboundSegments > 1 ) {
			var connectionLink = document.createElement( 'A' );
			connectionLink.href ="javascript:;";
			connectionLink.className = "u";
			connectionLink.onclick = function() { loadFlightDetails( flightResult.uid, '', 1, true ); };
			connectionLink.appendChild( document.createTextNode( "Connect" ) );
			connectionTD.appendChild( connectionLink );
		}
		
		//Flight Departure time
		var flightSegmentTimeTD = document.createElement( "TD" );
		flightSegmentTimeTD.className = "w225 fs10";
		flightSegmentTimeTD.appendChild( document.createTextNode( "Arrive: " ) ); // used to be Depart
		var flightTimeSpan = document.createElement( "SPAN" );
		flightTimeSpan.className = "b";
		flightTimeSpan.appendChild( document.createTextNode( departueTime ) );
		
		flightSegmentTimeTD.appendChild( flightTimeSpan );
		if(flightResult.isNextDayArrivalForOutboundItinerary == "true") {
			var flightDepartureDayAddSpan = document.createElement( "SPAN" );
			flightDepartureDayAddSpan.className = "tc06 b";
			flightDepartureDayAddSpan.appendChild( document.createTextNode( " (+1 Day)" ) );
			flightSegmentTimeTD.appendChild( flightDepartureDayAddSpan );
		}
	
		var flightSegmentServiceClassTD = document.createElement( "TD" );
		flightSegmentServiceClassTD.className = "fs10 b";
		flightSegmentServiceClassTD.appendChild( document.createTextNode(serviceClassDescription ) );
		
		outboundItineraryRow.appendChild( airLineLogoTD );
		outboundItineraryRow.appendChild( flightSegmentCityTD );
		outboundItineraryRow.appendChild( connectionTD );
		outboundItineraryRow.appendChild( flightSegmentTimeTD );
		outboundItineraryRow.appendChild( flightSegmentServiceClassTD );
		
		flightTableTBody.appendChild( outboundItineraryRow );
	}
	
	if( totalInboundSegments > 0 ) {
		var arrivalCity = inboundItinerary[ totalInboundSegments - 1 ].arrivalCity;
		var departureCity = inboundItinerary[ 0 ].departureCity;
		var arrivalTime = inboundItinerary[ 0 ].departureDateAndTime;
		var serviceClassDescription = inboundItinerary[ totalInboundSegments - 1 ].serviceClassDescription;
				
		//Return Jouney Information - Inbound Itinerary segment.
		var inboundItineraryRow = document.createElement( "TR" );

		var flightSegmentCityTD = document.createElement( "TD" );
		flightSegmentCityTD.className = "w220 b";
		flightSegmentCityTD.appendChild( document.createTextNode( departureCity + " to " + arrivalCity ) );

		var connectionTD = document.createElement( "TD" );
		connectionTD.className = "fs10";
		if( totalInboundSegments > 1 ) {
			//Show Flight Connection Link if more than one segment present.
			var connectionLink = document.createElement( 'A' );
			connectionLink.href ="javascript:;";
			connectionLink.className = "u";
			connectionLink.onclick = function() { loadFlightDetails( flightResult.uid, '', 2, true ); };
			connectionLink.appendChild( document.createTextNode( "Connect" ) );
			connectionTD.appendChild( connectionLink );
		}
		
		//Flight Arrival Time
		var flightSegmentTimeTD = document.createElement( "TD" );
		flightSegmentTimeTD.className = "fs10";
		flightSegmentTimeTD.appendChild( document.createTextNode( "Depart: " ) ); //used to be Arrive
		var flightTimeSpan = document.createElement( "SPAN" );
		flightTimeSpan.className = "b";
		flightTimeSpan.appendChild( document.createTextNode( arrivalTime ) );
		
		flightSegmentTimeTD.appendChild( flightTimeSpan );
		if(flightResult.isNextDayArrivalForInboundItinerary) {
			var flightArrivalDayAddSpan = document.createElement( "SPAN" );
			flightArrivalDayAddSpan.className = "tc06 b";
			flightArrivalDayAddSpan.appendChild( document.createTextNode( "  Next Day Arrival" ) );
			flightSegmentTimeTD.appendChild( flightArrivalDayAddSpan );
		}
		
		var flightSegmentServiceClassTD = document.createElement( "TD" );
		flightSegmentServiceClassTD.className = "fs10 b";
		flightSegmentServiceClassTD.appendChild( document.createTextNode(serviceClassDescription ) );
		
		inboundItineraryRow.appendChild( flightSegmentCityTD );
		inboundItineraryRow.appendChild( connectionTD );
		inboundItineraryRow.appendChild( flightSegmentTimeTD );
		inboundItineraryRow.appendChild( flightSegmentServiceClassTD );

		flightTableTBody.appendChild( inboundItineraryRow );
	}
	
	flightTable.appendChild( flightTableTBody );
	mainDiv.appendChild( flightTable );
	
	//Check Seat Availability , Detail Link and Chaneg Flight link Div ( Main Div ).
	var allFlightLinksDiv = document.createElement( 'DIV' );
	allFlightLinksDiv.className = "note h12 mt10 mb-05";
	
	//Check Seat Availability and Detail Link Div. 
	var flightDetailLinksDiv = document.createElement( 'DIV' );
	flightDetailLinksDiv.className = "fll";
	
	//Available Link
	var availableLink = document.createElement( 'A' );
	availableLink.className = "u";
	availableLink.href ="javascript:;";
    availableLink.onclick = function() {  loadFlightSeatMapPopupDiv( flightResult.uid, '', true ); };
	availableLink.appendChild( document.createTextNode( "Check Seat Availability" ) );
	
	//Separation between seat availability link and flight detail link.
	var separationImg = document.createElement( 'IMG' );
	separationImg.src = _webLoc + "/shared/images/core/spacer.gif";
	separationImg.alt = "";
	separationImg.width = "25";
	separationImg.height = "2";
		
	//Flight Detail Link 
	var detailLink = document.createElement( 'A' );
	detailLink.className = "u";
	detailLink.href ="javascript:;";
    detailLink.onclick = function() { loadFlightDetails( flightResult.uid, '', 0, true ); };
	detailLink.appendChild( document.createTextNode( "See Flight Details" ) );

	flightDetailLinksDiv.appendChild( availableLink );
	flightDetailLinksDiv.appendChild( separationImg );
	flightDetailLinksDiv.appendChild( detailLink );

	//Change Flight Link Div.
	var changeFlightsLinkOuterDiv = document.createElement( 'DIV' );
	
	//Hide "change flights" link in case of agent only packages through consumer app.
	//These packages cant be booked throug consumer site, avoid this flow by hiding link. 
	if( packageInfo.displayType != PACKAGE_DISPLAY_TYPE_AGENT_ONLY ) {
		changeFlightsLinkOuterDiv.className = "tar changeFlights";
		var changeFlightsLinkInnerDiv = document.createElement( "DIV" );

		//Change Flight Link.
		var changeFlightLink = document.createElement( 'A' );
		changeFlightLink.href ="javascript:;";
		changeFlightLink.onclick = function() { changeFlight( flightResult.uid , true, packageInfo.packageId ); };
		changeFlightLink.appendChild( document.createTextNode( "Change Flights" ) );
		changeFlightsLinkInnerDiv.appendChild( changeFlightLink );

		changeFlightsLinkOuterDiv.appendChild( changeFlightsLinkInnerDiv );	
	}

	var afterFlightLinksBR = document.createElement( 'BR' );
	afterFlightLinksBR.clear = "all";
		
	allFlightLinksDiv.appendChild( flightDetailLinksDiv );
	allFlightLinksDiv.appendChild( changeFlightsLinkOuterDiv );
	allFlightLinksDiv.appendChild( afterFlightLinksBR );
	
	mainDiv.appendChild( allFlightLinksDiv );
	
	var spacerImgDiv = document.createElement( 'DIV' );
	var spacerImg = document.createElement( 'IMG' );
	spacerImg.src = _webLoc + "/shared/images/core/spacer.gif";
	spacerImg.alt = "";
	spacerImgDiv.appendChild( spacerImg );
	mainDiv.appendChild( spacerImgDiv );
}

/*
 * Loads Car result category information into car result section.
 */
function loadCarResultDiv( mainDiv, carResult ) {
	var carTable = document.createElement( "TABLE" );
	carTable.className = "wp95 fs11";
	carTable.cellPadding = '2';
	carTable.cellSpacing = '1';
	carTable.border="0";
	
	var carTableTBody = document.createElement( "TBODY" );
	var carRow1 = document.createElement( "TR" );
	
	var carRow1TD1 = document.createElement( "TD" );
	carRow1TD1.className = "tac";
	
	//Car Icon
	var carImg = document.createElement( 'IMG' );
	carImg.src = _webLoc + "/shared/images/core/logos/car/" + carResult.carCompanyName + ".gif";
	carImg.alt = carResult.carCompanyName;
	carRow1TD1.appendChild( carImg );

	//Car City
	var carRow1TD2 = document.createElement( "TD" );
	carRow1TD2.className = "b";
	carRow1TD2.appendChild( document.createTextNode( carResult.pickupCity ) );

	//Car Category
	var carRow1TD3 = document.createElement( "TD" );
	carRow1TD3.className = "b";
	carRow1TD3.appendChild( document.createTextNode( carResult.categoryName + " Car" ) );
	
	//Car Pick Up Date and Drop off Date.
	var carRow1TD4 = document.createElement( "TD" );
	carRow1TD4.className = "w306";
	carRow1TD4.appendChild( document.createTextNode( "Pick-up: " ) );
	
	var carPickUpSpan = document.createElement( "SPAN" );
	carPickUpSpan.className = "b";
	carPickUpSpan.appendChild( document.createTextNode( carResult.pickupDate ) );
	carRow1TD4.appendChild( carPickUpSpan );
	
	var separationImg = document.createElement( 'IMG' );
	separationImg.src = _webLoc + "/shared/images/core/spacer.gif";
	separationImg.alt = "";
	separationImg.width = "5";
	carRow1TD4.appendChild( separationImg );
	
	carRow1TD4.appendChild( document.createTextNode( " Drop-Off: " ) );
	
	var carDropOffSpan = document.createElement( "SPAN" );
	carDropOffSpan.className = "b";
	carDropOffSpan.appendChild( document.createTextNode( carResult.dropoffDate ) );
	carRow1TD4.appendChild( carDropOffSpan );
	
	carRow1.appendChild( carRow1TD1 );
	carRow1.appendChild( carRow1TD2 );
	carRow1.appendChild( carRow1TD3 );
	carRow1.appendChild( carRow1TD4 );
	
	carTableTBody.appendChild( carRow1 );
	
	carTable.appendChild( carTableTBody );
	mainDiv.appendChild( carTable );
}

/*
 * Loads tour information into tour result section of package result.
 * */
function loadTourResultDiv( mainDiv, tourResult ) {
	if( tourResult.length > 0 ) {
		// add divider between car and tour.
		var tourSpacerImgDiv = document.createElement( 'DIV' );
		tourSpacerImgDiv.className = "divider p05";
	
		var tourSpacerImg = document.createElement( 'IMG' );
		tourSpacerImg.src = _webLoc + "/shared/images/core/spacer.gif";
		tourSpacerImg.alt = "";
		tourSpacerImgDiv.appendChild( tourSpacerImg );
		mainDiv.appendChild( tourSpacerImgDiv );
		
		var tourTable = document.createElement( "TABLE" );
		tourTable.className = "wp95 fs11";
		tourTable.cellPadding = '1';
		tourTable.cellSpacing = '0';
		tourTable.border="0";
		
		var tourTableTBody = document.createElement( "TBODY" );
		var tourRow1 = document.createElement( "TR" );
		
		//SightSeeing Header.
		var tourRow1Td1 = document.createElement( "TD" );
		tourRow1Td1.className = "b";
		tourRow1Td1.colSpan = "2";
		tourRow1Td1.appendChild( document.createTextNode( "Sightseeing Tours Included:" ) );
		
		tourRow1.appendChild( tourRow1Td1 );
		
		tourTableTBody.appendChild( tourRow1 );
		
		// create tour results section for each tour item.
		for( var tourIndex = 0; tourIndex < tourResult.length; tourIndex++ ) {
			var tourDescriptionRow = document.createElement( 'TR' );
			
			var tourDescriptionRowTD1 = document.createElement( "TD" );
			tourDescriptionRowTD1.className = "pl25";
			 
			if( tourResult[tourIndex].itineraryCode == '' ) {
				tourDescriptionRowTD1.appendChild( document.createTextNode( decodeHTML( tourResult[tourIndex].description ) ) );
			} else {
				var descrp1Link = document.createElement( 'A' );
				descrp1Link.className = "u";
				descrp1Link.href ="javascript:;";
				descrp1Link.onclick = new Function( "loadSightseeingPopup('" + tourResult[tourIndex].tourId + "','" + tourResult[tourIndex].itineraryCode + "')" );

				descrp1Link.appendChild( document.createTextNode( decodeHTML( tourResult[tourIndex].description ) ) );
				tourDescriptionRowTD1.appendChild( descrp1Link );
			}
			
			var tourDescriptionRowTD2 = document.createElement( "TD" );
			tourDescriptionRowTD2.className = "w306 b";
			tourDescriptionRowTD2.appendChild( document.createTextNode( tourResult[tourIndex].date ) ); 
			
			tourDescriptionRow.appendChild( tourDescriptionRowTD1 );
			tourDescriptionRow.appendChild( tourDescriptionRowTD2 );
			
			tourTableTBody.appendChild( tourDescriptionRow );
		}
		tourTable.appendChild( tourTableTBody );
		mainDiv.appendChild( tourTable );
	}
}

/*
 * Loads transfer information( which displays greeting information also ) 
 * into transfer result section of package result.
 * 
 * */
function loadTransferResultDiv( mainDiv, transferResult, isTransferDisplay  ) {
	var transferTable = document.createElement( "TABLE" );
	transferTable.className = "fs11";
	transferTable.width = "95%";
	transferTable.cellPadding = '0';
	transferTable.cellSpacing = '0';
	transferTable.border="0";
	
	var transferTableTBody = document.createElement( "TBODY" );
	var transferRow1 = document.createElement( "TR" );
	var transferRow2 = document.createElement( "TR" );
	
	//Transfer Type
	var transferRow1TD1 = document.createElement( "TD" );
	transferRow1TD1.className = "b";
	transferRow1TD1.colSpan = "2";
	if( isTransferDisplay ) {
		transferRow1TD1.appendChild( document.createTextNode( transferResult.transferType + " :" ) );
	} else {
		transferRow1TD1.appendChild( document.createTextNode( "Arrival Greeting :" ) );
	}
	
	//Transfer Description
	var transferRow2TD1 = document.createElement( "TD" );
	transferRow2TD1.className = "pl25";
	transferRow2TD1.appendChild( document.createTextNode( decodeHTML( transferResult.description ) ) );
	
	//Transfer Date
	var transferRow2TD2 = document.createElement( "TD" );
	transferRow2TD2.className = "w310 b";
	transferRow2TD2.appendChild( document.createTextNode( transferResult.date ) );
	
	transferRow1.appendChild( transferRow1TD1 );
	
	transferRow2.appendChild( transferRow2TD1 );
	transferRow2.appendChild( transferRow2TD2 );
	
	transferTableTBody.appendChild( transferRow1 );
	transferTableTBody.appendChild( transferRow2 );
	
	transferTable.appendChild( transferTableTBody );
	mainDiv.appendChild( transferTable );
}

/*
 *Function which displays multi city packages.  
 */
function showPackagesWithoutLeadInPrice( pageNumber ) {
	window.scrollTo( 0, 0 );
	document.getElementById( "searchResults" ).innerHTML = "";
	var packageResults = _packagesWithCityIndex[ _selectedCityTab - 1 ];
	packageResults.sort( sortPackageResults );
	var numberOfPackages = packageResults.length;
	var searchResultsDiv = document.getElementById( "searchResults" );
	if( numberOfPackages == 0  ) {
		searchResultsDiv.innerHTML = "<div class='tal p10 pb15 tc02 b'>No packages were found for the given search criteria. Please try again using different dates and/or destination information.</div>";
		return;    		
	}
	var spacerImage = document.createElement( 'IMG' );
	spacerImage.src = _webLoc + "/shared/images/core/spacer.gif";
	spacerImage.alt = "";
	spacerImage.height = "10";
    searchResultsDiv.appendChild( spacerImage );
	for( var packageCounter = ( pageNumber*NUMBER_OF_PACKAGE_RESULTS_WITHOUT_LIP_PER_PAGE- NUMBER_OF_PACKAGE_RESULTS_WITHOUT_LIP_PER_PAGE ); packageCounter < ( pageNumber* NUMBER_OF_PACKAGE_RESULTS_WITHOUT_LIP_PER_PAGE ); packageCounter++ ) {
	    if( packageCounter < numberOfPackages  ){
		var packageId = decodeHTML( packageResults[ packageCounter ].packageId );
		var signLine1 = decodeHTML( packageResults[ packageCounter ].signLine1 );
		var signLine2 = decodeHTML( packageResults[ packageCounter ].signLine2);
		var signLine3 = decodeHTML( packageResults[ packageCounter ].signLine3);
		var signLine4 = decodeHTML( packageResults[ packageCounter ].signLine4);
		var summary = decodeHTML( packageResults[ packageCounter ].summary );
		
		var packageSearchResultDiv = document.createElement( 'DIV' );
		packageSearchResultDiv.id = "packageSearchResultsDiv";
		packageSearchResultDiv.className = (packageCounter % 2 == 0) ? 'bgc11' : '';
		searchResultsDiv.appendChild( packageSearchResultDiv );
		
		var packageResultsAnchorDiv = document.createElement( 'DIV' );
		packageResultsAnchorDiv.className = "fll pr10";
		var link1 = document.createElement( 'A' );
		link1.href ="javascript:;";
		link1.onclick = new Function( "parent.loadRightContentPackage('" + selectedDestinationCode + "', '" + selectedRegionCode + "',null , null,'" + packageId + "',null ,null , null, true );" );
		
		var image1 = document.createElement( 'IMG' );
		image1.src = _webLoc + "/shared/images/package/destination/" + packageId + "/" + packageId + "_F_1.jpg";
		image1.alt = ( signLine1 ) + " Thumbnail";
		image1.width = "146";
		image1.height = "85";
		link1.appendChild( image1 );
		packageResultsAnchorDiv.appendChild( link1 );
		
		var packageResultsDataDiv = document.createElement( 'DIV' );
		packageResultsDataDiv.className = "fll w372";
		var span1 = document.createElement( 'SPAN' );
		packageResultsDataDiv.appendChild( span1 );
		span1.className = "fs12";

		var link2 = document.createElement( 'A' );
		link2.href = "javascript:;"
		link2.onclick = new Function( "parent.loadRightContentPackage('" + selectedDestinationCode + "', '" + selectedRegionCode + "',null , null,'" + packageId + "',null ,null , null, true );" );
		
		link2.className = "title pb02 fs14";
		link2.appendChild( document.createTextNode( signLine1 ));
		span1.appendChild( link2 );
		var br = document.createElement( 'br' );
		packageResultsDataDiv.appendChild( span1 );
		packageResultsDataDiv.appendChild( br );
		if( summary && trim(summary) != "" ) { 
			var summaryDiv = document.createElement( 'DIV' );
			summaryDiv.className = "fs11 pb02";
			summaryDiv.appendChild( document.createTextNode( summary ));
			packageResultsDataDiv.appendChild( summaryDiv );
		} else {
			if( signLine2 != "" ) {
				var signLine2Div = document.createElement( 'DIV' );
				signLine2Div.className = "fs11 pb02";
				signLine2Div.appendChild( document.createTextNode( signLine2 ));
				packageResultsDataDiv.appendChild( signLine2Div );
			}
			if( signLine3 != "" ) {
				var signLine3Div = document.createElement( 'DIV' );
				signLine3Div.className = "fs11 pb02";
				signLine3Div.appendChild( document.createTextNode( signLine3 ));
				packageResultsDataDiv.appendChild( signLine3Div );
			}
			if( signLine4 != "" ) {
				var signLine4Div = document.createElement( 'DIV' );
				signLine4Div.className = "fs11 pb02";
				signLine4Div.appendChild( document.createTextNode( signLine4 ));
				packageResultsDataDiv.appendChild( signLine4Div );
			}
		}
		packageSearchResultDiv.appendChild( packageResultsAnchorDiv );
		packageSearchResultDiv.appendChild( packageResultsDataDiv );

        
		var packageResultsDataDiv1 = document.createElement( 'DIV' );
		packageResultsDataDiv1.className = "flr";
		
		if(packageResults[ packageCounter ].displayType != PACKAGE_DISPLAY_TYPE_AGENT_ONLY ) {
    		var link3 = document.createElement( 'A' );
    		link3.className = "button";
    						
    		var image2 = document.createElement( 'IMG' );
    		image2.src = _webLoc + "/shared/images/core/buttons/book-it-red-btn.gif";
    		image2.alt = "Book It Button";
    		link3.appendChild( image2 );
    		link3.href = "javascript:;";
			image2.onclick = new Function("loadSearchPopupOrSearchResults('" + packageId + "');" );    		
    		packageResultsDataDiv1.appendChild( link3 );
    		
    		var packageResultsDataDiv2 = document.createElement( 'DIV' );
    		packageResultsDataDiv2.className = "pt45 pb10 tar";
    		var link4 = document.createElement( 'A' );
    		link4.className = "u";
    		link4.href = "javascript:;";
    		link4.onclick = new Function( "parent.loadRightContentPackage('" + selectedDestinationCode + "', '" + selectedRegionCode + "',null , null,'" + packageId + "',null ,null , null, true );" );
    		link4.appendChild( document.createTextNode( "View Details" ));
    		packageResultsDataDiv2.appendChild( link4 );
    		packageResultsDataDiv1.appendChild( packageResultsDataDiv2 );
		} else {
    		var image3 = document.createElement( 'IMG' );
    		image3.src = _webLoc + "/shared/images/core/icons/cta.gif";    		
    		image3.width = "129";
    		image3.height = "45";
    		image3.alt = "To Book Call 1-877-849-2790 Thumbnail";
    		packageResultsDataDiv1.appendChild( image3 );
		}
		
		packageSearchResultDiv.appendChild( packageResultsDataDiv1 );
		
		var br1 = document.createElement( 'br' );
    	br1.clear = "all"
    	packageSearchResultDiv.appendChild( br1 );
    	
    	var dividerDiv = document.createElement( 'DIV' );
    	dividerDiv.className = "divider";
    	var image3 = document.createElement( 'IMG' );
    	image3.src = _webLoc + "/shared/images/core/spacer.gif";
    	image3.alt = "";
    	image3.width = "1";
    	image3.height = "20";
    	dividerDiv.appendChild( image3 );
    	searchResultsDiv.appendChild( dividerDiv );
    	}
	}
	var numberOfPages = document.getElementById( "numberOfPages" ).value;
	document.getElementById( "selectedPage" ).value = pageNumber;
	showPagination(pageNumber, numberOfPages, "top");
	showPagination(pageNumber, numberOfPages, "bottom");	
}

function loadPackageResults( selectedCityTab ) {
	_selectedCityTab = selectedCityTab;
	if(  selectedCityTab == 1 ) {
		var packageResults = eval ( packageResultsJSON );
		_packagesWithCityIndex[ selectedCityTab - 1] = packageResults;
		var numberOfPackages = packageResults.length;
		createPagination( numberOfPackages, "top" );
		createPagination( numberOfPackages, "bottom" );
		if( isBookablePackage && isDestinationBookableForConsumer( selectedDestinationCode.toUpperCase() ) ) {
			showPackagesWithLeadInPrice( 1 );
		} else {
			showPackagesWithoutLeadInPrice( 1 );
		}
	} else {
		if( !isNull( _packagesWithCityIndex[ selectedCityTab - 1 ] ) ) {
			var numberOfPackages = _packagesWithCityIndex[ selectedCityTab - 1 ].length;
			createPagination( numberOfPackages, "top" );
			createPagination( numberOfPackages, "bottom" );
			showPackagesWithoutLeadInPrice( 1 );
		} else {
			getPackageResults( selectedCityTab );
		}
	}
}

 /* This method to get the multicity packages from Serever. 
 *+2 or more cities tab selected get all the packages, which have more than 2 cities.
 *+1 city tab selected get all the packages, which have exactly 2 cities.
 */  
function getPackageResults( selectedCityTab ) {
	_selectedCityTab = selectedCityTab;
	var queryString = "pr=2";
	if( selectedCityTab == 2 ) {
		var numberOfCities = ( selectedCityTab - 1 );
		queryString += "&numberOfCities=" + numberOfCities + "&operator=" + OPERATOR_TYPE_GREATER_THAN;
	}
	makeAjaxCall( 'packageResults.act', queryString , null, null, 'callbackGetPackageResults', '' );
}

function callbackGetPackageResults(  message, errorCode, packageJsonResults ) {
	if( message != '' ) {
		showMessage( message, errorCode, 'dataContent' );
	}  else {
		var packageResults = eval( packageJsonResults );
		_packagesWithCityIndex[ _selectedCityTab - 1 ] = packageResults;
		var numberOfPackages = packageResults.length;
		createPagination( numberOfPackages, "top" );
		createPagination( numberOfPackages, "bottom" );
		showPackagesWithoutLeadInPrice( 1 );
	}
}

function createPagination( numberOfPackages, divLocation ) {
	var paginationDiv = document.getElementById( divLocation + "PaginationDiv" );
	paginationDiv.innerHTML = "";
	if( numberOfPackages > 0 ) {
		paginationDiv.style.display = "inline";
	} else {
		paginationDiv.style.display = "none";
	}
	var pageSpan = document.createElement( "SPAN" );
	pageSpan.className = "b";
	pageSpan.appendChild( document.createTextNode( "Pages:" ) );
	var pageSpacerImg = document.createElement( "IMG" );
	pageSpacerImg.src = _webLoc + "/shared/images/core/spacer.gif";
	pageSpacerImg.alt = "";
	pageSpacerImg.width = "5";	 
	pageSpan.appendChild( pageSpacerImg );
	paginationDiv.appendChild( pageSpan );
	var numberOfPackagesPerPage = ( ( _selectedCityTab == 1 && isBookablePackage )? NUMBER_OF_PACKAGE_RESULTS_WITH_LIP_PER_PAGE : NUMBER_OF_PACKAGE_RESULTS_WITHOUT_LIP_PER_PAGE ) ;
	var numberOfPages = Math.ceil( numberOfPackages/numberOfPackagesPerPage );
	for( var pageIndex = 1; pageIndex <= numberOfPages ; pageIndex++ ) {
		//Previous Link
		var previousLink = document.createElement( 'A' );
		previousLink.className = "u";
		previousLink.id = divLocation + "previous";
		previousLink.style.display = "none";
    	previousLink.href = "javascript:;";
    	previousLink.onclick = function() { movePrevious(); };
    	
		previousLink.appendChild( document.createTextNode( "Previous" ) );
		paginationDiv.appendChild( previousLink );
		
		//Spacer Image between previous link and Page Number.
		var previousSpacerImg = document.createElement( "IMG" );
		previousSpacerImg.src = _webLoc + "/shared/images/core/spacer.gif";
		previousSpacerImg.alt = "";
		previousSpacerImg.width = "5";
		
		paginationDiv.appendChild( previousSpacerImg );
		
		// Page Number Div With Link.
		var pageNumberDiv = document.createElement( "DIV" );
		pageNumberDiv.style.display = "inline";
		pageNumberDiv.id = divLocation + "page_" + pageIndex;
				
		var pageNumberLink = document.createElement( 'A' );
		pageNumberLink.id = divLocation + "anchorId_" + pageIndex;
		pageNumberLink.appendChild( document.createTextNode( pageIndex ) );
		pageNumberLink.href = "javascript:;";
		    
    	pageNumberLink.href = "javascript:;";
    	if( _selectedCityTab == 1 && isBookablePackage ) {
    		pageNumberLink.onclick = new Function("showPackagesWithLeadInPrice('" +  pageIndex + "');");
    	} else {
    		pageNumberLink.onclick = new Function("showPackagesWithoutLeadInPrice('" +  pageIndex + "');");    		
    	}
    	
	    if( pageIndex == 1 ) {
	    	pageNumberLink.className = "pagenos-sel";
	    } else {
	    	pageNumberLink.className = "pagenos";
	    }
	    pageNumberDiv.appendChild( pageNumberLink );    
	    paginationDiv.appendChild( pageNumberDiv );
	    
	    if( pageIndex != numberOfPages ) {
	    	paginationDiv.appendChild( document.createTextNode( "|" ) );
	    } else {
		    var previousSpacerImg = document.createElement( "IMG" );
			previousSpacerImg.src = _webLoc + "/shared/images/core/spacer.gif";
			previousSpacerImg.alt = "";
			previousSpacerImg.width = "5";
			paginationDiv.appendChild( previousSpacerImg );
			
			var nextLink = document.createElement( 'A' );
			nextLink.className = "u";
			nextLink.style.display = "inline";
			nextLink.id = divLocation + "next";
	    	nextLink.href = "javascript:;";
	    	nextLink.onclick = function() { moveNext(); };
	    	
			nextLink.appendChild( document.createTextNode( "Next" ) );
			paginationDiv.appendChild( nextLink );
	    }
	}
	document.getElementById( "numberOfPages" ).value = numberOfPages;
}

function changeFlight( itemUid, isForLIP, packageId ) {
	var additionalSearchPopupDivContainer = document.getElementById( 'additionalSearchResultsPopupDivContainer' ); 
	if( isNull( additionalSearchPopupDivContainer ) ) {
		additionalSearchResultsPopupDivContainer = createPopupDiv('additionalSearchResultsPopupDivContainer', 0, 0, 703, 200, false, true,  "tal popupDiv");
	}

	var queryString = 'fr=14';
	queryString += '&uid=' + itemUid;
	queryString += '&forLIP=' + isForLIP;
	queryString += '&packageId=' + packageId;
	//Submit Ajax call with '/vp/booking/searchFlights/<destinationCode>/<regionCode>/<packageId>' as the description to be passed into Google Analytics
	var trackingText = '/vp/booking/searchFlights/' + _destinationCode + '/'+ _regionCode + '/package/' + packageId;
	asynchronousRequest = new AsynchronousRequest();
	asynchronousRequest.url = _webLoc + '/flightResults.act';
	asynchronousRequest.queryString = queryString;
	asynchronousRequest.useAjax = true;
	asynchronousRequest.target = 'additionalSearchResultsPopupDivContainer';
	asynchronousRequest.callbackFunctionName = 'callbackLoadAdditionalSearchResultsPopup';
	if( trackingText && (trackingText != '' )) {
			asynchronousRequest.postCallbackScript = "pageTracker._trackPageview('" + trackingText + "')";
	}
	var splashScreenRequest = new SplashScreenRequest();
	splashScreenRequest.splashScreenText = "Please Wait...";
	asynchronousRequest.splashScreenRequest = splashScreenRequest;
	asynchronousRequest.splashScreenDisplayFunctionName = "displaySearchingPopup";
	asynchronousRequest.splashScreenHideFunctionName = "hideSearchingPopup";
	disableElement( 'dataContent', true);
	makeAjaxCallWithRequest(asynchronousRequest, '');
}

function callbackLoadAdditionalSearchResultsPopup() {
	if( !showMessage( this.errorMessage, this.errorCode, 'dataContent' ) ) {
		var additionalSearchResultsPopup = document.getElementById( 'additionalSearchResultsPopupDiv' );
		if( additionalSearchResultsPopup ) { 
			additionalSearchResultsPopupDivContainer.style.height = additionalSearchResultsPopup.style.height;
			additionalSearchResultsPopupDivContainer.style.width = additionalSearchResultsPopup.style.width;
			showBlock( 'additionalSearchResultsPopupDivContainer' );
			positionBlockCentrally( 'additionalSearchResultsPopupDivContainer' );
			disableElement( 'dataContent', true );
		}
		return true;
	}
	return false;
}
/*function callbackShowAdditionalFlightResults( message, errorCode ) {
	showMessage( message, errorCode, 'dataContent' );
	loadTripSummary();
}*/

function isDestinationBookableForConsumer( destination ) {
    if( destination == "AUSTRALIA" || destination == "NEWZEALAND" || 
        destination == "FIJI" || destination == "TAHITIANISLANDS" || destination == "COOKISLANDS" ) {
          return false;
    }
    return true;
}

/* On click of back button load the pacakge results; from package details page*/
function reLoadPackageResults(){
	var queryString = 'pr=0';
	makeAjaxCall( 'packageResults.act', queryString, null, 'rightContent', 'callbackReLoadPackageResults', '' );
}

function callbackReLoadPackageResults( message, errorCode ) {
	showMessage( message, errorCode, 'dataContent' );
	return true;
}

function isMultiCityTabEnabled() {
	var isMultiCityDestination = false;
	for( var index = 0; index < DEFAULT_MULTI_DESTINATIONS.length; index++ ) {
		if( DEFAULT_MULTI_DESTINATIONS[index].toLowerCase() == selectedDestinationCode.toLowerCase() ){
			isMultiCityDestination = true;
		}
	}
	return isMultiCityDestination;
}

/* This function ignore the new changes in adl. flight results popup of LIP package result screens */
function ignoreChangesFromPopup( productUid ) {
	disableElement( 'additionalSearchResultsPopupDivContainer', false );
	removeElement( 'additionalSearchResultsPopupDivContainer' )	
	disableElement( 'dataContent', false );
	var queryString = 'fr=15';
	queryString += '&uid=' + productUid;
	makeAjaxCall( 'flightResults.act', queryString, null, 'rightContent', 'callbackIgnoreChangesFromPopup', '');
}

/* call back function of ignore changes popup*/
function callbackIgnoreChangesFromPopup( message, errorCode ) {
	showMessage( this.errorMessage, this.errorCode, 'dataContent' );
	return true;
}

/* This function apply the new changes in adl. flight results popup of LIP package result screens. */
function applyChangesFromPopup(  productUid ) {
	disableElement( 'additionalSearchResultsPopupDivContainer', false );
	removeElement( 'additionalSearchResultsPopupDivContainer' )	
	disableElement( 'dataContent', false );
	var queryString = 'fr=16';
	queryString += '&uid=' + productUid;
	makeAjaxCall( 'flightResults.act', queryString, null, 'mainContent', 'callbackFlightChangeShowMessage', '' );
}

/* call back function of apply changes popup*/
function callbackFlightChangeShowMessage() {
	showMessage( this.errorMessage, this.errorCode, 'dataContent' );
	var queryString = 'pr=0';
	makeAjaxCall( 'packageResults.act', queryString, null, 'rightContent', 'callbackApplyChangesFromPopup', '' );
}

/* Load package search results after apply changes from additional fligt results. */
function callbackApplyChangesFromPopup( message, errorCode){
	showMessage( message, errorCode, 'dataContent' );
	return true;
}

/* This function closes the flight related popups. */
function closeFlightPopups( popupDiv ){
	removeElement( popupDiv );
	var additionalSearchResultsPopup = document.getElementById( 'additionalSearchResultsPopupDivContainer' );
	if( additionalSearchResultsPopup ) { 
		disableElement('additionalSearchResultsPopupDivContainer', false);
	}else {
		disableElement( 'dataContent', false );
	}
}var _event;
var _cityName;
var _departureCityString;
var _fromWidget;
var searchedDestinationCode;
var searchedRegionCode;
var _packageId;
var airportInfos;
var _fromMenu;
var _hotelName;
var _selectedDestination;
var BOOKABLE_DESTINATION = new Array( 'AUSTRALIA', 'CARIBBEAN', 'EUROPE', 'HAWAII', 'MEXICO', 'NEW ZEALAND', 'FIJI', 'TAHITI', 'COOK ISLANDS' );

/* creates a popup div, with package search criteria information populated.*/
function initiatePackageSearch( packageId , fromWidget ) {
	if ( fromWidget == undefined ) {
		//_fromMenu = true;
		var queryString = "";
		queryString += "sp=4";
		queryString += '&packageId=' + packageId;
		makeAjaxCall( 'searchPackage.act', queryString, null, 'mainContent', 'callbackIsFromWidget', '' );		
	} else {
		// create pop up div for search criteria.
		var searchPopupDivContainer = document.getElementById('searchPopupDivContainer');
		if( isNull( searchPopupDivContainer ) ) {
			searchPopupDivContainer = createPopupDiv('searchPopupDivContainer', 0, 0, 703, 200, false, true,  "");
		}
		searchPopupDivContainer.style.height = "450";
	
		// create action code to open search pop up.
		var queryString = 'sp=0';
		queryString += '&packageId=' + packageId;
		queryString += '&fromMenu='+_fromMenu
		//Load the search popup with '/vp/booking/searchPackage///<packageId>' as the description to be passed into Google Analytics		
		//The three '/' are put on purpose as place holders to retain the general format
		makeAjaxCall( 'searchPackage.act', queryString, null, 'searchPopupDivContainer', 'callbackInitiatePackageSearch', '/vp/booking/searchPackage///package/' + packageId );
	}
}

function callbackInitiatePackageSearch() {
	if(!showMessage(this.errorMessage, this.errorCode, 'dataContent')) {
		var searchPopupDiv = document.getElementById('searchPopupDiv');
		if(searchPopupDiv) {
			searchPopupDivContainer.style.height = searchPopupDiv.style.height;
			showBlock('searchPopupDivContainer');
			positionBlockCentrally('searchPopupDivContainer');	
			disableElement('dataContent', true);
			searchPopupDiv.focus();
		}	
		return true;
	}
	return false;
}

function callbackIsFromWidget( fromWidget, packageId ) {
	if(!showMessage(this.errorMessage, this.errorCode, 'dataContent')) {
		if( fromWidget == "true" ){
			_fromMenu = false;
			loadSearchPopupOrSearchResults( packageId );
		}else {
			_fromMenu = true;
			initiatePackageSearch( packageId, fromWidget );
		}
		return true;
	}
	return false;
}

/*
searches package with given search criteria, available from search popup div.
validates all user entered information.
sends request to searchPackage activity through ajax call through query string.
*/
function searchPackage( packageId, includeFlightItinerary, numberOfCities, fromMenu ) {
	clearErrorElements();
	//action code to do package search.
	var queryString = 'sp=1';

	var departureCity = '';
	var serviceClass = '';
	var nonStop = false;
	var connectionOne = false;
	var connectionTwo = false;
	var numberOfNightsInEachCity = "";
	var adults = "";
	var children = "";
	var childrenAges = "";
	var childSeatFlags = "";
	var  flightConnections = -1;
	var isFlightMandatory;
	var departureCityCode ="";

	//flight itinerary fields.
	var departureCityField = document.getElementById( "departureCityText" );
	var departureCityCodeFiled = document.getElementById( "departureCityCode" );
	var serviceClassField = document.getElementById( "serviceClass" );
	var nonStopField = document.getElementById( "nonStop" );

	//Hotel components fields.
	var departureDate = document.getElementById( "departureDate" ).value;
	//var departureTime = document.getElementById( "departureTime" ).value;
	var returnDate = document.getElementById( "returnDate" ).value;
	//var returnTime = document.getElementById( "returnTime" ).value;
	var hotelRooms = document.getElementById( "numberOfRooms" ).value;

	//Checking for !null and !undefined for flight itinerary fields.
	if ( departureCityField != null && departureCityField != undefined ){
		departureCity = departureCityField.value;
	}
	if ( departureCityCodeFiled != null && departureCityCodeFiled != undefined ){
		departureCityCode = departureCityCodeFiled.value;
	}
	if ( serviceClassField != null && serviceClassField != undefined ){
		serviceClass = serviceClassField.value;
	}
	if ( nonStopField != null && nonStopField != undefined ){
		nonStop = nonStopField.checked;
	}

	if ( includeFlightItinerary == "true" ) {
		isFlightMandatory = document.getElementById( "flightItineraryCheckbox" ).checked;
	}else{
		isFlightMandatory = false;
	}

	if( isFlightMandatory ) {
		if( trim( departureCity ) == '' ){
			departureCityCode = "";
		}
		
		if(  trim( departureCityCode ) == '' ) {
			showErrorMessage('Please select a departure city from the list', 'searchPopupDivContainer', 'departureCityText', '1px solid #7f9db9');
			return false;
		}else if( serviceClass == null || serviceClass == '' ) {
			showErrorMessage('Please select a service class.', 'searchPopupDivContainer', 'serviceClass', '1px solid #7f9db9');
			return false;
		}

		queryString += '&departureCity=' + departureCity;
		queryString += '&departureCityCode=' + departureCityCode;
		queryString += '&flightConnections=' + flightConnections;
		queryString += '&serviceClass=' + serviceClass;
	}
	if( departureDate == null || departureDate == 'mm/dd/yyyy' || departureDate == '' ) {
		showErrorMessage('Please select a departure date.', 'searchPopupDivContainer', 'departureDate', '1px solid #7f9db9');
		return false;
	} else if( isDate( 'departureDate', 'searchPopupDivContainer' ) == false ){
		document.getElementById( 'departureDate' ).value = "mm/dd/yyyy";
		document.getElementById( 'departureDate' ).select();
		return false;
	} else if( isPastDate( 'departureDate' ) ) {
		return false;
	}
	if( returnDate == null || returnDate == 'mm/dd/yyyy' || returnDate == '' ) {
		showErrorMessage('Please select a return date.', 'searchPopupDivContainer', 'returnDate', '1px solid #7f9db9');
		return false;
	} else if( isDate( 'returnDate', 'searchPopupDivContainer' ) == false ) {
		document.getElementById( 'returnDate' ).value = "mm/dd/yyyy";
		document.getElementById( 'returnDate' ).select();
		return false;
	}
	var isNightOptionBlank = false;
	var nightOptionString ="";
	for( var cityIndex = 1; cityIndex <= numberOfCities ; cityIndex++ ) {
		var nightsInCity = trim( document.getElementById( "numberOfNights" + cityIndex ).value );
		if ( nightsInCity == "" ){
			isNightOptionBlank = true;
			nightOptionString ='numberOfNights' + cityIndex;
			break;
		} else {
			numberOfNightsInEachCity += nightsInCity + ",";
		}
	}
	if( isNightOptionBlank ){
		showErrorMessage('Total number of nights should not exceed sum of nights in each city.', 'searchPopupDivContainer', nightOptionString, '1px solid #7f9db9');
		return false;
	}
	var isPassengersExceededPerRoom = false;
	for( var roomCounter = 1; roomCounter <= hotelRooms; roomCounter++ ){
		var adultsInRoom = document.getElementById( "adultsInRoom_" + roomCounter ).value;
		var childrensPerRoom = document.getElementById( "childrenInRoom_" + roomCounter ).value;

		if ( adultsInRoom > 4 ){
			isPassengersExceededPerRoom = true;
		} else if( ( parseInt( adultsInRoom )+ parseInt( childrensPerRoom ) ) > 5 ){
			isPassengersExceededPerRoom = true;
		}
		adults += adultsInRoom + ",";
		children += childrensPerRoom + ",";
		for ( var childCounter = 1; childCounter <= childrensPerRoom; childCounter++ ){
			var childrenAgesPerRoom =document.getElementById( "childAge_" + childCounter + "_" + roomCounter ).value;
			if(childrenAgesPerRoom < 0) {
					var msg ="Please select the age for child " + childCounter + " in room " + roomCounter;
					showErrorMessage( msg, 'searchPopupDivContainer', "childAgeForWidget_" + childCounter + "_" + roomCounter, '1px solid #7f9db9');
					return false;
			}
			childrenAges += childrenAgesPerRoom + ",";
			
			var infantSeatSelectValue =document.getElementById( "infantSeatSelect_" + childCounter + "_" + roomCounter ).value;
			var childSeatFlag = (!isInfant(childrenAgesPerRoom) || isFlightMandatory == false) ? -1 : infantSeatSelectValue;
			childSeatFlags += childSeatFlag + ",";
		}
	}
	if( isPassengersExceededPerRoom) {
		showWarningMessage( 'Many hotel rooms accommodate up to four travelers.  If you do not receive your desired results, try searching again using two or more rooms', 'searchPopupDivContainer' );
	}

	var flightItineraryCheckboxField = document.getElementById( "flightItineraryCheckbox");
	var isFlightItinerary = false;
	if( flightItineraryCheckboxField != undefined ){
		isFlightItinerary = flightItineraryCheckboxField.checked; 
	}

	// Removing last comma from adults,children and childrenAges strings.
	adults = adults.substring( 0, adults.length - 1 );
	children = children.substring( 0, children.length - 1 );
	childrenAges = childrenAges.substring( 0, childrenAges.length - 1 );
	numberOfNightsInEachCity = numberOfNightsInEachCity.substring( 0, numberOfNightsInEachCity.length - 1 );

	disableElement( 'searchPopupDivContainer', true );

	//preparing query string to farwording variables to activity.
	queryString += '&packageId=' + packageId;
	queryString += '&departureDate=' + departureDate;
	queryString += '&arrivalDate=' + returnDate;
	queryString += '&numberOfNightsInEachCity=' + numberOfNightsInEachCity;
	queryString += '&adults=' + adults;
	queryString += '&children=' + children;
	queryString += '&childrenAges=' + childrenAges;
	queryString += '&childSeatFlags=' + childSeatFlags;
	queryString += '&hotelRooms=' + hotelRooms;
	queryString += '&includeFlightItinerary=' + isFlightMandatory;
	queryString += '&fromMenu=' + fromMenu;
	queryString += '&flightChecked=' + isFlightItinerary;
	
	asynchronousRequest = new AsynchronousRequest();
	asynchronousRequest.url = _webLoc + '/searchPackage.act';
	asynchronousRequest.queryString = queryString;
	asynchronousRequest.useAjax = true;
	asynchronousRequest.target = 'mainContent';
	asynchronousRequest.callbackFunctionName = 'callbackSearchPackage';

	var splashScreenRequest = new SplashScreenRequest();
	splashScreenRequest.splashScreenText = "Searching...";
	asynchronousRequest.splashScreenRequest = splashScreenRequest;
	asynchronousRequest.splashScreenDisplayFunctionName = "displaySearchingPopup";
	asynchronousRequest.splashScreenHideFunctionName = "hideSearchingPopup";
	
	//Makes the Ajax call with '/vp/browse/package/<packageId>' as the description to be passed into Google Analytics
	makeAjaxCallWithRequest( asynchronousRequest, '/vp/browse/package/' + packageId );
}

function callbackSearchPackage() {	
	if(!showMessage(this.errorMessage, this.errorCode, 'searchPopupDivContainer')) {
		disableElement( 'searchPopupDivContainer', false );
		hideBlock( 'searchPopupDivContainer' )	
		disableElement( 'dataContent', false );
	}
	return true;
}

function performSearchAgain( checkinDate, checkoutDate, productUid ) {
	var queryString = 'sp=6';
	queryString += '&newStartDate=' + checkinDate;
	queryString += '&newEndDate=' + checkoutDate;
	queryString += '&uid=' + productUid;

	var asynchronousRequest = new AsynchronousRequest();
	asynchronousRequest.url = _webLoc + '/searchPackage.act';
	asynchronousRequest.queryString = queryString;
	asynchronousRequest.useAjax = true;
	asynchronousRequest.target = 'mainContent';
	asynchronousRequest.callbackFunctionName = 'callbackPerformSearchAgain';

	var splashScreenRequest = new SplashScreenRequest();
	splashScreenRequest.splashScreenText = "Please Wait...";
	asynchronousRequest.splashScreenRequest = splashScreenRequest;
	asynchronousRequest.splashScreenDisplayFunctionName = "displaySearchingPopup";
	asynchronousRequest.splashScreenHideFunctionName = "hideSearchingPopup";

	disableElement( 'dataContent', true );
	makeAjaxCallWithRequest( asynchronousRequest, '' );
}

function callbackPerformSearchAgain( ) {
	disableElement( 'dataContent', false );
	if(showMessage( this.errorMessage, this.errorCode, 'dataContent' )) {		
		return false;
	}
}

var _packageId;
/*
loads a search popup div in case of flight required for a requested package.
issues a search otherwise.
*/
function loadSearchPopupOrSearchResults( packageId ) {
	var departureDate = document.getElementById( "departureDateWidget" ).value;
	var returnDate = document.getElementById( "returnDateWidget" ).value;
	var hotelRooms = document.getElementById( "numberOfRoomsWidget" ).value;
	var numberOfNights = document.getElementById( "numberOfNightsWidget").value;
	var departureCity = document.getElementById( "departureCityTextWidget" ).value;
	var departureCityCode = document.getElementById( "departureCityCodeWidget" ).value;
	//var hotelId = document.getElementById( "hotelIdWidget" ).value;
	//var hotelName = document.getElementById( "hotelNameWidget" ).value;
	var flightItineraryCheckboxWidget = document.getElementById( "flightItineraryCheckboxWidget").checked;
	var serviceClass =  document.getElementById( "serviceClassWidget");
	var adultsInRoom = 0;
	var childrenInRoom = 0;
	var childrenAges="";
	var childSeatFlags = "";
	_packageId = packageId;
	
	for( var roomCounter = 1; roomCounter <= hotelRooms; roomCounter++ ) {
		adultsInRoom = adultsInRoom + parseInt( document.getElementById( "adultsInRoomForWidget_" + roomCounter ).value ) +",";
	}
	for( var roomCounter = 1; roomCounter <= hotelRooms; roomCounter++ ) {
		childrenInRoom = childrenInRoom + parseInt( document.getElementById( "childrenInRoomForWidget_" + roomCounter ).value ) +",";
		var children = parseInt( document.getElementById( "childrenInRoomForWidget_" + roomCounter ).value );
		for ( var childCounter = 1; childCounter <= children; childCounter++ ){
			var childrenAgesPerRoom =document.getElementById( "childAgeForWidget_" + childCounter + "_" + roomCounter ).value;
			childrenAges += childrenAgesPerRoom + ",";
			
			var infantSeatSelectWidgetValue =document.getElementById( "infantSeatSelectWidget_" + childCounter + "_" + roomCounter ).value;
			var childSeatFlag = (!isInfant(childrenAgesPerRoom) || flightItineraryCheckboxWidget == false) ? -1 : infantSeatSelectWidgetValue;
			childSeatFlags += childSeatFlag + ",";
		}
	}

	var isPassengersExceededPerRoom = false;
	for( var roomCounter = 1; roomCounter <= hotelRooms; roomCounter++ ){
		var adultsPerRoom = document.getElementById( "adultsInRoomForWidget_" + roomCounter ).value;
		var childrensPerRoom = document.getElementById( "childrenInRoomForWidget_" + roomCounter ).value;

		if ( adultsPerRoom > 4 ){
			isPassengersExceededPerRoom = true;
		} else if( ( parseInt( adultsPerRoom ) + parseInt( childrensPerRoom ) ) > 5 ){
			isPassengersExceededPerRoom = true;
		}
	}
	if( isPassengersExceededPerRoom ){
		showWarningMessage( 'Many hotel rooms accommodate up to four travelers.  If you do not receive your desired results, try searching again using two or more rooms', 'dataContent' );
	}
	
	_packageId = packageId;
	var queryString = 'sp=2';
	queryString += '&departureDate=' + departureDate;	
	queryString += '&arrivalDate=' + returnDate;
	queryString += '&hotelRooms=' + hotelRooms;
	queryString += '&numberOfNightsInEachCity=' + numberOfNights;
	queryString += '&adults=' + adultsInRoom;
	queryString += '&children=' + childrenInRoom;
	queryString += '&childrenAges=' + childrenAges;
	queryString += '&childSeatFlags=' + childSeatFlags;
	queryString += '&packageId=' + packageId;
	queryString += '&fromMenu=false';
	queryString += '&fromWidget=true';
	queryString += '&flightChecked=' + flightItineraryCheckboxWidget;
	//queryString += '&hotelId=' + hotelId;
	//queryString += '&hotelName=' + hotelName;
	queryString += '&departureCityCode=' + departureCityCode;
	queryString += '&serviceClass=' + serviceClass;
	
	if ( flightItineraryCheckboxWidget) {
		if( trim( departureCity ) == '' ){
			departureCityCode = "";
		}
		
		if(  trim( departureCityCode ) == '' ) {
			showErrorMessage('Please select a departure city from the list', 'searchPopupDivContainer', 'departureCityText', '1px solid #7f9db9');
			return false;
		}

		queryString += '&departureCity=' + departureCity+'&includeFlightItinerary=true'; 		
	}

	disableElement( 'dataContent', true );
	asynchronousRequest = new AsynchronousRequest();
	asynchronousRequest.url = _webLoc + '/searchPackage.act';
	asynchronousRequest.queryString = queryString;
	asynchronousRequest.useAjax = true;
	asynchronousRequest.target = 'mainContent';
	asynchronousRequest.callbackFunctionName = 'callbackLoadSearchPopupOrSearch';

	var splashScreenRequest = new SplashScreenRequest();
	splashScreenRequest.splashScreenText = "Please Wait...";
	asynchronousRequest.splashScreenRequest = splashScreenRequest;
	asynchronousRequest.splashScreenDisplayFunctionName = "displaySearchingPopup";
	asynchronousRequest.splashScreenHideFunctionName = "hideSearchingPopup";

	//Submit Ajax call with '/vp/booking/searchPackage///package/<packageId>' as the description to be passed into Google Analytics
	//The three '/' are put on purpose as place holders to retain the general format
	makeAjaxCallWithRequest( asynchronousRequest, '/vp/booking/searchPackage///package/' + packageId);
}

function callbackLoadSearchPopupOrSearch(showPopup, fromWidget ) {
	disableElement( 'dataContent', false );
	if( showPopup == 'true' ) {
		if(!showMessage( this.errorMessage, this.errorCode, 'searchPopupDivContainer' )) {
			initiatePackageSearch( _packageId, fromWidget );
		}else {
			return false;
		}
	}else {
		if(showMessage( this.errorMessage, this.errorCode, 'dataContent' )) {
			return false;
		}
	}
	return true;	
}

// function to load room occupancy controls for search popup.
function loadRoomOccupancyControls() {
	var previousSelectedRooms = document.getElementById( "previousSelectedRooms" ).value;
	var selectedRooms = parseInt( document.getElementById( "numberOfRooms" ).value );
	var hotelRooms = ( selectedRooms -  previousSelectedRooms );
	if ( hotelRooms > 0 )  {
		for( var roomCounter = parseInt( previousSelectedRooms ) + 1; roomCounter <= selectedRooms ; roomCounter++ ) {
			var roomOccupancy = document.getElementById( "roomOccupancy_" + roomCounter );
			if( ( roomOccupancy == undefined ) && ( roomOccupancy == null ) ) {
				loadOccupancyControlsForRoom( roomCounter );
			}
		}
	} else {
		var roomOccupancyInformationTbody = document.getElementById("roomOccupancyInformationTbody");
			for( var roomCounter = previousSelectedRooms; roomCounter > selectedRooms ; roomCounter-- ) {
				var roomOccupancy = document.getElementById( "roomOccupancy_" + roomCounter );
				if( ( roomOccupancy != undefined ) && ( roomOccupancy != null ) ) {
					roomOccupancyInformationTbody.removeChild( roomOccupancy );
				}
			}
	}
	document.getElementById( "previousSelectedRooms" ).value = selectedRooms;
	return true;
}

// function to load room occupancy controls for room in search popup.
function loadOccupancyControlsForRoom( roomCounter ) {
	var roomOccupancyInformation = document.getElementById( "roomOccupancyInformation" );
	var roomOccupancyInformationTbody = document.getElementById("roomOccupancyInformationTbody");
	var roomOccupancy = document.getElementById( "roomOccupancy_" + roomCounter );
	if( ( roomOccupancy == undefined ) || ( roomOccupancy == null ) ) {
		roomOccupancy = document.createElement( "TR" );
		roomOccupancy.id = "roomOccupancy_" + roomCounter;
		roomOccupancy.name = "roomOccupancy_" + roomCounter;

		var roomOccupancyCell = document.createElement( "TD" );
		roomOccupancyCell.colSpan = 2;
		roomOccupancy.insertBefore(roomOccupancyCell, null);

		var roomOccupancyTable = document.createElement( "TABLE" );
		roomOccupancyTable.width="100%";
		roomOccupancyTable.className = "fs11";
		roomOccupancyCell.insertBefore(roomOccupancyTable, null);

		var roomOccupancyTableBody = document.createElement( "TBODY" );
		roomOccupancyTableBody.id = "roomOccupancyTableBody_" + roomCounter;
		roomOccupancyTable.insertBefore(roomOccupancyTableBody, null);

		var roomOccupancyRow1 = document.createElement( "TR" );
		roomOccupancyTableBody.insertBefore(roomOccupancyRow1, null);

		var roomOccupancyColumn1 = document.createElement( "TD" );
		roomOccupancyColumn1.className="tal b wp30";
		roomOccupancyColumn1.appendChild( document.createTextNode( "Room " + roomCounter ) );
		roomOccupancyRow1.insertBefore(roomOccupancyColumn1, null);

		var roomOccupancyColumn2 = document.createElement( "TD" );
		roomOccupancyColumn2.className="tac wp35";
		var adultsInRoom = document.createElement( "SELECT" );
		adultsInRoom.id = "adultsInRoom_" + roomCounter;
		adultsInRoom.name = "adultsInRoom_" + roomCounter;
		adultsInRoom.className = "w44 fs11 textbox";
		for( var adultsIndex = 0 ; adultsIndex < 9 ; adultsIndex++ ) {
			adultsInRoom[ adultsIndex ] = new Option( adultsIndex + 1, adultsIndex + 1 );
		}
		adultsInRoom[ 1 ].selected = true;
		roomOccupancyColumn2.align = "center";
		roomOccupancyColumn2.appendChild( adultsInRoom );
		roomOccupancyRow1.insertBefore(roomOccupancyColumn2, null);

		var roomOccupancyColumn3 = document.createElement( "TD" );
		roomOccupancyColumn3.className="tac wp35";
		var childrenInRoom = document.createElement( "SELECT" );
		childrenInRoom.id = "childrenInRoom_" + roomCounter;
		childrenInRoom.name = "childrenInRoom_" + roomCounter;
		childrenInRoom.onchange = function(){ loadChildrenAges( roomCounter ); }
		childrenInRoom.className = "w44 fs11 textbox";
		for( var childIndex = 0 ; childIndex < 6 ; childIndex++ ) {
			childrenInRoom[ childIndex ] = new Option( childIndex, childIndex );
		}
		childrenInRoom[ 0 ].selected = true;

		roomOccupancyColumn3.align = "center";
		roomOccupancyColumn3.appendChild( childrenInRoom );
		roomOccupancyRow1.insertBefore(roomOccupancyColumn3, null);

		var roomOccupancyDivider = document.createElement( "DIV" );
		roomOccupancyDivider.className = "divider";
		roomOccupancyCell.insertBefore(roomOccupancyDivider, null);

		var spacerImage = new Image();
		spacerImage.src = _webLoc + "/shared/images/core/spacer.gif";
		spacerImage.alt = "";
		roomOccupancyDivider.insertBefore(spacerImage, null);

		roomOccupancyInformationTbody.appendChild( roomOccupancy );
		roomOccupancyInformation.appendChild( roomOccupancyInformationTbody );
	} else {
		roomOccupancy.style.display = "block";
	}
}

// function to load children ages onchange of child dropdown.
function loadChildrenAges( roomCounter ) {
	var numberOfChildrenInRoom = document.getElementById( "childrenInRoom_" + roomCounter  ).value;
	var roomOccupancyTableBody = document.getElementById("roomOccupancyTableBody_" + roomCounter);
	if(roomOccupancyTableBody) {
		var roomOccupancyAgesHeaderTr = document.getElementById("roomOccupancyAgesHeaderTr_" + roomCounter);
		if(!roomOccupancyAgesHeaderTr) {
			roomOccupancyAgesHeaderTr = document.createElement("TR");
			roomOccupancyAgesHeaderTr.id = "roomOccupancyAgesHeaderTr_" + roomCounter;
			
			var tdElement = document.createElement( "TD" );
			tdElement.className="tac note";
			tdElement.colSpan = 3;
			tdElement.appendChild( document.createTextNode( "Age of Children (At time of travel)" ))
			roomOccupancyAgesHeaderTr.appendChild(tdElement);
			roomOccupancyTableBody.appendChild(roomOccupancyAgesHeaderTr);
			
			var roomOccupancyAgesBodyTr = document.createElement("TR");
			roomOccupancyAgesBodyTr.id = "roomOccupancyAgesBodyTr_" + roomCounter
			roomOccupancyTableBody.appendChild(roomOccupancyAgesBodyTr);
						
			var tdElement = document.createElement("TD");
			tdElement.colSpan = 3;
			roomOccupancyAgesBodyTr.appendChild(tdElement);
			
			var roomOccupancyAgesTable = document.createElement("TABLE");
			roomOccupancyAgesTable.className = "fs11";			
			roomOccupancyAgesTable.width="100%"
			roomOccupancyAgesTable.cellSpacing="0";
			roomOccupancyAgesTable.cellPadding="0";
			roomOccupancyAgesTable.border="0";
			tdElement.appendChild(roomOccupancyAgesTable);
			
			var roomOccupancyAgesTableBody = document.createElement("TBODY");
			roomOccupancyAgesTableBody.id ="roomOccupancyAgesTBody_" + roomCounter;
			roomOccupancyAgesTable.appendChild(roomOccupancyAgesTableBody);
		}
		
		var roomOccupancyAgesTableBody = document.getElementById("roomOccupancyAgesTBody_" + roomCounter);
		for(var childCounter = 1; childCounter <= numberOfChildrenInRoom; childCounter+=2) {
			var roomOccupancyTr = document.getElementById("roomOccupancyTr_" + childCounter +"_" + roomCounter);
			if(!roomOccupancyTr){	
				roomOccupancyTr = document.createElement("TR");
				roomOccupancyTr.id = "roomOccupancyTr_" + childCounter +"_" + roomCounter;
				roomOccupancyAgesTableBody.appendChild(roomOccupancyTr);			
			}								
			var isLastRow = (childCounter >= numberOfChildrenInRoom -1);
			
			var roomOccupancyTd = document.getElementById("roomOccupancyTd_" + childCounter +"_" + roomCounter);
			if(!roomOccupancyTd) {			
				roomOccupancyTd = createChildItem(childCounter, roomCounter, isLastRow, numberOfChildrenInRoom);				
				roomOccupancyTr.appendChild(roomOccupancyTd);
			}else {
				setChildItemClass(roomOccupancyTd, childCounter, isLastRow, numberOfChildrenInRoom);
			}	
			
			if(!isLastRow || numberOfChildrenInRoom %2 ==0) {
				var roomOccupancyTd = document.getElementById("roomOccupancyTd_" + (parseInt(childCounter) + 1) + "_" + roomCounter);
				if(!roomOccupancyTd) {		
					roomOccupancyTd = createChildItem(childCounter + 1, roomCounter, isLastRow, numberOfChildrenInRoom);		
					roomOccupancyTr.appendChild(roomOccupancyTd);
				}else {
					setChildItemClass(roomOccupancyTd, childCounter + 1, isLastRow, numberOfChildrenInRoom);
				}	 	
			}					
		}
		
		var roomOccupancyAgesHeaderTr = document.getElementById("roomOccupancyAgesHeaderTr_" + roomCounter);
		var roomOccupancyAgesBodyTr = document.getElementById("roomOccupancyAgesBodyTr_" + roomCounter);
				
		if(numberOfChildrenInRoom == 0) {
			roomOccupancyAgesHeaderTr.style.display = "none";
			roomOccupancyAgesBodyTr.style.display = "none";
		}else {
			roomOccupancyAgesHeaderTr.style.display = "";
			roomOccupancyAgesBodyTr.style.display = "";
		}
		
		for( var childCounter = 1; childCounter<= numberOfChildrenInRoom; childCounter++ ) {
			var roomOccupancyTd = document.getElementById("roomOccupancyTd_" + childCounter + "_" + roomCounter);
			if(roomOccupancyTd.style.display == "none") {
				var childAgeSelect= document.getElementById("childAge_" + childCounter + "_" + roomCounter);	
				var infantSeatSelect= document.getElementById("infantSeatSelect_" + childCounter + "_" + roomCounter);						
				roomOccupancyTd.style.display = "";
				infantSeatSelect.style.display = "none";
				childAgeSelect.selectedIndex = 0;
			}							
		}
		
		for(var childCounter = parseInt(numberOfChildrenInRoom) + 1; ;childCounter++) {
			var roomOccupancyTd = document.getElementById("roomOccupancyTd_" + childCounter +"_" + roomCounter);
			if(roomOccupancyTd) {
				roomOccupancyTd.style.display = "none";
			}else {
				break;
			}
		}
		
	}
}


function createChildItem(childCounter, roomCounter, isLastRow, numberOfChildrenInRoom) {	
	var roomOccupancyTd = document.createElement("TD");
	roomOccupancyTd.id = "roomOccupancyTd_" + childCounter +"_" + roomCounter;
	roomOccupancyTd.style.display = "none";
	setChildItemClass(roomOccupancyTd, childCounter, isLastRow, numberOfChildrenInRoom); 	
	
	var nobrElement = document.createElement("NOBR");
	roomOccupancyTd.appendChild(nobrElement);
	
	childAgeSelect = document.createElement("SELECT");
	childAgeSelect.id = "childAge_" + childCounter +"_" + roomCounter;
	childAgeSelect.name = "childAge_" + childCounter +"_" + roomCounter;
	childAgeSelect.className = "w44 mb05 mr03 fs11 textbox";
	childAgeSelect.onchange = new Function("onChildAgeChange(" + childCounter + "," + roomCounter + ")");
	childAgeSelect[ 0 ] = new Option( '-', -1);
	childAgeSelect[ 1 ] = new Option( '<1', 0 );
	for(var ageIndex =1; ageIndex <=18; ageIndex++) {
		childAgeSelect[ ageIndex + 1 ] = new Option( ageIndex, ageIndex );
	}
	nobrElement.appendChild(childAgeSelect);				
	nobrElement.appendChild(document.createTextNode( "\u00a0" ));
	
	var infantSeatSelectWidget = document.createElement( "SELECT" );
	infantSeatSelectWidget.id = "infantSeatSelect_" + childCounter + "_" + roomCounter;
	infantSeatSelectWidget.name = "infantSeatSelect_" + childCounter + "_" + roomCounter;
	infantSeatSelectWidget.className = "mb05 fs11 textbox";
	infantSeatSelectWidget[ 0 ] = new Option( 'Infant On Adult\'s Lap', 0);
	infantSeatSelectWidget[ 1 ] = new Option( 'Infant in Own Seat', 1)					
	
	nobrElement.appendChild( infantSeatSelectWidget );
	
	return roomOccupancyTd;
}

function setChildItemClass(roomOccupancyTd, childCounter, isLastRow, numberOfChildrenInRoom) {
	if(roomOccupancyTd) {
		if(childCounter%2 ==0) {
			if(isLastRow){		
				roomOccupancyTd.className = "pl05 pt05 wp49";
			} else {
				roomOccupancyTd.className = "pl05 pt05 wp49 bob02";
			}
		}else {
			if(numberOfChildrenInRoom == 1) {
				roomOccupancyTd.className = "pl05 pt05 wp49";
			}
			else if(isLastRow){	
				roomOccupancyTd.className = "pl05 pt05 wp49 bor01";
			} else {
				roomOccupancyTd.className = "pl05 pt05 wp49 bob02 bor01";
			}
		}	
	}
}

// function to load childeren ages onchange of child dropdown in widget integration.
function loadChildrenAgesForWidget( roomCounter  ) {
	var numberOfChildrenInRoom = document.getElementById( "childrenInRoomForWidget_" + roomCounter  ).value;
	var roomOccupancyTableBody = document.getElementById( "roomOccupancyTableBodyForWidget_" + roomCounter );
	if( roomOccupancyTableBody ) {
		var roomOccupancyAgesHeaderTr = document.getElementById( "roomOccupancyAgesHeaderForWidgetTr_" + roomCounter );
		if( !roomOccupancyAgesHeaderTr ) {
			var roomOccupancyAgesHeaderTr = document.createElement( "TR" );
			roomOccupancyAgesHeaderTr.id = "roomOccupancyAgesHeaderForWidgetTr_" + roomCounter;
			roomOccupancyTableBody.insertBefore( roomOccupancyAgesHeaderTr, null );
			
			var td0 = document.createElement( "TD" );
			td0.className="tac note";
			td0.colSpan = 3;
			td0.appendChild( document.createTextNode( "Age of Children (At time of travel)" ));
			roomOccupancyAgesHeaderTr.insertBefore( td0, null );			
		}
		
		if( numberOfChildrenInRoom == 0 ) {
			roomOccupancyAgesHeaderTr.style.display = "none";		
		} else {
			roomOccupancyAgesHeaderTr.style.display = "";
		}
		
		for( var childIndex = 1; childIndex<= numberOfChildrenInRoom; childIndex++ ) {
			var roomOccupancyTr = document.getElementById( "roomOccupancyForWidgetTr_" + childIndex  + "_" + roomCounter);
 			var isNewRow = !roomOccupancyTr || roomOccupancyTr.style.display == "none";
			if( !roomOccupancyTr ) {
				roomOccupancyTr = document.createElement( "TR" );
				roomOccupancyTr.id = "roomOccupancyForWidgetTr_" + childIndex + "_" + roomCounter;
				roomOccupancyTableBody.insertBefore( roomOccupancyTr, null );
				
				var roomOccupancyTd = document.createElement( "TD" );
				roomOccupancyTd.id = "childrenAgesForWidgetTd_"+ childIndex + "_" + roomCounter ;
				roomOccupancyTd.name = "childrenAgesForWidgetTd_"+ childIndex + "_" + roomCounter;				
				roomOccupancyTd.colSpan=3;
				roomOccupancyTr.insertBefore( roomOccupancyTd, null );
				var nobrElement = document.createElement( "NOBR" );
				roomOccupancyTd.insertBefore(nobrElement, null);
				
				var childAgeSelectWidget = document.createElement( "SELECT" );
				childAgeSelectWidget.id = "childAgeForWidget_" + childIndex + "_" + roomCounter;
				childAgeSelectWidget.name = "childAgeForWidget_" + childIndex + "_" + roomCounter;
				childAgeSelectWidget.className = "w44 fs11 textbox";
				childAgeSelectWidget.onchange = new Function("onChildAgeWidgetChange(" + childIndex + "," + roomCounter + ")");
				childAgeSelectWidget[ 0 ] = new Option( '-', -1);
				childAgeSelectWidget[ 1 ] = new Option( '<1', 0 );
				for( var ageIndex = 1 ; ageIndex <= 18 ; ageIndex++ ) {
					childAgeSelectWidget[ ageIndex + 1] = new Option( ageIndex, ageIndex );
				}
				var childAgeDivWidget = document.createElement( "DIV" );
				childAgeDivWidget.id = "childAgeForWidget_div_" + childIndex + "_" + roomCounter;
				childAgeDivWidget.name = "childAgeForWidget_div_" + childIndex + "_" + roomCounter;
				childAgeDivWidget.className = "mb05 fll";				
				childAgeDivWidget.appendChild( childAgeSelectWidget );
				nobrElement.appendChild( childAgeDivWidget );				
				
				nobrElement.appendChild( document.createTextNode( "\u00a0\u00a0\u00a0" ));
				
				var infantSeatSelectWidget = document.createElement( "SELECT" );
				infantSeatSelectWidget.id = "infantSeatSelectWidget_" + childIndex + "_" + roomCounter;
				infantSeatSelectWidget.name = "infantSeatSelectWidget_" + childIndex + "_" + roomCounter;
				infantSeatSelectWidget.className = "mb05 fs11 textbox";
				infantSeatSelectWidget[ 0 ] = new Option( 'Infant On Adult\'s Lap', 0);
				infantSeatSelectWidget[ 1 ] = new Option( 'Infant in Own Seat', 1)					
				nobrElement.appendChild( infantSeatSelectWidget );					
			}						
			
			if(isNewRow) {
				var childAgeSelect = document.getElementById("childAgeForWidget_" + childIndex + "_" + roomCounter);
				childAgeSelect.selectedIndex = 0;
				var infantSeatSelectWidget = document.getElementById("infantSeatSelectWidget_" + childIndex + "_" + roomCounter);
				infantSeatSelectWidget.style.display="none";
				infantSeatSelectWidget.selectedIndex = 0;
			}	

			var roomOccupancyTd = document.getElementById("childrenAgesForWidgetTd_"+ childIndex + "_" + roomCounter);		
			if(childIndex!= numberOfChildrenInRoom) {
				roomOccupancyTd.className="bob02 pl10 pt05 tal";
			} else {
				roomOccupancyTd.className="pl10 pt05 tal";
			}
			roomOccupancyTr.style.display = "";
		}
		
		for(var childRowIndex = parseInt(numberOfChildrenInRoom) + 2; childRowIndex < roomOccupancyTableBody.rows.length; childRowIndex++) {
			roomOccupancyTableBody.rows[childRowIndex].style.display = "none";
		}
	}
}

// function to load roomOccupancy for widget integaration.
function loadRoomOccupancyControlsForWidget() {
	var prevSelectedRooms = document.getElementById( "prevSelectedRooms" ).value;
	var selectedRooms = parseInt( document.getElementById( "numberOfRoomsWidget" ).value );
	var hotelRooms = ( selectedRooms -  prevSelectedRooms );
	if ( hotelRooms > 0 )  {
		for( var roomCounter = parseInt( prevSelectedRooms ) + 1; roomCounter <= selectedRooms ; roomCounter++ ) {
			var roomOccupancyForWidget = document.getElementById( "roomOccupancyForWidget_" + roomCounter );
			if( ( roomOccupancyForWidget == undefined ) && ( roomOccupancyForWidget == null ) ) {
				loadOccupancyControlsForRoomInWidget( roomCounter );
			}
		}
	} else {
		var roomOccupancyInformationTbodyWidget = document.getElementById("roomOccupancyInformationTbodyWidget");
			for( var roomCounter = prevSelectedRooms; roomCounter > selectedRooms ; roomCounter-- ) {
				var roomOccupancyForWidget = document.getElementById( "roomOccupancyForWidget_" + roomCounter );
				if( ( roomOccupancyForWidget != undefined ) && ( roomOccupancyForWidget != null ) ) {
					roomOccupancyInformationTbodyWidget.removeChild( roomOccupancyForWidget );
				}
			}
	}
	document.getElementById( "prevSelectedRooms" ).value = selectedRooms;
	return true;
}

// function to load roomOccupancyControls for room in widget Integaration
function loadOccupancyControlsForRoomInWidget( roomCounter ) {
	var roomOccupancyInformationWidget = document.getElementById( "roomOccupancyInformationWidget" );
	var roomOccupancyInformationTbodyWidget = document.getElementById("roomOccupancyInformationTbodyWidget");
	var roomOccupancyForWidget = document.getElementById( "roomOccupancyForWidget_" + roomCounter );
	if( ( roomOccupancyForWidget == undefined ) || ( roomOccupancyForWidget == null ) ) {
		roomOccupancyForWidget = document.createElement( "TR" );
		roomOccupancyForWidget.id = "roomOccupancyForWidget_" + roomCounter;
		roomOccupancyForWidget.name = "roomOccupancyForWidget_" + roomCounter;

		var roomOccupancyCell = document.createElement( "TD" );
		roomOccupancyCell.colSpan = 2;
		roomOccupancyForWidget.appendChild(roomOccupancyCell );

		var roomOccupancyTable = document.createElement( "TABLE" );

		roomOccupancyTable.className = "fs11 wp100";
		roomOccupancyTable.cellPadding = '1';
		roomOccupancyTable.cellSpacing = '0';
		roomOccupancyCell.appendChild( roomOccupancyTable );

		var roomOccupancyTableBody = document.createElement( "TBODY" );
		roomOccupancyTableBody.id = "roomOccupancyTableBodyForWidget_" + roomCounter;
		roomOccupancyTable.appendChild( roomOccupancyTableBody );

		var roomOccupancyRow1 = document.createElement( "TR" );
		roomOccupancyTableBody.appendChild( roomOccupancyRow1 );

		var roomOccupancyColumn1 = document.createElement( "TD" );
		roomOccupancyColumn1.className="w135 tar b";
		
		var nobr = document.createElement( "NOBR" );
		roomOccupancyColumn1.appendChild( nobr );
		
		nobr.appendChild( document.createTextNode( "Room " + roomCounter ) );
		roomOccupancyRow1.appendChild( roomOccupancyColumn1 );

		var roomOccupancyColumn2 = document.createElement( "TD" );
		roomOccupancyColumn2.className="tac w135";
		var adultsInRoom = document.createElement( "SELECT" );
		adultsInRoom.id = "adultsInRoomForWidget_" + roomCounter;
		adultsInRoom.name = "adultsInRoomForWidget_" + roomCounter;
		adultsInRoom.className = "w44 mb02 fs11 textbox";
		for( var adultsIndex = 0 ; adultsIndex < 9 ; adultsIndex++ ) {
			adultsInRoom[ adultsIndex ] = new Option( adultsIndex + 1, adultsIndex + 1 );
		}
		adultsInRoom[ 1 ].selected = true;
		roomOccupancyColumn2.align = "center";
		roomOccupancyColumn2.appendChild( adultsInRoom );
		roomOccupancyRow1.appendChild( roomOccupancyColumn2 );

		var roomOccupancyColumn3 = document.createElement( "TD" );
		roomOccupancyColumn3.className="tac w135";
		var childrenInRoom = document.createElement( "SELECT" );
		childrenInRoom.id = "childrenInRoomForWidget_" + roomCounter;
		childrenInRoom.name = "childrenInRoomForWidget_" + roomCounter;
		childrenInRoom.onchange = function(){ loadChildrenAgesForWidget( roomCounter ); }

		childrenInRoom.className = "w44 mb02 fs11 textbox";
		for( var childIndex = 0 ; childIndex < 6 ; childIndex++ ) {
			childrenInRoom[ childIndex ] = new Option( childIndex, childIndex );
		}
		childrenInRoom[ 0 ].selected = true;

		roomOccupancyColumn3.align = "center";
		roomOccupancyColumn3.appendChild( childrenInRoom );
		roomOccupancyRow1.appendChild( roomOccupancyColumn3 );

		var roomOccupancyDivider = document.createElement( "DIV" );
		roomOccupancyDivider.className = "divider";
		roomOccupancyCell.insertBefore(roomOccupancyDivider, null);

		var spacerImage = new Image();
		spacerImage.src = _webLoc + "/shared/images/core/spacer.gif";
		spacerImage.alt = "";
		roomOccupancyDivider.insertBefore(spacerImage, null);

		roomOccupancyInformationTbodyWidget.appendChild( roomOccupancyForWidget );
		roomOccupancyInformationWidget.appendChild( roomOccupancyInformationTbodyWidget );
	} else {
		roomOccupancyForWidget.style.display = "block";
	}
	return true;
}



function getOffsetPosition( srcElement ) {
	var offsetLeft = 0;
	var offsetTop = 0;
	do {
		offsetLeft += srcElement.offsetLeft;
		offsetTop += srcElement.offsetTop;
		srcElement = srcElement.offsetParent;
	} while( srcElement.offsetParent );
	return new Array( offsetLeft, offsetTop );
}

function addDaysToReturnDate( numberOfCities ) {
	//clearErrorElements();
	var noOfDays = 0;
	var totalDays = 0;
	var isNightsFieldEmpty = false;
	var departureDate = document.getElementById( "departureDate" ).value;
	for( var cityIndex = 1; cityIndex <= numberOfCities; cityIndex++ ) {
		noOfDays = document.getElementById( "numberOfNights" + cityIndex ).value;
		if( noOfDays == "" ) {
			isNightsFieldEmpty = true;
		} else {
			if ( ( departureDate == "" || departureDate == "mm/dd/yyyy" ) ) {
				document.getElementById( "numberOfNights1" )[0].selected = true;
				showErrorMessage('Please select a departure date.', 'searchPopupDivContainer', 'departureDate', '1px solid #7f9db9');
				return false;
			}
			totalDays = totalDays + parseInt( noOfDays );
		}
	}
	_totalNumberOfNights = totalDays + _numberOfOvernightRails;
	document.getElementById( "returnDate" ).value = addDaysToDate( departureDate, totalDays + _numberOfOvernightRails );
}

/*Adding number of days to the supplied date*/
function addDaysToDate( dateField, numberField ){
	var beforeDate = new Date( dateField );
	beforeDate.setDate( beforeDate.getDate() + parseInt( numberField ) ) ;
	var beforeDateMonth = beforeDate.getMonth() + 1;
	var beforeDateDay = beforeDate.getDate();
	if ( beforeDateMonth < 10) { beforeDateMonth = "0" + beforeDateMonth; }
	if ( beforeDateDay < 10) { beforeDateDay = "0" + beforeDateDay; }
	var actulBeforeDate = beforeDateMonth + "/" + beforeDateDay + "/" + beforeDate.getFullYear();
	return actulBeforeDate;
}

function updateReturnDate( numberOfCities ) {
	// quick fix for firefox, since it doesn't fire onblur event
	var departureDateField = document.getElementById( "departureDate" );
	departureDateField.onblur = function() {updateDates( numberOfCities );};
	return true;
}

function updateDates( numberOfCities ) {
	clearErrorElements();
	var departureDate = document.getElementById( "departureDate" ).value;
	var totalDays = 0;
	var numberOfDays = 0;
	if( ( departureDate != '' ) && ( departureDate != "mm/dd/yyyy" ) && isDate( 'departureDate', 'searchPopupDivContainer' ) ) {
		for( var cityIndex = 1; cityIndex <= numberOfCities; cityIndex++ ) {
			var numberOfNights = document.getElementById( "numberOfNights" + cityIndex );
			numberOfDays = parseInt( numberOfNights.options[numberOfNights.selectedIndex].text );
			if( !( isNaN( numberOfDays ) ) ) {
				totalDays = parseInt( totalDays ) + numberOfDays;
			}
		}
		_totalNumberOfNights = totalDays + _numberOfOvernightRails;
		document.getElementById( "returnDate" ).value = addDaysToDate( departureDate, totalDays + _numberOfOvernightRails );
	} else {
		return false;
	}
}

function loadFlightItineraryInformation(){
	var flightItineraryFiled = document.getElementById( "flightItineraryCheckbox" )
	if( flightItineraryFiled != undefined ){
		var isFlightItinerary = flightItineraryFiled.checked;
		if( !isFlightItinerary ){
			document.getElementById( "flightItineraryBlockRow1" ).style.display = "none";
			document.getElementById( "flightItineraryBlockRow2" ).style.display = "none";
			document.getElementById( "departureCityText" ).value = "";
		}else {
			document.getElementById( "flightItineraryBlockRow1" ).style.display = "";
			document.getElementById( "flightItineraryBlockRow2" ).style.display = "";
			
			if (_serviceClass != undefined){
				var serviceClassList = document.getElementById("serviceClass");
				for (var i=0; i<serviceClassList.options.length; i++){
					if 	(serviceClassList.options[i].value == _serviceClass){
						serviceClassList.options[i].selected = true;
					}	
				}
			}			
		}
	}
}
function loadFlightItineraryInformationForWidget(){
	var isFlightItineraryField = document.getElementById( "flightItineraryCheckboxWidget" );
	if( isFlightItineraryField != undefined ){
		var isFlightItinerary = isFlightItineraryField.checked;
		if( !isFlightItinerary ){
			document.getElementById( "flightItineraryBlockRow1Widget" ).style.display = "none";
			document.getElementById( "flightItineraryBlockRow2Widget" ).style.display = "none";
			document.getElementById( "departureCityTextWidget" ).value = "";
		}else {
			document.getElementById( "flightItineraryBlockRow1Widget" ).style.display = "";
			document.getElementById( "flightItineraryBlockRow2Widget" ).style.display = "";
		}
	}
}


function displayInfantSeatSelects(show){
	var numberOfRoomsSelect = document.getElementById("numberOfRooms");
	if(numberOfRoomsSelect){
		numberOfRooms = numberOfRoomsSelect.value;
		for(var roomIndex = 1; roomIndex<=numberOfRooms; roomIndex++) {
			var childrenInRoomSelect = document.getElementById("childrenInRoom_" + roomIndex);
			if(childrenInRoomSelect) {
				childrenInRoom = childrenInRoomSelect.value;
				for(var childIndex = 1; childIndex<=childrenInRoom; childIndex++) {					
					var infantSeatSelect= document.getElementById("infantSeatSelect_"+ childIndex +"_" + roomIndex);
					if(infantSeatSelect) {
						if(show){
							var childAgeSelect = document.getElementById("childAge_"+ childIndex +"_" + roomIndex);
							if(childAgeSelect) {
								var childAge = parseInt(childAgeSelect.value);
								if(isInfant(childAge)) {
									infantSeatSelect.selectedIndex=0;
									infantSeatSelect.style.display="";									
								}	
							}	
						}else {
							infantSeatSelect.style.display="none";
						}
					}
				}	
			}	
		}
	}	
}

function displayInfantSeatSelectsForWidget(show){
	var numberOfRoomsWidget = document.getElementById("numberOfRoomsWidget");
	if(numberOfRoomsWidget){
		numberOfRooms = numberOfRoomsWidget.value;
		for(var roomIndex = 1; roomIndex<=numberOfRooms; roomIndex++) {
			var childrenInRoomForWidget = document.getElementById("childrenInRoomForWidget_" + roomIndex);
			if(childrenInRoomForWidget) {
				childrenInRoom = childrenInRoomForWidget.value;
				for(var childIndex = 1; childIndex<=childrenInRoom; childIndex++) {					
					var infantSeatSelectWidget= document.getElementById("infantSeatSelectWidget_"+ childIndex +"_" + roomIndex);
					if(infantSeatSelectWidget) {
						if(show){
							var childAgeForWidget = document.getElementById("childAgeForWidget_"+ childIndex +"_" + roomIndex);
							if(childAgeForWidget) {
								var childAge = parseInt(childAgeForWidget.value);
								if(isInfant(childAge)) {
									infantSeatSelectWidget.selectedIndex=0;
									infantSeatSelectWidget.style.display="";									
								}	
							}	
						}else {
							infantSeatSelectWidget.style.display="none";
						}
					}
				}	
			}	
		}
	}	
}

function loadCitiesOfSelectedDestination( destination ) {
    _selectedDestination = destination;    
    if ( destination!="" && isDestinationBookable( destination ) ) {
    	// check whether destination is Fiji, Cook Islands or Tahiti, in which case dont need to load regions.
		if( !isRegionRequired( destination ) ) {
			// dont load regions.
			// hide region dropdown box.
			_selectedDestination = "";
			displayWidgetFieldsForSelectedDestination();
			return false;
		}
		var queryString = 'lc=3';
		queryString += '&destination=' + destination;
		makeAjaxCall( 'leftContent.act', queryString, null, null, 'callbackLoadCitiesOfSelectedDestination', '' );
	} else {	   
	   displayWidgetFieldsForSelectedDestination();
	} 
}

function isDestinationBookable( destination ) {
    if( destination == "escortedVacations"      ||
        destination == "themeParks"             || 
        destination == "lasVegasAndDesert"      ||
        destination == "houseboatVacations") {
          return false;           
    }    
    return true;
}

/*
 *Check weather region related processing required.
 **/
function isRegionRequired( destination ) {
	destination = destination.toUpperCase();
	for( var index = 0; index < BOOKABLE_DESTINATION.length; index++ ) {
		if( BOOKABLE_DESTINATION[index] == destination ) {
			return true;
		}
	}
	return false;
} 

function loadLandingPage( destination ) {    
    if( destination == "australia" ) {
       loadDestination(destination);    
    }
    if( destination == "cookIslands" ) {
       loadDestination(destination);    
    }else if ( destination == "escortedVacations" ) {
       loadAncillary(destination);    
    }else if( destination == "fiji" ) {
       loadDestination(destination);    
    }else if( destination == "lasVegasAndDesert" ) {
       loadAncillary(destination);        
    }else if( destination == "newZealand" ) {
       loadDestination(destination); 
    }else if( destination == "tahitianIslands" ) {
       loadDestination(destination);    
    }else if( destination == "themeParks" ) {
       loadAncillaryHome();    
    }else if( destination == "houseboatVacations" ) {
       loadAncillary(destination);    
    }
}

function callbackLoadCitiesOfSelectedDestination(citiesList ) {
	if( !showMessage( this.errorMessage, this.errorCode, 'dataContent' ) ) {
		if( document.getElementById( "destination" )[0].selected ){
			hideRegionAndHotelColumns();
		}else {
			document.getElementById( "cityTd" ).style.display = "block";
			document.getElementById( "cityTd" ).innerHTML = "Region <span class='sup'>*</span><br /><div id='regionDiv' class='mt03'><label><select name = 'region' id = 'region' class='w205 textbox fs11' onChange = 'clearHotelIdDiv();'>" + citiesList + "</select></label></div>";
		}
	}
	displayWidgetFieldsForSelectedDestination();
	return true;
}

function displayWidgetFieldsForSelectedDestination() {
    if( !_selectedDestination || _selectedDestination == "" ) {
        document.getElementById( "cityTd").style.display = "none"; 
        document.getElementById( "hotelNameTd").style.display = "none"; 
        document.getElementById( "searchFieldsWidgetDiv" ).style.display = "";
        document.getElementById( "otherDestinationsDiv" ).style.display = "none";
    } else if( isDestinationBookable( _selectedDestination ) ) {
        document.getElementById( "cityTd").style.display = "";
        if( document.getElementById( "region").value != "" ) {
            //document.getElementById( "hotelNameTd").style.display = "";
            document.getElementById( "hotelNameTd").style.display = "none";
        } else {
            document.getElementById( "hotelNameTd").style.display = "none";
        } 
        document.getElementById( "searchFieldsWidgetDiv" ).style.display = "";
        document.getElementById( "otherDestinationsDiv" ).style.display = "none";
    } else {
        document.getElementById( "destination" ).value = _selectedDestination;
        document.getElementById( "cityTd").style.display = "none"; 
        document.getElementById( "hotelNameTd").style.display = "none"; 
        document.getElementById( "searchFieldsWidgetDiv" ).style.display = "none";
        document.getElementById( "otherDestinationsDivContent" ).innerHTML = getTextForNonBookableDestinations( _selectedDestination );
        document.getElementById( "otherDestinationsDiv" ).style.display = "";
    }
    //_selectedDestination = "";
}

function getTextForNonBookableDestinations(destination) {
    if(destination == "escortedVacations") {
        return "Want to see the world but not sure how to start? With an escorted tour, all you have to do is sit back, relax and enjoy the adventure. <br /><br />To book, call Costco Travel toll free at <b>" + bookingPhoneNumber + "</b>.";
    }else if(destination == "themeParks") {
        return "Everyone loves a theme park! These are classic, all-American vacations at their very best. <br /><br />Book Disneyland&#174; Resort vacations online. <br /><br />To book an Orlando theme park package, call Costco Travel toll free at <b>" + bookingPhoneNumber + "</b>. ";
    }else if(destination =="houseboatVacations") {
        return "Enjoy hot summer days and starry summer nights aboard a fully equipped houseboat. <br /><br />To book, call Costco Travel toll free at <b>" + bookingPhoneNumber + "</b>."
    }else if(destination =="lasVegasAndDesert"){
        return "From the mega-watt glitter of the Las Vegas Strip to the world-class golf courses and spas of Arizona and California, a desert vacation sizzles with sun, fun, glamour and action.<br /><br /> <b>Book online</b>."
    }      
}

function searchPackagesForWidget( includeChildrenAgesForWidgetOrPopup ) {    
	clearErrorElements();
	var destination = document.getElementById( "destination" ).value;	
	if ( destination == "" ) {
		var msg ="Please select a destination.";
		showErrorMessage( msg, 'dataContent', 'destinationSelectionDiv', '#7f9db9');
		return false;
	}
	var isRegionValidationRequired = isRegionRequired( destination );
	var region = document.getElementById( "region" ).value; 
	if( isRegionValidationRequired ) {
		if ( region == "" ) {
			var msg ="Please select a region.";
			showErrorMessage( msg, 'dataContent', 'regionDiv', '#7f9db9');
			return false;
		}
	}
	
	_selectedDestination = destination;
    if( isDestinationBookable( destination ) ) {
    	var departureDate = document.getElementById( "departureDateWidget" ).value;
    	var returnDate = document.getElementById( "returnDateWidget" ).value;
    	if( ( ( departureDate != "" ) && ( departureDate != "mm/dd/yyyy" ) ) && ( ( returnDate != "" ) && ( returnDate != "mm/dd/yyyy" ) ) ) {
    		var fromDate = new Date( departureDate );
    		var toDate = new Date( returnDate );
    		if ( fromDate >= toDate ) {
    			var msg = "Please select a return date which is greater than departure date.";
    			showErrorMessage( msg ,'dataContent', 'departureDateWidget', '1px solid #7f9db9' );
    			return false;
    		}
    	}
    	var departureCity = document.getElementById( "departureCityTextWidget" ).value;
    	var departureCityCode = document.getElementById( "departureCityCodeWidget" ).value;
    	
    	var flightItineraryCheckboxWidget = document.getElementById( "flightItineraryCheckboxWidget" ).checked;
    	if ( flightItineraryCheckboxWidget ) {
    		if( trim( departureCity ) == '' ){
    			departureCityCode = "";
    		}
    		if(  trim( departureCityCode ) == '' ) {
    			var msg ="Please select a flight departure city.";
    			showErrorMessage( msg, 'dataContent', 'departureCityTextWidget', '1px solid #7f9db9');
    			return false;
    		}
    	}
    
    	var destination = document.getElementById( "destination" ).value;
    	
    	var hotelName = document.getElementById( "hotelNameWidget" ).value;
    	var hotelId = document.getElementById( "hotelIdWidget" ).value;
    	var hotelRooms = document.getElementById( "numberOfRoomsWidget" ).value;
    	var numberOfNights = document.getElementById( "numberOfNightsWidget").value;
    	var serviceClass = document.getElementById("serviceClassWidget").value;
    	
    	var adultsInRoom = 0;
    	var childrenInRoom = 0;
    	var adults = 0;
    	var children = 0;
    	var childrenAges="";
    	var childSeatFlags = "";
    	
    	for( var roomCounter = 1; roomCounter <= hotelRooms; roomCounter++ ) {
    		numAdults = parseInt( document.getElementById( "adultsInRoomForWidget_" + roomCounter ).value );
    		adultsInRoom = adultsInRoom + numAdults;
    		adults = adults + parseInt( document.getElementById( "adultsInRoomForWidget_" + roomCounter ).value ) +",";
    	}
    
    	for( var roomCounter = 1; roomCounter <= hotelRooms; roomCounter++ ) {
    		var numChildren = parseInt( document.getElementById( "childrenInRoomForWidget_" + roomCounter ).value );
    		if ( includeChildrenAgesForWidgetOrPopup ) {			
    			children = children + parseInt( document.getElementById( "childrenInRoomForWidget_" + roomCounter ).value ) +",";
    
    			for ( var childCounter = 1; childCounter <= numChildren ; childCounter++ ){
    				var childrenAgesPerRoom =document.getElementById( "childAgeForWidget_" + childCounter + "_" + roomCounter ).value;
    				var infantSeatSelectWidgetValue =document.getElementById( "infantSeatSelectWidget_" + childCounter + "_" + roomCounter ).value;
    				if(childrenAgesPerRoom < 0) {
    					var msg ="Please select the age for child " + childCounter + " in room " + roomCounter;
    					showErrorMessage( msg, 'dataContent', "childAgeForWidget_div_" + childCounter + "_" + roomCounter, 'solid #7f9db9' );
    					return false;
    				}
    				childrenAges += childrenAgesPerRoom + ",";				
    				var childSeatFlag = (!isInfant(childrenAgesPerRoom) || flightItineraryCheckboxWidget == false) ? -1 : infantSeatSelectWidgetValue;
    				childSeatFlags += childSeatFlag + ",";				
    			}
    
    		}
    		childrenInRoom = childrenInRoom + numChildren;
    	}
    
    	var numberOfPassengers = adultsInRoom + childrenInRoom ;
    	var queryString = 'lc=4&lbc=1';
    	if( isRegionValidationRequired ) {
    		 queryString +="&rc=16";
    		 queryString += '&cityCode=' + region;
    	} else {
    		queryString +="&rc=24";
    	}

    	queryString += '&destination=' + destination;
    	queryString += '&departureCity=' + departureCity;
    	queryString += '&departureCityCode=' + departureCityCode;
    	queryString += '&flightChecked=' + flightItineraryCheckboxWidget;
    	if( departureDate == "" || departureDate == "mm/dd/yyyy" ) {
    		showErrorMessage('Please select a departure date.', 'dataContent', 'departureDateWidget', '1px solid #7f9db9');
    		return false;
    	} else if( isDate( 'departureDateWidget', 'dataContent' ) == false ) {
    		document.getElementById( 'departureDateWidget' ).value = "mm/dd/yyyy";
    		document.getElementById( 'departureDateWidget' ).select();
    		return false;
    	}
    	if( returnDate == "" || returnDate == "mm/dd/yyyy" ) {
    		showErrorMessage('Please select a return date.', 'dataContent', 'returnDateWidget', '1px solid #7f9db9');
    		return false;
    	} else if( isDate( 'returnDateWidget', 'dataContent' ) == false ) {
    		document.getElementById( 'returnDateWidget' ).value = "mm/dd/yyyy";
    		document.getElementById( 'returnDateWidget' ).select();
    		return false;
    	}
    	
    	if( numberOfNights == '' ) {
    		var fromDate = new Date( departureDate );
    		var toDate = new Date( returnDate );
    		numberOfNights = computeDifferenceBetweenDates( fromDate, toDate );
    	}
    	if( hotelName == '' ){
    		hotelId = "";
    		document.getElementById( "hotelIdWidget" ).value = "";
    	}else {
    		if( hotelId == ''){
    			showErrorMessage('Please select a hotel name.', 'dataContent', 'hotelNameWidget', '1px solid #7f9db9');
    			return false;
    		}
    	}
    	hotelName = hotelName.replace( /&/g, '>>' );
    	queryString += '&arrivalDate=' + returnDate;
    	queryString += '&departureDate=' + departureDate;
    	queryString += '&numberOfNights=' + numberOfNights;
    	queryString += '&numberOfPassengers=' + numberOfPassengers;
    	queryString += '&hotelRooms=' + hotelRooms;
    	queryString += '&adults=' + adults;
    	queryString += '&children=' + children;
    	queryString += '&childrenAges=' + childrenAges;
    	queryString += '&childSeatFlags=' + childSeatFlags;	
    	queryString += '&fromWidget=true';
    	queryString += '&fromMenu=false';
    	queryString += '&hotelId=' + hotelId;
    	queryString += '&hotelName=' + hotelName;
    	queryString += '&serviceClass=' + serviceClass;
    	//Analytics Tracking text '/vp/booking/searchWidget/<destinationCode>' has to be added only when clicking on the search button from the widget
    	//If we're coming to the package search results page by clicking on back button or other
    	//navigation, we will not add this tracking text
    	var trackingText = '/vp/booking/searchWidget/' + destination;
    	if( region && region != '' ) {
    		trackingText += '/' + region;
    	}
   		searchAllPackagesForDestinationAndRegion( queryString, true, trackingText );	
    } else {
        loadLandingPage( destination );    
    }	
}

function isInfant(childAge) {
    return parseInt(childAge) >=0 && parseInt(childAge) <2;    
}

function searchAllPackagesForDestinationAndRegion(queryString, showSplashScreen, trackingText) {
	if(showSplashScreen == null || showSplashScreen == undefined) {
		showSplashScreen = false;
	}
	
	disableElement( 'dataContent', true );
	asynchronousRequest = new AsynchronousRequest();
	asynchronousRequest.url = _webLoc + '/mainContent.act';
	asynchronousRequest.queryString = queryString;
	asynchronousRequest.useAjax = true;
	asynchronousRequest.target = 'mainContent';
	asynchronousRequest.callbackFunctionName = 'callbackSearchPackagesForWidget';

	if(showSplashScreen) {
		var splashScreenRequest = new SplashScreenRequest();
		splashScreenRequest.splashScreenText = "Please Wait...";
		asynchronousRequest.splashScreenRequest = splashScreenRequest;
		asynchronousRequest.splashScreenDisplayFunctionName = "displaySearchingPopup";
		asynchronousRequest.splashScreenHideFunctionName = "hideSearchingPopup";
	}
	
	makeAjaxCallWithRequest( asynchronousRequest, trackingText );

	//Add the pseudo code '1001' to browser history
	var historyData = new Object();
	historyData.queryString = queryString;
	historyData.showSplashScreen = showSplashScreen;
	
	addHistoryWithData(HISTORY_SEARCH_RESULT_ALL_PACKAGES, historyData);
	setSupportPhoneNumber(bookingPhoneNumber);
}

function callbackSearchPackagesForWidget( message, errorCode ) {
	if( message != '' ) {
		disableElement( 'dataContent', false );
		showMessage( message, errorCode, 'dataContent' );	
	} else {
		if( !isRegionRequired( _selectedDestination ) ) {
			document.getElementById( "cityTab1" ).innerHTML = "1 Region";
			document.getElementById( "cityTab2" ).innerHTML = "2 Regions";
			document.getElementById( "cityTab3" ).innerHTML = "3 or more Regions";
		}
	}
	if( !( isRegionRequired( _selectedDestination ) ) ) {
		_selectedDestination = "";
		displayWidgetFieldsForSelectedDestination();
	}
	return true;
}

function reLoadPackageResults( ) {
	var queryString = 'lc=4&lbc=1';
	queryString +="&rc=23";
	
	disableElement( 'dataContent', true );
	var asynchronousRequest = new AsynchronousRequest();
	asynchronousRequest.url = _webLoc + '/mainContent.act';
	asynchronousRequest.queryString = queryString;
	asynchronousRequest.useAjax = true;
	asynchronousRequest.target = 'mainContent';
	asynchronousRequest.callbackFunctionName = 'callbackReLoadPackageResults';
	
	var splashScreenRequest = new SplashScreenRequest();
	splashScreenRequest.splashScreenText = "Please Wait...";
	asynchronousRequest.splashScreenRequest = splashScreenRequest;
	asynchronousRequest.splashScreenDisplayFunctionName = "displaySearchingPopup";
	asynchronousRequest.splashScreenHideFunctionName = "hideSearchingPopup";
		
	makeAjaxCallWithRequest( asynchronousRequest, "" );
}

function callbackReLoadPackageResults( message, errorCode ) {
	if( message != '' ) {
		disableElement( 'dataContent', false );
		showMessage( message, errorCode, 'dataContent' );	
	}
	return true
}

function showHiddenSearchPopup() {
	var searchPopupDivContainer = document.getElementById('searchPopupDivContainer');
	if( searchPopupDivContainer != null && searchPopupDivContainer != undefined ){
		searchPopupDivContainer.style.width = "703";
		searchPopupDivContainer.style.height = "450";
		searchPopupDivContainer.style.zIndex = "200";

		showBlock('searchPopupDivContainer');
		positionBlockCentrally('searchPopupDivContainer');		
		disableElement( 'dataContent', true );
	}
}

// function to add number of days to return date
function addNumberOfDaysToReturnDate() {
	clearErrorElements();
	var noOfDays = 0;
	var totalDays = 0;
	var isNightsFieldEmpty = false;
	var departureDate = document.getElementById( "departureDateWidget" ).value;
	noOfDays = document.getElementById( "numberOfNightsWidget").value;
		if( noOfDays == "" ) {
			isNightsFieldEmpty = true;
		} else {
			if ( ( departureDate == "" || departureDate == "mm/dd/yyyy" ) ) {
				document.getElementById( "numberOfNightsWidget" )[0].selected = true;
				showErrorMessage('Please select departure date.', 'dataContent', 'departureDateWidget', '1px solid #7f9db9');
				return false;
			}
			totalDays = totalDays + parseInt( noOfDays );
		}
	if( !isNightsFieldEmpty ) {
		document.getElementById( "returnDateWidget" ).value = addDaysToDate( departureDate, totalDays );
		return true;
	} else {
		showErrorMessage('Please select the number of nights.', 'dataContent' );
		return false;
	}
	return false;
}

// function to call onchange of return date.
function returnDateOnChangeForWidget() {
	var departureDate = trim( document.getElementById( "departureDateWidget" ).value );
	var returnDate = trim( document.getElementById( "returnDateWidget" ).value );
	if( ( ( departureDate != "" ) && ( departureDate != "mm/dd/yyyy" ) ) && ( ( returnDate != "" ) && ( returnDate != "mm/dd/yyyy" )  ) ) {
		populateNumberOfNightsDropDown( departureDate, returnDate );
	}
}

// function to call onchange of departure date.
function departureDateOnChangeForWidget() {
	var departureDate = trim( document.getElementById( "departureDateWidget" ).value );
	var returnDate = trim( document.getElementById( "returnDateWidget" ).value );
	if( ( returnDate != "" ) && ( returnDate != "mm/dd/yyyy" ) ) {
		populateNumberOfNightsDropDown( departureDate, returnDate );
	}
}

function departureDateOnChange() {
	var departureDate = trim( document.getElementById( "departureDate" ).value );
	var returnDate = trim( document.getElementById( "returnDate" ).value );
	if( ( returnDate != "" ) && ( returnDate != "mm/dd/yyyy" ) ) {
		populateNumberOfNightsDropDown( departureDate, returnDate );
	}
}

function populateNumberOfNightsDropDown( departureDate, returnDate ) {
	var fromDate = new Date( departureDate );
	var toDate = new Date( returnDate );
	if( fromDate < toDate ) {
		var nights = computeDifferenceBetweenDates( fromDate, toDate );
		if( nights <= 30 ) {
			document.getElementById( "numberOfNightsWidget" ).value = nights;
		} else {
			document.getElementById( "numberOfNightsWidget" )[0].selected = true;
		}
	} else {
		document.getElementById( "numberOfNightsWidget" )[0].selected = true;
	}
	return false;
}

function returnDateOnChange( numberOfCities ) {
	var departureDate = trim( document.getElementById( "departureDate" ).value );
	var returnDate = trim( document.getElementById( "returnDate" ).value );
	if( ( ( departureDate != "" ) && ( departureDate != "mm/dd/yyyy" ) )  && ( ( returnDate !="" ) && ( returnDate != "mm/dd/yyyy" ) ) ) {
		var fromDate = new Date( departureDate );
		var toDate = new Date( returnDate );
		var nights = 0;
		if( fromDate < toDate ) {
			nights = computeDifferenceBetweenDates( fromDate, toDate );
		} 
		var previousNights = _totalNumberOfNights;
		//If nights is greater then previously selected nights, distribute the extra nights across the cities.
		//otherwise deduct the difference nights across the cities.
		if( nights > previousNights ) {
			var extraNights = ( nights - previousNights ) % numberOfCities;
			var extraNightsPerCity = parseInt( ( nights - previousNights ) / numberOfCities );
			for( var cityIndex = 1 ; ( ( cityIndex <= numberOfCities ) && ( ( extraNightsPerCity > 0 ) || ( extraNights > 0 ) ) ) ; cityIndex++ ) {
				var nightsField = document.getElementById( "numberOfNights" + cityIndex );
				var nightsFieldLength = nightsField.length;
				var updatedNightsPerCity = extraNightsPerCity;
				var selectedNight = parseInt( nightsField.value );
				if( extraNights > 0 ) {
					extraNights--;
					updatedNightsPerCity++;
				}
				if( !( isNaN( selectedNight ) ) ) {
					updatedNightsPerCity += selectedNight;
				}
				if( ( updatedNightsPerCity >= parseInt( _minDays[ cityIndex - 1 ] ) ) && ( updatedNightsPerCity <= parseInt( nightsField[ nightsFieldLength - 1 ].value ) ) ) {
					nightsField.value = updatedNightsPerCity;
				} else {
					nightsField[ 0 ].selected = true;
				}
			}
		} else {
			var extraNights = ( previousNights - nights );
			for( var cityIndex = 1 ; ( extraNights > 0 ) ; cityIndex++ ) {
				var nightsField = document.getElementById( "numberOfNights" + cityIndex );
				var numberOfNightsPerCity = parseInt( nightsField.value );
				if( !( isNaN( numberOfNightsPerCity ) ) ) {
					numberOfNightsPerCity--;
					if( numberOfNightsPerCity >= parseInt( _minDays[ cityIndex - 1 ] ) ) {
						nightsField.value = numberOfNightsPerCity;
					} else {
						nightsField[ 0 ].selected = true;
					}
				}
				extraNights--;
				if( cityIndex == numberOfCities ) {
					cityIndex = 0;
				}
			}
		}
	}
}

/* function which loads suggestion box of cities as user keys 3 chars in departure city text box.*/
function loadDepartureCities( event, fromWidget ) {
	var cityNameField;
	var content = "";
	
	//Cannot set _event = event because 
	//when callbackLoadDepartureCities is invoked as a result of the makeAjaxCall then the event object is no longer defined,
	//which causes a javascript error in IE6. 
	_event = {keyCode: event.keyCode};
	_fromWidget = fromWidget;

	if( fromWidget){
		cityNameField = document.getElementById( "departureCityTextWidget" );
		content = "mainContent";
		_departureCityString = "departureCityTextWidget";
	}
	else{
		cityNameField = document.getElementById( "departureCityText" );
		content = "searchPopupDivContainer";
		_departureCityString = "departureCityText";
	} 
	
	var cityName = cityNameField.value.toUpperCase();
	_cityName = cityName;
	
	//if ESC key pressed
	if( _event.keyCode == 27 ){
		clearHotelIdDiv();
		hideRegionAndHotelColumns();
		hideSuggestionBox();
		return false;
	}
	
	if(cityName.length < 3) {
	 	airportInfos = null;
	 	hideSuggestionBox();
	}	
	else if( cityName.length >= 3 && trim( cityName ) != "") {
		if(airportInfos == null) {
			var queryString = "";
			queryString += "sh=0";
			queryString += '&departureCity=' + cityName;

			makeAjaxCall( 'searchHelper.act', queryString, null, content, 'callbackLoadDepartureCities', '' );			
		}
		else {
			callbackLoadDepartureCities();		
		}
	}	
}

function callbackLoadDepartureCities( message, errorCode, airportInfosJson ) {
	if( message &&  message != '' ) {
		if( _fromWidget ) {
			showMessage( message, errorCode, 'dataContent' );
		} else {
			showMessage( message, errorCode, 'searchPopupDivContainer' );
		}
	} else {
		if(airportInfosJson) {
			airportInfos = eval(airportInfosJson);
		}
		
		var suggestions = new Array();
		if(airportInfos) {
			for(var index = 0; index < airportInfos.length; ++index) {
				if(airportInfos[index].name.toUpperCase().indexOf(_cityName) == 0) {
					suggestions[airportInfos[index].code] = "(" + airportInfos[index].code + ") " + airportInfos[index].name + ", " + airportInfos[index].cityName + ", " + airportInfos[index].state;
				}
				if(airportInfos[index].cityName.toUpperCase().indexOf(_cityName) == 0) {
					suggestions[airportInfos[index].code] = "(" + airportInfos[index].code + ") " + airportInfos[index].name + ", " + airportInfos[index].cityName + ", " + airportInfos[index].state;
				}
				if(airportInfos[index].code.toUpperCase() == _cityName) {
					suggestions[airportInfos[index].code] = "(" + airportInfos[index].code + ") " + airportInfos[index].name + ", " + airportInfos[index].cityName + ", " + airportInfos[index].state;
				}			
			}
		}
		
		if( _fromWidget ){
			document.getElementById( "departureCityCodeWidget" ).value ="";
			showSuggestionBox( _event, 'departureCityTextWidget', suggestions, 'tc04 w295 fs11 h90','No departure cities found with given criteria' );
		}
		else {
			document.getElementById( "departureCityCode" ).value ="";
			showSuggestionBox( _event, 'departureCityText', suggestions, 'tc04 w295 fs11 h90','No departure cities found with given criteria' );
		}
	}
	return true;
}

//Overridden method from common.js that sets the display text in departure city text field
function _setSuggestionParentElementValue(parentElement, selectedKey, selectedValue) {
	if(parentElement) {
		parentElement.value = selectedValue.substring( 0, selectedValue.indexOf( ","));
	}
}



function showSearchPackageTab() {
	loadRightContent('rightContent.act', null, '/home');
	loadLeftBottomContent('leftBottomContent.act', 'lbc=0', '');
	loadLeftContent('leftContent.act','lc=6' );
	varSearchMode = "VacationPackage";
}

function showSearchCruisesTab() {
	loadCruise();
}

function showSearchCarsTab() {
	document.getElementById( "packageTabInfo" ).style.display = 'none';
	document.getElementById( "cruisesTabInfo" ).style.display = 'none';
	document.getElementById( "carsTabInfo" ).style.display='block';
	document.getElementById( "hotelsTabInfo" ).style.display='none';
	document.getElementById( "searchPackageTab" ).className = "search-tab";
	document.getElementById( "searchCruisesTab" ).className = "search-tab";
	document.getElementById( "searchCarsTab" ).className = "search-tab-sel";
	document.getElementById( "carsTabInfo" ).className = 'bo02';
	document.getElementById( "carsTabInfo" ).innerHTML = "<div class='p10 fs11'>Hit the road with exceptional savings on an economical compact, a sleek convertible, a rugged SUV or just about any other type of vehicle. <br /><br /><b>Book online</b>.</div>";
	document.getElementById( "searchHotelsTab" ).className = "search-tab";
	loadRightContent('rightContent.act', 'rc=6&ancillary=rentalCars', '/rc/browse/rentalCarsHome');
	loadLeftBottomContent('leftBottomContent.act', 'lbc=0', '');
}

function showSearchHotelsTab() {
	document.getElementById( "packageTabInfo" ).style.display = 'none';
	document.getElementById( "cruisesTabInfo" ).style.display = 'none';
	document.getElementById( "carsTabInfo" ).style.display='none';
	document.getElementById( "hotelsTabInfo" ).style.display='block';
	document.getElementById( "searchPackageTab" ).className = "search-tab";
	document.getElementById( "searchCruisesTab" ).className = "search-tab";
	document.getElementById( "searchCarsTab" ).className = "search-tab";
	document.getElementById( "searchHotelsTab" ).className = "search-tab-sel";
	document.getElementById( "hotelsTabInfo" ).className = 'bo02';
	document.getElementById( "hotelsTabInfo" ).innerHTML = "<div class='p10 fs11'><b>For a City Stay, a Business Stay or Other Independent Travel:</b><br />Check out the member savings with Best Western and Hyatt Hotels & Resorts&#174;.<br/><br/>Book Best Western online.<br /><br />To book Hyatt Hotels & Resorts, call Costco Travel toll free at <b>1-877-849-2730</b>.<br /><br /><b>For Vacation Travel:</b><br />Click on the Packages tab above for other hotel options.</div>";
	loadRightContent('rightContent.act', 'rc=6&ancillary=hotels', '/an/browse/ancillaryID//hotels ');
	loadLeftBottomContent('leftBottomContent.act', 'lbc=0', '');
}

function onKeyDownOnSearchPopup( event, packageId, includeFlightItinerary, numberOfCities, fromMenu  ){
	if ( event && event.keyCode == 13 ){
		var searchPopupDiv = document.getElementById( "searchPopupDiv" );
		if ( searchPopupDiv != undefined ){
			searchPackage( packageId, includeFlightItinerary, numberOfCities, fromMenu );
		}
	}
}

function onChildAgeWidgetChange(childIndex, roomIndex) {
	var childAgeSelectBoxForWidget = document.getElementById("childAgeForWidget_"+ childIndex + "_" + roomIndex);
	var flightItineraryCheckboxWidget =  document.getElementById("flightItineraryCheckboxWidget");
	var infantSeatSelectWidget = document.getElementById("infantSeatSelectWidget_" + childIndex + "_" + roomIndex);
	setInfantSeatSelectDisplay(flightItineraryCheckboxWidget,childAgeSelectBoxForWidget, infantSeatSelectWidget);
}


function onChildAgeChange(childIndex, roomIndex) {
	var childAgeSelectBox = document.getElementById("childAge_"+ childIndex + "_" + roomIndex);
	var flightItineraryCheckbox =  document.getElementById("flightItineraryCheckbox");
	var infantSeatSelect= document.getElementById("infantSeatSelect_" + childIndex + "_" + roomIndex);
	setInfantSeatSelectDisplay(flightItineraryCheckbox, childAgeSelectBox, infantSeatSelect);	
}

function setInfantSeatSelectDisplay(flightItineraryCheckbox, childAgeSelectBox, infantSeatSelect) {	
	if(childAgeSelectBox && isInfant(childAgeSelectBox.value) && flightItineraryCheckbox && flightItineraryCheckbox.checked) {	
		infantSeatSelect.style.display = "";	
	}else {
		infantSeatSelect.style.display = "none";
	}
}

function setSupportPhoneNumber(phoneNumber){
	document.getElementById("tollNumber").innerHTML = phoneNumber;
/*
	if (phoneNumber == supportPhoneNumber){
		document.getElementById("phoneMessage").innerHTML = supportMessage;
	}	
	else if (phoneNumber == bookingPhoneNumber){
		document.getElementById("phoneMessage").innerHTML = bookingMessage;
	}
*/
}


function convertJsonToDateRange( jsonDateRange ) {
	var dateRanges = new Array();
	if( jsonDateRange != null  && jsonDateRange != "" ) {
		var josnDateRanges = eval( jsonDateRange );
		var numberOfDateRanges = josnDateRanges.length;
		for( var index = 0 ; index < numberOfDateRanges ; index++ ) {
			var fromDate  = null;
			var toDate = null;
			if( ( josnDateRanges[ index ].fromDate != null ) && ( josnDateRanges[ index ].fromDate != "" ) ) {
				fromDate = new Date( josnDateRanges[ index ].fromDate );
			}
			if( ( josnDateRanges[ index ].toDate != null ) && ( josnDateRanges[ index ].toDate != "" ) ) {
				toDate = new Date( josnDateRanges[ index ].toDate );
			}
			dateRanges[ index ] = new DateRange( fromDate, toDate );
		}
	}
	return dateRanges;
}

function getDisabledDateRanges( enabledDateRange ) {
	var disableDateRanges = new Array();
	if( enabledDateRange == null || enabledDateRange.length == 0 ) {
		return disableDateRanges;
	}
	var currentDate = new Date();
	currentDate.setHours(0);
 	currentDate.setMinutes(0);
 	currentDate.setSeconds(0);
 	currentDate.setMilliseconds(0);
 	
	//Inserting date range in 0th index of enabled date range array.
	enabledDateRange.splice( 0, 0, new DateRange( new Date( "12/31/1899" ), new Date( "12/31/1899" ) ) );
	enabledDateRange[ enabledDateRange.length ] = new DateRange( new Date( "01/01/2071" ), new Date( "01/01/2071" ) );
	enabledDateRange.sort( sortByDateRange );
	
	var noOfDateRanges = enabledDateRange.length;
	var counter  = 0;
	for( var index = 1 ; index < noOfDateRanges ; index++ ) {
		if( ( enabledDateRange[ index - 1 ].toDate == null ) || ( enabledDateRange[ index - 1 ].toDate == "" ) ) {
			continue;
		}
		var toDate = null;
		// From date is null get the previous index of to date.if to date is less than current date then add current date. 
		if( ( enabledDateRange[ index ].fromDate == null ) || ( enabledDateRange[ index ].fromDate == "" ) ) {
			if( enabledDateRange[ index - 1 ].toDate < currentDate ) {
				toDate = currentDate;
			} else {
				toDate = new Date( enabledDateRange[ index - 1 ].toDate );
			}
		} else {
			toDate = new Date( enabledDateRange[ index ].fromDate );
		}
		var fromDate = new Date( enabledDateRange[ index - 1 ].toDate );
		toDate.setDate( toDate.getDate() - 1 ); 
		fromDate.setDate( fromDate.getDate() + 1 );
		disableDateRanges[ counter ] = new DateRange( fromDate, toDate );
		counter++; 
	}
	return disableDateRanges;
}

function getDisabledDateRangeForPackage( departureDateFieldName ) {
	var jsonDateRange = ( isNull( _travelDateRanges )? null : _travelDateRanges );
	var dateRange = convertJsonToDateRange( jsonDateRange );
	var disabledDateRanges = getDisabledDateRanges( dateRange );
	if( !( isNull( departureDateFieldName ) ) ) {
		var dateRange = getDisabledDateRangeForReturnDate( departureDateFieldName );
		if( !( isNull( dateRange ) ) ) {
			disabledDateRanges[ disabledDateRanges.length ] = dateRange;
			disabledDateRanges.sort( sortByDateRange );
		} 
	}
	return disabledDateRanges;
}

function getDisabledDateRangeForReturnDate( departureDateFieldName ) {
	var departureDateValue = document.getElementById( departureDateFieldName ).value;
	var disabledDateRange = null;
	if( ( departureDateValue != "" ) && ( departureDateValue != "mm/dd/yyyy" ) ) {
		var departureDate = new Date( departureDateValue );
		departureDate.setDate( departureDate.getDate() - 1 );
		disabledDateRange = new DateRange( addDays(new Date(), -1), departureDate );
	}
	return disabledDateRange;
}

function sortByDateRange( firstDateRange, secondDateRange ) {
	var firstDate = new Date( ( firstDateRange.fromDate == null || firstDateRange.fromDate == ""  )? firstDateRange.toDate : firstDateRange.fromDate );
	var secondDate = new Date( ( secondDateRange.fromDate == null || secondDateRange.fromDate == "" )? secondDateRange.toDate : secondDateRange.fromDate );
	if( secondDate > firstDate ) {
		return -1;
	} else if( secondDate < firstDate ) {
		return 1;
	} else {
		return 0;
	}
}

function getSpecialDates( firstFieldName, secondFieldName ) {
	var firstFieldValue = trim( document.getElementById( firstFieldName ).value );
	var secondFieldValue = trim( document.getElementById( secondFieldName ).value );
	var specialDatesForPackage = new Array();
	if( ( firstFieldValue != "" && firstFieldValue != "mm/dd/yyyy" ) &&  ( secondFieldValue != "" && secondFieldValue != "mm/dd/yyyy" ) ) {
		var firstDate = new Date( firstFieldValue );
		var counter = 0;
		var secondDate = new Date( secondFieldValue );
		while( firstDate <= secondDate ) {
			var date = new Date( firstDate );
			specialDatesForPackage[ date ] = date;
			firstDate.setDate( firstDate.getDate() + 1 );
		}
	} else if( ( firstFieldValue != "" && firstFieldValue != "mm/dd/yyyy" ) ) {
		var date = new Date( firstFieldValue );
		specialDatesForPackage[ date ] = date;
	} else if( ( secondFieldValue != "" && secondFieldValue != "mm/dd/yyyy" ) ) {
		var date = new Date( firstFieldValue );
		specialDatesForPackage[ date ] = date;
	}
	return specialDatesForPackage;
}

function showWidgetCalendar( elementName, isReturnDate ) {
	var flightItineraryCheckboxWidget = document.getElementById('flightItineraryCheckboxWidget');
	var disabledDateRanges = new Array();
	if(flightItineraryCheckboxWidget && flightItineraryCheckboxWidget.checked) {
		var minDateRange = new DateRange(getMinCalendarDate(), addDays(new Date(), -1));
		var maxDateRange = new DateRange(addDays(new Date(), 330), getMaxCalendarDate());
		disabledDateRanges = [ minDateRange, maxDateRange ] ;
	}
	if( isReturnDate ) {
		var dateRange = getDisabledDateRangeForReturnDate( 'departureDateWidget' );
		if( !( isNull( dateRange ) ) ) {
			disabledDateRanges[ disabledDateRanges.length ] = dateRange;
			disabledDateRanges.sort( sortByDateRange );
		}
	}
	showCalendar( elementName, getSpecialDates( 'departureDateWidget', 'returnDateWidget'), disabledDateRanges );
}

function showTravelCalendar(elementName, isReturnDate) {

	var specialDates = getSpecialDates( 'departureDate', 'returnDate' );
	var disabledDateRanges;
	if(isReturnDate) {
		disabledDateRanges = getDisabledDateRangeForPackage('departureDate');
	} else {
		disabledDateRanges = getDisabledDateRangeForPackage();
	}	
	var currentDate = getCurrentDate();
	var startDate = getFirstEnabledDate(currentDate, disabledDateRanges);
	return showCalendar( elementName, specialDates, disabledDateRanges, startDate);
}

function flightItineraryCheckBoxOnClick() {
	loadFlightItineraryInformation();
	var isFlightItineraryField = document.getElementById( "flightItineraryCheckbox" );
	if( isFlightItineraryField ){
		var isFlightItinerary = isFlightItineraryField.checked;
		if( !isFlightItinerary ){
			displayInfantSeatSelects(false);
		}else {
			displayInfantSeatSelects(true);
		}
	}	
}

function flightItineraryCheckBoxWidgetOnClick() {
	loadFlightItineraryInformationForWidget();
	var isFlightItineraryField = document.getElementById( "flightItineraryCheckboxWidget" );
	if( isFlightItineraryField ){
		var isFlightItinerary = isFlightItineraryField.checked;
		if( !isFlightItinerary ){
			displayInfantSeatSelectsForWidget(false);
		}else {
			displayInfantSeatSelectsForWidget(true);
		}
	}	
} 

function loadHotels( event ) {
	_event = {keyCode: event.keyCode};

	var cityNameField = document.getElementById( "region" );
	var hotelNameField = document.getElementById( "hotelNameWidget" );
	
	var cityName = cityNameField.value.toUpperCase();
	var hotelName = hotelNameField.value.toUpperCase();
	_hotelName = hotelName;
	
	//if ESC key pressed
	if( _event.keyCode == 27 ){
		clearHotelIdDiv();
		hideRegionAndHotelColumns();
		hideSuggestionBox();
		return false;
	}
	
	var hotelIdOptionList = document.getElementById( "hotelIdList" );
	if( hotelIdOptionList == null || hotelIdOptionList == undefined ){
		var queryString = "";
		queryString += "sh=1";
		queryString += '&city=' + cityName;
		makeAjaxCall( 'searchHelper.act', queryString, null, 'mainContent', 'callbackLoadHotels', '' );			
	}else {
		callbackLoadHotels();		
	}	
}

function callbackLoadHotels( message, errorCode, hotelIdList ) {
	if( message &&  message != '' ) {
		showMessage( message, errorCode, 'dataContent' );
	} else {
		if( hotelIdList != null && hotelIdList != undefined  ){
			document.getElementById( "hotelIdDiv" ).innerHTML = "<select name = 'hotelIdList' id= 'hotelIdList'>"  + hotelIdList + "</select>";
		}
		var hotelIdOptionList = document.getElementById( "hotelIdList" );
		var suggestions = new Array();
		if( hotelIdOptionList != null && hotelIdOptionList != undefined ) {
			for(var index = 0; index < hotelIdOptionList.length; ++index) {
				var hotelNameFromOptionList = hotelIdOptionList[index].text;
				if( hotelNameFromOptionList.indexOf( '***' ) == 0 ){
					hotelNameFromOptionList = hotelNameFromOptionList.substring( 3, hotelNameFromOptionList.length );
				}
				if ( trim(_hotelName ) == '' ){
					suggestions[hotelIdOptionList[index].value] = hotelNameFromOptionList;
				}else
					if( hotelNameFromOptionList.toUpperCase().indexOf(_hotelName.toUpperCase()) != -1 ) {
					suggestions[hotelIdOptionList[index].value] = hotelNameFromOptionList;
				}
			}
		}
		showSuggestionBox( _event, 'hotelNameWidget', suggestions, 'tc04 w295 fs11 h90','No hotel found with given criteria' );
	}
	return true;
}

function setSuggestionBoxSelectOptionValue( elementName ){
	if( elementName != null && elementName != undefined ){
		var suggestionBoxSelect = document.getElementById("_suggestionBoxSelect");
		if( elementName.id == 'hotelNameWidget' ){
			document.getElementById( "hotelIdWidget" ).value = suggestionBoxSelect.value;
		}else if( elementName.id == 'departureCityTextWidget' ){
			document.getElementById( "departureCityCodeWidget" ).value = suggestionBoxSelect.value;
		}else if( elementName.id == 'departureCityText' ){
			document.getElementById( "departureCityCode" ).value = suggestionBoxSelect.value;
		}
		return true;
	}
}

function clearHotelIdDiv() {
	if( document.getElementById( "region" )[0].selected ){
		document.getElementById( "hotelNameTd" ).style.display = "none";	
	}else {
		//document.getElementById( "hotelNameTd" ).style.display = "block";
		document.getElementById( "hotelNameTd" ).style.display = "none";
	}
	document.getElementById( "hotelIdDiv" ).innerHTML = "";
	document.getElementById( "hotelNameWidget" ).value = "";
}

function clearHiddenFieldValuesWhenNoSuggesionsFound( elementName ){
	if( elementName == 'hotelNameWidget' ){
		var hotelIdField = document.getElementById( "hotelIdWidget" );
		if( hotelIdField != null && hotelIdField != undefined ){
			hotelIdField.value = "";
		}
	}
	return true;
}

function hideRegionAndHotelColumns(){
	document.getElementById( "cityTd" ).style.display = "none";
	document.getElementById( "hotelNameTd" ).style.display = "none";
	document.getElementById( "destination" )[0].selected = true;
}
/*****global variable section.*****/ 
var _productUid;
var _targetAct;
var _fromSearchResults;
var _cityUid;
var _tickingPriceTicker;
var _sightseeingDates;
var _itemUid;
var HOURS_ALLOWED_WITHOUT_EXTRA_CHARGE = 1;

function loadSearchResults_1() {
	var queryString = 'sr=1';
	//Make Ajax call with '/vp/booking/searchDestination///package/<packageId>' as the description to be passed into Google Analytics
	var trackingText = '/vp/booking/searchDestination///package/' + _packageId; 
	makeAjaxCall( 'searchResults.act', queryString, null, 'mainContent', 'callbackLoadSearchResults_1', trackingText );	
}

function callbackLoadSearchResults_1( message, errorCode ) {
	showMessage( message, errorCode, 'dataContent' );
	return true;
}

function loadSearchResults_2() {
	var queryString = 'sr=2';
	makeAjaxCall( 'searchResults.act', queryString, null, 'mainContent', 'callbackLoadSearchResults_2', '' );	
}

function callbackLoadSearchResults_2( message, errorCode ) {
	showMessage( message, errorCode, 'dataContent' );
	return true;
}

function ignoreChanges( productUid, targetActivity ) {
	window.clearTimeout( _tickingPriceTicker );
	var queryString = 'sr=3';
	queryString += '&uid=' + productUid;
	_productUid = productUid;
	_targetAct = targetActivity;
	//Make Ajax call with '/vp/booking/searchOptions/<destinationCode>/<regionCode>/package/<packageId>' as the description to be passed into Google Analytics
	var trackingText = '/vp/booking/searchOptions/' + _destinationCode + '/' + _regionCode + '/package/' + _packageId; 
	makeAjaxCall( 'searchResults.act', queryString, null, 'rightContent', 'callbackIgnoreChanges', trackingText );
}

function callbackIgnoreChanges( message, errorCode ) {
	showMessage( message, errorCode, 'dataContent' );
	loadProductSummary( _targetAct, _productUid );
	return true;
}

function applyChanges(  productUid, targetActivity ) {
	window.clearTimeout( _tickingPriceTicker );
	disableElement( 'dataContent', true );
	var queryString = 'sr=4';

	// product uid and target activity are required to be stored in global js variables only if 
	// we are calling loadProductSummary(...) js function in callbackApplyChanges(...) function

	//_productUid = productUid;
	//_targetAct = targetActivity;
	//makeAjaxCall( 'searchResults.act', queryString, null, 'mainContent', 'callbackApplyChanges', '' );

	var asynchronousRequest = new AsynchronousRequest();
	asynchronousRequest.url = _webLoc + '/searchResults.act';
	asynchronousRequest.queryString = queryString;
	asynchronousRequest.useAjax = true;
	asynchronousRequest.target = 'mainContent';
	asynchronousRequest.callbackFunctionName = 'callbackApplyChanges';

	var splashScreenRequest = new SplashScreenRequest();
	splashScreenRequest.splashScreenText = "Please Wait...";
	asynchronousRequest.splashScreenRequest = splashScreenRequest;
	asynchronousRequest.splashScreenDisplayFunctionName = "displaySearchingPopup";
	asynchronousRequest.splashScreenHideFunctionName = "hideSearchingPopup";

	makeAjaxCallWithRequest( asynchronousRequest, '' );
}

function callbackApplyChanges( message, errorCode, targetValue ) {
	disableElement( 'dataContent', false );
	showMessage( message, errorCode, 'dataContent' );
	var queryString;
	if (targetValue == 0){
		queryString = 'sr=1';
	}	
	else {
		queryString = 'sr=2';
	}	
	makeAjaxCall( 'searchResults.act', queryString, null, 'mainContent', 'callbackAfterApplyChanges', '' );
}

function callbackAfterApplyChanges( message, errorCode){
	showMessage( message, errorCode, 'dataContent' );
	loadTripSummary();
	return true;
}

function updatePackagePrice(updatedPackagePrice, priceDisplayElementName, priceHiddenElementName) {
	var priceHiddenElement = document.getElementById( priceHiddenElementName );
	if(!priceHiddenElement) {
		priceHiddenElement = document.getElementById( "totalPackagePrice" );
	}
	
	var priceDisplayElement = document.getElementById( priceDisplayElementName );
	if(!priceDisplayElement) {
		priceDisplayElement = document.getElementById( "totalPackagePriceDisplay" );
	}	
	
	var newPackagePrice = Math.floor( updatedPackagePrice );
	var oldPackagePrice = Math.floor( priceHiddenElement.value );
	
	if( newPackagePrice > oldPackagePrice ) {
		if( ( ( newPackagePrice - oldPackagePrice ) / 500 ) > 1 ) {
			oldPackagePrice = oldPackagePrice + 500;
		} else if( ( ( newPackagePrice - oldPackagePrice ) / 250 ) > 1 ) {
			oldPackagePrice = oldPackagePrice + 250;
		} else if( ( ( newPackagePrice - oldPackagePrice ) / 100 ) > 1 ) {
			oldPackagePrice = oldPackagePrice + 100;
		} else if( ( ( newPackagePrice - oldPackagePrice ) / 50 ) > 1 ) {
			oldPackagePrice = oldPackagePrice + 50;
		} else if( ( ( newPackagePrice - oldPackagePrice ) / 10 ) > 1 ) {
			oldPackagePrice = oldPackagePrice + 10;
		} else {
			oldPackagePrice = oldPackagePrice + 1;
		}
		priceHiddenElement.value = oldPackagePrice;
		priceDisplayElement.innerHTML = "$" + oldPackagePrice + ".00";
		_tickingPriceTicker = setTimeout( "updatePackagePrice( '" + updatedPackagePrice + "', '" + priceDisplayElement.id + "', '" + priceHiddenElement.id + "' )", 10 );	
	} else if( oldPackagePrice > newPackagePrice ) {
		if( ( ( oldPackagePrice - newPackagePrice ) / 500 ) > 1 ) {
			oldPackagePrice = oldPackagePrice - 500;
		} else if( ( ( oldPackagePrice - newPackagePrice ) / 250 ) > 1 ) {
			oldPackagePrice = oldPackagePrice - 250;
		} else if( ( ( oldPackagePrice - newPackagePrice ) / 100 ) > 1 ) {
			oldPackagePrice = oldPackagePrice - 100;
		} else if( ( ( oldPackagePrice - newPackagePrice ) / 50 ) > 1 ) {
			oldPackagePrice = oldPackagePrice - 50;
		} else if( ( ( oldPackagePrice - newPackagePrice ) / 10 ) > 1 ) {
			oldPackagePrice = oldPackagePrice - 10;
		} else {
			oldPackagePrice = oldPackagePrice - 1;
		}
		priceHiddenElement.value = oldPackagePrice;
		priceDisplayElement.innerHTML = "$" + oldPackagePrice + ".00";
		_tickingPriceTicker = setTimeout( "updatePackagePrice( '" + updatedPackagePrice + "', '" + priceDisplayElement.id + "', '" + priceHiddenElement.id + "' )", 10 );
	} else {
		priceHiddenElement.value = updatedPackagePrice;
		priceDisplayElement.innerHTML =formatCurrency( updatedPackagePrice );		
		return true;
	}
}

function loadSearchResults( cityCounter, totalCities ) {
	if( cityCounter == -1 ){
		loadSearchResults_1();
	}else if( cityCounter == totalCities ){
		loadTripProtectionPopup();
	}else{
		var queryString = 'rc=12';
		queryString += '&cityCounter=' + cityCounter;
		//Make Ajax call with '/vp/booking/searchDestination///package/<packageId>' as the description to be passed into Google Analytics
		var trackingText = '/vp/booking/searchDestination///package/' + _packageId; 
		makeAjaxCall( 'rightContent.act', queryString, null, 'rightContent', 'callbackSearchResults02', trackingText );
	}
}

function callbackSearchResults02(){
	showMessage(this.errorMessage, this.errorCode);
	return true;
}

function continueToSearchResults02() {
	var queryString = 'sr=10';
	makeAjaxCall( 'searchResults.act', queryString, null, 'mainContent', 'callbackContinueToSearchResults02', '' );
}

function callbackContinueToSearchResults02( message, errorCode ) {
	showMessage( message, errorCode, 'dataContent' );
	return true;
}
/*****************************flight results section**********************************************/
function chooseDifferentFlight( flightProductUid ) {
	window.clearTimeout( _tickingPriceTicker );
	var queryString = 'fr=1';
	queryString += '&uid=' + flightProductUid;
	//Make Ajax call with '/vp/booking/searchFlights/<destinationCode>/<regionCode>/package/<packageId>' as the description to be passed into Google Analytics
	var trackingText = '/vp/booking/searchFlights/' + _destinationCode + '/' + _regionCode + '/package/' + _packageId; 
	makeAjaxCall( 'flightResults.act', queryString, null, 'rightContent', 'callbackChooseDifferentFlight', trackingText );	
}

function callbackChooseDifferentFlight() {
	showMessage( this.errorMessage, this.errorCode, 'dataContent' );
	return true;
}

function sortFlights( flightProductUid, sortType, airlineCode, isForLIP, packageId , isAscendingOrder ) {
	var queryString = '';
	queryString += '&uid=' + flightProductUid;	
	queryString += '&fr=' + sortType;
	queryString += '&selectedAirline=' + airlineCode;
	queryString += '&forLIP=' + isForLIP;
	queryString += '&packageId=' + packageId;
	queryString += '&ascendingOrder=' + isAscendingOrder;
	makeAjaxCall( 'flightResults.act', queryString, null, flightProductUid, 'callbackSortFlights', '' );
}

function callbackSortFlights() {
	showMessage( this.errorMessage, this.errorCode, 'dataContent' );
	return true;
}

function filterFlightsByAirline( flightProductUid, airlineCode, isForLIP, packageId ) {
	var queryString = 'fr=8';
	queryString += '&uid=' + flightProductUid;
	queryString += '&selectedAirline=' + airlineCode;
	queryString += '&forLIP=' + isForLIP;
	queryString += '&packageId=' + packageId;
	makeAjaxCall( 'flightResults.act', queryString, null, flightProductUid, 'callbackFilterFlightsByAirline', '' );	
}

function callbackFilterFlightsByAirline() {
	showMessage( this.errorMessage, this.errorCode, 'dataContent' );
	return true;
}

function filterFlightsByAlliances( flightProductUid, airlineAlliance ) {
	filterFlightsByAirline( flightProductUid, _airlineAlliances[airlineAlliance] );
}

/* shows all flights, no filtering criteria by airlines.*/
function showAllFlights( flightProductUid, isForLIP, packageId ) {
	var queryString = 'fr=11';
	queryString += '&uid=' + flightProductUid;
	queryString += '&forLIP=' + isForLIP;
	queryString += '&packageId=' + packageId;
	makeAjaxCall( 'flightResults.act', queryString, null, flightProductUid, 'callbackShowAllFlights', '' );
}

function callbackShowAllFlights() {
	showMessage( this.errorMessage, this.errorCode, 'dataContent' );
	return true;
}

function loadFlightDetails( itemUid, selectedAirline, segmentOnDisplay, isForLIP ) {
	// create pop up div for flight details.	
	var flightDetailsPopupDivContainer = document.getElementById( 'flightDetailsPopupDivContainer' ); 
	if( isNull( flightDetailsPopupDivContainer ) ) {
		flightDetailsPopupDivContainer = createPopupDiv('flightDetailsPopupDivContainer', 0, 0, 700, 204, false, true,  "");
		//flightDetailsPopupDivContainer = document.createElement('DIV');
		//flightDetailsPopupDivContainer.id = 'flightDetailsPopupDivContainer';
		//flightDetailsPopupDivContainer.onmouseover = function( event ) { setDragEvent( 'flightDetailsPopupDivContainer', event ) };
		//document.body.insertBefore( flightDetailsPopupDivContainer, document.body.firstChild );
	}
	
	//flightDetailsPopupDivContainer.style.position = "absolute";
	//flightDetailsPopupDivContainer.style.width = "700";
	//flightDetailsPopupDivContainer.style.height = "450";
	//flightDetailsPopupDivContainer.style.zIndex = "200";
	//flightDetailsPopupDivContainer.innerHTML = '';
		
	var queryString = 'fr=6';
	queryString += '&uid=' + itemUid;
	queryString += '&selectedAirline=' + selectedAirline;
	queryString += '&isSearchResultsFormat=1';
	queryString += '&segmentOnDisplay=' + segmentOnDisplay;
	queryString += '&forLIP=' + isForLIP;
	makeAjaxCall( 'flightResults.act', queryString, null, 'flightDetailsPopupDivContainer', 'callbackLoadFlightDetails', '' );
}

function callbackLoadFlightDetails() {
	showMessage( this.errorMessage, this.errorCode, 'flightDetailsPopupDivContainer' );
	
	var flightDetailsPopupDiv = document.getElementById('flightDetailsPopupDiv');
	if( flightDetailsPopupDiv ) {
		flightDetailsPopupDivContainer.style.height = flightDetailsPopupDiv.style.height;
	}
	showBlock( 'flightDetailsPopupDivContainer' );
	positionBlockCentrally( 'flightDetailsPopupDivContainer' );	
	disableElement( 'dataContent', true );
	var additionalSearchResultsPopup = document.getElementById( 'additionalSearchResultsPopupDivContainer' );
	if( additionalSearchResultsPopup) { 
		disableElement('additionalSearchResultsPopupDivContainer', true);
	}
	return true;
}

function changeFlightItem( flightItemUid, productUid, airlineCode, callBackFunctionName, isForLIP, packageId ) {
	window.clearTimeout( _tickingPriceTicker );	
	var queryString = 'fr=7';
	queryString += '&uid=' + flightItemUid;
	queryString += '&selectedAirline=' + airlineCode;
	queryString += '&forLIP=' + isForLIP;
	queryString += '&packageId=' + packageId;
	if(!callBackFunctionName) {
		callBackFunctionName = 'callbackChangeFlightItem';
	}
	makeAjaxCall( 'flightResults.act', queryString, null, productUid, callBackFunctionName, '' );
}

function callbackChangeFlightItem() {
	showMessage( this.errorMessage, this.errorCode, 'dataContent' );
	return true;
}

function callbackChangeFlightItemFromDetails() {
	showMessage( this.errorMessage, this.errorCode, 'dataContent' );
	removeElement('flightDetailsPopupDivContainer'); 
	disableElement( 'dataContent', false );
	return true;
}

function callbackChangeFlightItemFromSeatMap() {
	removeElement('flightSeatMapPopupDiv'); 
	disableElement( 'dataContent', false );
	showMessage( this.errorMessage, this.errorCode, 'dataContent' );
	return true;
}

function loadFlightTNC() {
	// create popup div for flight TNC.	
	var flightTNCPopupDivContainer = document.getElementById('flightTNCPopupDivContainer');
	if( isNull( flightTNCPopupDivContainer ) ) {
		flightTNCPopupDivContainer = createPopupDiv('flightTNCPopupDivContainer', 0, 0, 450, 204, false, true,  "tal popupDivSmall");
		//flightTNCPopupDivContainer = document.createElement('DIV');
		//flightTNCPopupDivContainer.id = 'flightTNCPopupDivContainer';
		//flightTNCPopupDivContainer.onmouseover = function( event ) { setDragEvent( 'flightTNCPopupDivContainer', event ) };
		//document.body.insertBefore( flightTNCPopupDivContainer, document.body.firstChild );
	}
	
	//flightTNCPopupDivContainer.style.display = "none";
	//flightTNCPopupDivContainer.style.position = "absolute";
	//flightTNCPopupDivContainer.style.width = "450";
	//flightTNCPopupDivContainer.style.zIndex = "200";
	//flightTNCPopupDivContainer.className = "tal popupDivSmall";
	//flightTNCPopupDivContainer.id = "flightTNCPopupDivContainer";
	
	makeAjaxCall('search/airlineTNCPopup.jsp', 'flightTNCPopupDiv=true', null, 'flightTNCPopupDivContainer', 'callbackLoadFlightTNC');
}

function callbackLoadFlightTNC( message, errorCode ) {
	showBlock('flightTNCPopupDivContainer');
	positionBlockCentrally('flightTNCPopupDivContainer');
	var additionalSearchResultsPopup = document.getElementById( 'additionalSearchResultsPopupDivContainer' );
	if( additionalSearchResultsPopup ) { 
		disableElement('additionalSearchResultsPopupDivContainer', true);
	}
	disableElement('dataContent', true);
}
/*************************************hotel results section***********************************************/
function chooseDifferentHotel( productUid ) {
	var queryString = 'hr=11';
	queryString += '&uid=' + productUid;
	makeAjaxCall( 'hotelResults.act', queryString, null, 'rightContent', 'callbackChooseDifferentHotel', '' );
}

function callbackChooseDifferentHotel() {
	showMessage( this.errorMessage, this.errorCode, 'dataContent' );
	return true;
}

function sortHotelsByPrice( productUid, fromSearchResults , isAscendingOrder ) {
	var queryString = 'hr=3';
	queryString += '&uid=' + productUid;
	queryString += '&fromSearchResults=' + fromSearchResults;
	queryString += '&ascendingOrder=' + isAscendingOrder;
	if( fromSearchResults.toUpperCase() == "TRUE" ) {
		makeAjaxCall( 'hotelResults.act', queryString, null, productUid, 'callbackSortHotelsByPrice', '' );
	} else {
		makeAjaxCall( 'hotelResults.act', queryString, null, 'rightContent', 'callbackSortHotelsByPrice', '' );
	}
}

function callbackSortHotelsByPrice() {
	showMessage( this.errorMessage, this.errorCode, 'dataContent' );
	return true;
}

function sortHotelsByBestValue( productUid, fromSearchResults , isAscendingOrder ) {
	var queryString = 'hr=4';
	queryString += '&uid=' + productUid;
	queryString += '&fromSearchResults=' + fromSearchResults;
	queryString += '&ascendingOrder=' + isAscendingOrder;
	if( fromSearchResults.toUpperCase() == "TRUE" ) {
		makeAjaxCall( 'hotelResults.act', queryString, null, productUid, 'callbackSortHotelsByBestValue', '' );
	} else {
		makeAjaxCall( 'hotelResults.act', queryString, null, 'rightContent', 'callbackSortHotelsByBestValue', '' );
	}
}

function callbackSortHotelsByBestValue() {
	showMessage( this.errorMessage, this.errorCode, 'dataContent' );
	return true;
}

function changeHotelItem( itemUid, productUid, fromSearchResults, targetActivity ) {
	window.clearTimeout( _tickingPriceTicker );
	var queryString = 'hr=1';
	queryString += '&uid=' + itemUid;
	queryString += '&fromSearchResults=' + fromSearchResults;
	if ( fromSearchResults.toUpperCase() == "TRUE" ){
		_fromSearchResults = true;
		_productUid = productUid;
		_targetAct = targetActivity;
	} else {
		_fromSearchResults = false;
	}
	disableElement( 'dataContent', true );
    	
	var asynchronousRequest = new AsynchronousRequest();
	asynchronousRequest.url = _webLoc + '/hotelResults.act';
	asynchronousRequest.queryString = queryString;
	asynchronousRequest.useAjax = true;
	asynchronousRequest.target = productUid;
	asynchronousRequest.callbackFunctionName = 'callbackChangeHotelItem';

	var splashScreenRequest = new SplashScreenRequest();
	splashScreenRequest.splashScreenText = "Please Wait...";
	asynchronousRequest.splashScreenRequest = splashScreenRequest;
	asynchronousRequest.splashScreenDisplayFunctionName = "displaySearchingPopup";
	asynchronousRequest.splashScreenHideFunctionName = "hideSearchingPopup";

	makeAjaxCallWithRequest( asynchronousRequest, '' );
	
	//makeAjaxCall( 'hotelResults.act', queryString, null, productUid, 'callbackChangeHotelItem', '' );
}

function callbackChangeHotelItem() {
	disableElement( 'dataContent', false );
	showMessage( this.errorMessage, this.errorCode, 'dataContent' );
	if( _fromSearchResults ) {
		loadProductSummary( _targetAct,_productUid );
	}
	return true;
}

function includeExcludeService( serviceItemUid, hotelSubCategoryItemUid, productUid, quantity, fromSearchResults ) {
	window.clearTimeout( _tickingPriceTicker );
	var queryString = 'hr=2';
	queryString += '&serviceUid=' + serviceItemUid;
	queryString += '&uid=' + hotelSubCategoryItemUid;
	var serviceItemSelectionField = document.getElementById( "service_" + serviceItemUid );
	if( serviceItemSelectionField.checked ) {
		queryString += '&serviceQuantity=' + quantity;
	} else {
		queryString += '&serviceQuantity=0';
	}
	queryString += '&fromSearchResults=' + fromSearchResults;
	makeAjaxCall( 'hotelResults.act', queryString, null, productUid, 'callbackIncludeExcludeService', '' );
}

function callbackIncludeExcludeService() {
	showMessage( this.errorMessage, this.errorCode, 'dataContent' );
	return true;
}

function updateServiceQuantity( serviceItemUid, hotelSubCategoryItemUid, productUid, fromSearchResults ) {
	window.clearTimeout( _tickingPriceTicker );
	var queryString = 'hr=2';
	queryString += '&serviceUid=' + serviceItemUid;
	queryString += '&uid=' + hotelSubCategoryItemUid;
	queryString += '&serviceQuantity=' + document.getElementById( "service_" + serviceItemUid ).value;
	queryString += '&fromSearchResults=' + fromSearchResults;
	makeAjaxCall( 'hotelResults.act', queryString, null, productUid, 'callbackUpdateServiceQuantity', '' );
}

function callbackUpdateServiceQuantity() {
	showMessage( this.errorMessage, this.errorCode, 'dataContent' );
	return true;
}

function showMoreHotels( productUid ) {
	var queryString = 'hr=5';
	queryString += '&uid=' + productUid;
	queryString += '&fromSearchResults=true';
	makeAjaxCall( 'hotelResults.act', queryString, null, productUid, 'callbackShowMoreHotels', '' );
}

function callbackShowMoreHotels() {
	showMessage( this.errorMessage, this.errorCode, 'dataContent' );
	return true;
}

function showLessHotels( productUid ) {
	var queryString = 'hr=6';
	queryString += '&uid=' + productUid;
	queryString += '&fromSearchResults=true';
	makeAjaxCall( 'hotelResults.act', queryString, null, productUid, 'callbackShowLessHotels', '' );
}

function callbackShowLessHotels() {
	showMessage( this.errorMessage, this.errorCode, 'dataContent' );
	return true;
}

function showMoreRoomCategories( roomUid, fromSearchResults ) {
	_itemUid = roomUid;
	var queryString = 'hr=7';
	queryString += '&uid=' + roomUid;
	queryString += '&fromSearchResults=' + fromSearchResults;
	makeAjaxCall( 'hotelResults.act', queryString, null, roomUid, 'callbackShowMoreRoomCategories', '' );
}

function callbackShowMoreRoomCategories() {
	showMessage( this.errorMessage, this.errorCode, 'dataContent' );
	if( this.errorCode == null || this.errorCode == undefined ) {
		expandSubCategoriesOfRoom( _itemUid );
		_itemUid = null;
	}
	return true;
}

function showLessRoomCategories( roomUid, fromSearchResults ) {
	_itemUid = roomUid;
	var queryString = 'hr=8';
	queryString += '&uid=' + roomUid;
	queryString += '&fromSearchResults=' + fromSearchResults;
	makeAjaxCall( 'hotelResults.act', queryString, null, roomUid, 'callbackShowLessRoomCategories', '' );
}

function callbackShowLessRoomCategories() {
	showMessage( this.errorMessage, this.errorCode, 'dataContent' );
	if( this.errorCode == null || this.errorCode == undefined ) {
		expandSubCategoriesOfRoom( _itemUid );
		_itemUid = null;
	}
	return true;
}

function displayItineraryRemarks( itineraryCode ) {
	var itineraryRemarksDivContainer = document.getElementById( 'itineraryRemarksDivContainer' );
	if( isNull( itineraryRemarksDivContainer ) ) {
		itineraryRemarksDivContainer = createPopupDiv('itineraryRemarksDivContainer', 0, 0, 450, 200, false, true, 'popupDivSmall tal');
	}

	var queryString = 'hr=15';
	queryString += '&itineraryCode=' + itineraryCode;
	makeAjaxCall( 'hotelResults.act', queryString, null, 'itineraryRemarksDivContainer', 'callbackDisplayItineraryRemarks', '' );
}

function callbackDisplayItineraryRemarks() {
	showMessage( this.errorMessage, this.errorCode, 'dataContent' );
	showBlock( 'itineraryRemarksDivContainer' );
	positionBlockCentrally( 'itineraryRemarksDivContainer' );	
	disableElement( 'dataContent', true );
	return true;
}

/* function to check availability calendar.*/
function loadAllotmentCalendar( itemUid ) {
	var queryString = 'hr=16';
	queryString += '&uid=' + itemUid;
	_itemUid = itemUid;
	makeAjaxCall( 'hotelResults.act', queryString, null, 'dataContent', 'callbackLoadAllotmentCalendar', '' );
}

function callbackLoadAllotmentCalendar(allotmentAvailability ) {
	if( showMessage(this.errorMessage, this.errorCode, 'dataContent' ) ) {
		return false;
	} else {
		allotmentAvailability = "(" + allotmentAvailability + ")";
		var allotmentInfoJSON = eval( allotmentAvailability );
		var allotmentJSONArray = allotmentInfoJSON.allotments;
		var disabledDateRanges = getDisabledDateRanges( allotmentInfoJSON.travelDateRanges );
		var numberOfAllotments = allotmentJSONArray.length;
		var dayAllotments = new Array();
		var fieldName = "cal_" + _itemUid;
		
		for( var index = 0 ; index < numberOfAllotments ; index++ ) {
			dayAllotments[ index ] = new DayAllotment( new Date( allotmentJSONArray[index].date ), allotmentJSONArray[index].status ); 
		}
		var checkinDate = new Date( allotmentInfoJSON.checkinDate );
		var checkoutDate = new Date( allotmentInfoJSON.checkoutDate );
		var specialDates = new Array();
		while( checkinDate <= checkoutDate ) {
			var date = new Date( checkinDate );
			specialDates[ date ] = date;
			checkinDate = addDays( checkinDate, 1 );
		}
		createAllotmentCalendar( fieldName, '','', new Date( allotmentInfoJSON.startDate ), 1, dayAllotments, allotmentInfoJSON.nights, allotmentInfoJSON.productUid, disabledDateRanges, specialDates );
		disableElement( 'dataContent', true );
	}
	return true;
}

function selectHotelItem( productUid, hotelItemUid, fromSearchResults, targetActivity) {
	window.clearTimeout( _tickingPriceTicker );
	
	var queryString = 'hr=19';	
	queryString += '&selectedHotelItemUid=' + hotelItemUid + '&fromSearchResults=' + fromSearchResults;
	disableElement( 'dataContent', true );
	if(fromSearchResults) {
		var productSummaryInvokeInfo = getLoadProductSummaryInvokeInfo(targetActivity, productUid );
		makeMultiAjaxCall(new Array(
				new AsynchronousMultiRequestItem('hotelResults.act', queryString, null, productUid, "callbackSelectHotelItem"),
				new AsynchronousMultiRequestItem(productSummaryInvokeInfo[0], productSummaryInvokeInfo[1], null, productSummaryInvokeInfo[2], productSummaryInvokeInfo[3])
			   ), true);
	}else {
		makeAjaxCallWithWaitingDiv( 'hotelResults.act', queryString, null, productUid, 'callbackSelectHotelItem');
	}
}

function callbackSelectHotelItem() {
	disableElement( 'dataContent', false );
	showMessage( this.errorMessage, this.errorCode, 'dataContent' );	
	return true;
}

function expandSubCategoriesOfRoom( roomUid ) {
	document.getElementById( "subCategoriesOfRoom_" + roomUid ).style.display = "block";
	document.getElementById( "expandCollapseRoomLink_" + roomUid ).innerHTML = "[-]";
}

function expandCollapseSubCategoriesOfRoom( roomUid ) {
	var expandCollapseRoomLink = document.getElementById( "expandCollapseRoomLink_" + roomUid );
	var subCategoriesOfRoomDiv = document.getElementById( "subCategoriesOfRoom_" + roomUid );
	if( subCategoriesOfRoomDiv.style.display == "block" ) {
		subCategoriesOfRoomDiv.style.display = "none";
		expandCollapseRoomLink.innerHTML = "[+]";
	} else {
		subCategoriesOfRoomDiv.style.display = "block";
		expandCollapseRoomLink.innerHTML = "[-]";
	}
}
/*******************************car results section**************************************/
function populateCarTransfers( productUid, cityCounter, totalCities ) {
	var queryString = 'trr=4';
	queryString += '&uid=' + productUid;
	queryString += '&displayCarFirst=true' ;
	queryString += '&cityCounter='+cityCounter;
	queryString += '&totalCities='+totalCities;
	//Make Ajax call with '/vp/booking/searchCars/<destinationCode>/<regionCode>/package/<packageId>' as the description to be passed into Google Analytics
	var trackingText = '/vp/booking/searchCars/' + _destinationCode + '/' + _regionCode + '/package/' + _packageId; 
	makeAjaxCall( 'transferResults.act', queryString, null, 'rightContent', 'callbackPopulateCarTransfers', trackingText );
}

function callbackPopulateCarTransfers( message, errorCode ) {
	showMessage( message, errorCode, 'dataContent' );	
	return true;
}

function changeCarCategoryItem( carCategoryItemUid, cityUid, displayCarFirst ) {
	window.clearTimeout( _tickingPriceTicker );
	var queryString = 'trr=9';
	queryString += '&uid=' + carCategoryItemUid;
	queryString += '&displayCarFirst=' + displayCarFirst;
	disableElement( 'dataContent', true );
	makeAjaxCallWithWaitingDiv( 'transferResults.act', queryString, null, cityUid, 'callbackChangeCarCategoryItem' );
}

function callbackChangeCarCategoryItem( message, errorCode ) {
	disableElement( 'dataContent', false );
	showMessage( message, errorCode, 'dataContent' );
	return true;
}

function changeCarAgencyItem( cityUid, agencyDivId, displayCarFirst ) {
	window.clearTimeout( _tickingPriceTicker );
	var queryString = 'trr=24';
	var uid = document.getElementById( agencyDivId ).value;
	
	queryString += '&uid=' + uid;
	queryString += '&displayCarFirst=' + displayCarFirst;
	makeAjaxCall( 'transferResults.act', queryString, null, cityUid, 'callbackChangeCarAgencyItem', '' );
}

function callbackChangeCarAgencyItem( message, errorCode ) {
	showMessage( message, errorCode, 'dataContent' );
	return true;
}

function clearCarSelection() {
	var carSelectionTable = document.getElementById( "carSelectionTable" );
	carSelectionTable.className = "tableSelection";
	var carSelectionRows = carSelectionTable.getElementsByTagName( "TR" );
	
	var carSelectionColumns = carSelectionRows[ 0 ].getElementsByTagName( "TD" );
	modifyClassName(carSelectionColumns[0],"+tableSelectionTitleHover");
	for( var j = 1 ; j < carSelectionColumns.length ; j++ ) {
		carSelectionColumns[ j ].className = "tableSelectionTitle";
	}
	
	for( var i = 1 ; i < carSelectionRows.length ; i++ ) {
		carSelectionRows[ i ].className = "";
		carSelectionColumns = carSelectionRows[ i ].getElementsByTagName( "TD" );
		modifyClassName(carSelectionColumns[ 0 ], "+carCategory -tableSelectionTitleHover");
		for( var j = 1 ; j < carSelectionColumns.length ; j++ ) {
			modifyClassName(carSelectionColumns[ j ], "+tableSelectionTD -tableSelectionTDHover -tableSelectionTRHover");
		}
	}
}

function highlightCarSelection( rowIndex, columnIndex ) {
	clearCarSelection();
	var carSelectionRows = document.getElementById( "carSelectionTable" ).getElementsByTagName( "TR" );
	
	var carSelectionColumn = document.getElementById( "carSelectionColumn_0_" + columnIndex ); 
	modifyClassName(carSelectionColumn, "+tableSelectionTitleHover -tableSelectionTitle");
	
	for( var i = 1 ; i < carSelectionRows.length ; i++ ) {
		carSelectionColumn = document.getElementById( "carSelectionColumn_" + i + "_" + columnIndex );
		modifyClassName(carSelectionColumn, "+tableSelectionTRHover -tableSelectionTDHover");
	}

	modifyClassName(document.getElementById( "carSelectionRow_" + rowIndex ), "+tableSelectionTRHover");
	
	carSelectionColumn = document.getElementById( "carSelectionColumn_" + rowIndex + "_" + columnIndex );
	modifyClassName(carSelectionColumn, "+tableSelectionTDHover -tableSelectionTRHover -tableSelectionTD");
	
	carSelectionColumn = document.getElementById( "carSelectionColumn_" + rowIndex + "_0" );
	modifyClassName(carSelectionColumn, "+tableSelectionTitleHover -carCategory");
}
/*******************************transfer results section**************************************/
function populateAllTransfers( productUid, cityCounter, totalCities ) {
	var queryString = 'trr=4';
	queryString += '&uid=' + productUid;
	queryString += '&displayCarFirst=false' ;
	queryString += '&cityCounter='+cityCounter;
	queryString += '&totalCities='+totalCities;
	//Make Ajax call with '/vp/booking/searchTransportation/<destinationCode>/<regionCode>/package/<packageId>' as the description to be passed into Google Analytics
	var trackingText = '/vp/booking/searchTransportation/' + _destinationCode + '/' + _regionCode + '/package/' + _packageId; 
	makeAjaxCall( 'transferResults.act', queryString, null, 'rightContent', 'callbackPopulateAllTransfers', trackingText );
}

function callbackPopulateAllTransfers( message, errorCode ) {
	showMessage( message, errorCode, 'dataContent' );
	return true;
}

function populateTransfersForPickupPoint(cityUid, cityCounter, totalCities, showAdditionalTransfers) {
    var pickupPointList = document.getElementById("pickupPointList");
    if(pickupPointList) {
        var pickupPoint = pickupPointList.value;
        var actionCode = 20;
        if(showAdditionalTransfers == true) {
            actionCode = 21;
        }
        
        var queryString = 'trr=' + actionCode;
    	queryString += '&uid=' + cityUid + '&selectedPickupPoint=' + pickupPoint +'&cityCounter=' + cityCounter + '&totalCities=' + totalCities;
    	disableElement( 'dataContent', true );
    	makeAjaxCallWithWaitingDiv( 'transferResults.act', queryString, null, 'rightContent', 'callbackPopulateTransfersForPickupPoint');  
    }	 
}

function callbackPopulateTransfersForPickupPoint( message, errorCode ) {
   disableElement( 'dataContent', false );
   showMessage( message, errorCode, 'dataContent' );
   return true; 
}

function populateAllTransportation( cityUid ) {
	var queryString = 'trr=12';
	queryString += '&uid=' + cityUid;
	queryString += '&displayCarFirst=false' ;
	makeAjaxCall( 'transferResults.act', queryString, null, 'rightContent', 'callbackPopulateAllTransportation', '' );
}

function callbackPopulateAllTransportation( message, errorCode ) {
	showMessage( message, errorCode, 'dataContent' );
	return true;
}

function changeTransferItem( transferDayTourId, cityUid, displayCarFirst ) {
	window.clearTimeout( _tickingPriceTicker );
	var queryString = 'trr=3';
	queryString += '&uid=' + cityUid;
	queryString += '&transferDayTourId=' + transferDayTourId;
	queryString += '&displayCarFirst=' + displayCarFirst;
	makeAjaxCall( 'transferResults.act', queryString, null, cityUid, 'callbackChangeTransferItem', '' );
}

function callbackChangeTransferItem( message, errorCode ) {
	showMessage( message, errorCode, 'dataContent' );
	return true;
}

function clearItemSelection( cityUid, displayCarFirst ) {
	window.clearTimeout( _tickingPriceTicker );
	var queryString = 'trr=5';
	queryString += '&uid=' + cityUid;
	queryString += '&displayCarFirst=' + displayCarFirst;
	makeAjaxCall( 'transferResults.act', queryString, null, cityUid, 'callbackClearItemSelection', '' );
}

function callbackClearItemSelection( message, errorCode ) {
	showMessage( message, errorCode, 'dataContent' );
	return true;
}

function reLoadTransportation( cityUid, displayCarFirst, previousPickupTime, previousDropoffTime ) {
	clearErrorElements();
	var pickupTimeField = document.getElementById( "pickupTime" );
	var dropoffTimeField = document.getElementById( "dropoffTime" );
	if( isNull( pickupTimeField ) || isNull( dropoffTimeField ) ) {
		return false;
	}
	var pickupTime = pickupTimeField.value;
	var dropoffTime = dropoffTimeField.value;

	if( pickupTime != "-1" && dropoffTime != "-1" ){

		if( showConfirmMessageForCar( pickupTime, dropoffTime ) ){ 
			var queryString = 'trr=16';
			queryString += '&uid=' + cityUid;
			queryString += '&pickupTime=' + pickupTime;
			queryString += '&dropoffTime=' + dropoffTime;
			queryString += '&displayCarFirst=' + displayCarFirst;
			disableElement( 'dataContent', true );
			makeAjaxCallWithWaitingDiv( 'transferResults.act', queryString, null, cityUid, 'callbackReLoadTransportation' );
		} else {
			pickupTimeField.value = previousPickupTime;
			dropoffTimeField.value = previousDropoffTime;
		}
	} else {
		showErrorMessage( 'Please select a pick-up/drop-off time', 'dataContent' );
		return false;
	}
}

function callbackReLoadTransportation( message, errorCode ) {
	disableElement( 'dataContent', false );
	showMessage( message, errorCode, 'dataContent' );
	return true;
}

/* get the number of hours by passing time. */
function getHoursFromTime( time ) {
	var addTwelveHoursClock = 0;
	var isAM = true;
	var index =0;
	if( time.indexOf( "PM" ) != -1 ){
		isAM = false;
		index = time.indexOf( "PM" );
		addTwelveHoursClock = 12;
	}else if( time.indexOf( "AM" ) != -1 ){
		isAM = true
		index = time.indexOf( "AM" );
		addTwelveHoursClock = 0;
	}
	time = time.substring( 0 , index )
	var timeArray = time.split( ":" );
	var hours = parseInt( timeArray[ 0 ], 10 );
	if( hours == 12 ){
		hours = 00;
	}
	return ( (hours + addTwelveHoursClock) );
}

function applyTranspotationChanges(  cityUid, cityCounter, totalCities ) {
	window.clearTimeout( _tickingPriceTicker );
	var queryString = 'trr=13';
	_cityUid = cityUid;	
	queryString += '&uid=' + cityUid;
	queryString += '&cityCounter=' + cityCounter;
	queryString += '&totalCities=' + totalCities;
	makeAjaxCall( 'transferResults.act', queryString, null, 'rightContent', 'callbackApplyTranspotationChanges', '' );
}

function callbackApplyTranspotationChanges( message, errorCode 	) {
	showMessage( message, errorCode, 'dataContent' );
	loadTransportationTripSummary( _cityUid, false );
	return true;
}

function ignoreTranspotationChanges( cityUid, cityCounter, totalCities  ) {
	window.clearTimeout( _tickingPriceTicker );
	var queryString = 'trr=14';
	queryString += '&uid=' + cityUid;
	queryString += '&cityCounter=' + cityCounter;
	queryString += '&totalCities=' + totalCities;
	_cityUid = cityUid;
	//Make Ajax call with '/vp/booking/searchOptions/<destinationCode>/<regionCode>/<packageId>' as the description to be passed into Google Analytics
	var trackingText = '/vp/booking/searchOptions/' + _destinationCode + '/' + _regionCode + '/package/' + _packageId; 
	makeAjaxCall( 'transferResults.act', queryString, null, 'rightContent', 'callbackIgnoreTranspotationChanges', trackingText );
}

function callbackIgnoreTranspotationChanges( message, errorCode ) {
	showMessage( message, errorCode, 'dataContent' );	
	loadTransportationTripSummary( _cityUid , false );
	return true;
}

function changeArrivalGreetingTransferItem( transferItemUid,cityUid, displayCarFirst ) {
	window.clearTimeout( _tickingPriceTicker );
	var queryString = 'trr=18';
	queryString += '&uid=' + transferItemUid;
	queryString += '&displayCarFirst=' + displayCarFirst;
	makeAjaxCall( 'transferResults.act', queryString, null, cityUid, 'callbackChangeArrivalGreetingTransferItem', '' );
}

function callbackChangeArrivalGreetingTransferItem( message, errorCode ) {
	showMessage( message, errorCode, 'dataContent' );
	return true;
}

function clearArrivalGreetingItemSelection( cityUid, displayCarFirst ) {
	window.clearTimeout( _tickingPriceTicker );
	var queryString = 'trr=19';
	queryString += '&uid=' + cityUid;
	queryString += '&displayCarFirst=' + displayCarFirst;
	makeAjaxCall( 'transferResults.act', queryString, null, cityUid, 'callbackClearArrivalGreetingItemSelection', '' );
}

function callbackClearArrivalGreetingItemSelection( message, errorCode ) {
	showMessage( message, errorCode, 'dataContent' );
	return true;
}
/**********************************tour results section*******************************************/
function populateAllTours( cityUid, cityCounter, totalCities  ) {
	_cityUid = cityUid;
	var queryString = 'tr=1';
	queryString += '&uid=' + cityUid;
	queryString += '&cityCounter='+cityCounter;
	queryString += '&totalCities='+totalCities;
	//Make Ajax call with '/vp/booking/searchSightseeing/<destinationCode>/<regionCode>/package/<packageId>' as the description to be passed into Google Analytics
	var trackingText = '/vp/booking/searchSightseeing/' + _destinationCode + '/' + _regionCode + '/package/' + _packageId; 
	makeAjaxCall( 'tourResults.act', queryString, null, 'rightContent', 'callbackPopulateAllTours', trackingText);
}

function callbackPopulateAllTours( message, errorCode ) {
	showMessage( message, errorCode, 'dataContent' );
	loadTourSummaryBlock( _cityUid, true );
	return true;
}

function includeExcludeTourItem( tourItemIndex, tourItemId, numberOfMandatoryTours, cityUid, cityCounter, totalCities ) {
	window.clearTimeout( _tickingPriceTicker );
	clearErrorElements();
	var tourItemSelectionField = document.getElementById( "tourItemSelection_" + tourItemIndex );
	var tourDateSelectionField = document.getElementById( "tourDateSelection_" + tourItemIndex );
	if( tourItemSelectionField.checked ) {
		while( tourDateSelectionField.value == "" ) {
			tourDateSelectionField.selectedIndex = tourDateSelectionField.selectedIndex + 1;
		}
		if( tourDateSelectionField.value == "" ) {
			showErrorMessage( 'Please pick a date for sightseeing item #' + ( tourItemIndex + 1 ), 'dataContent', ( 'tourDateSelection_' + tourItemIndex ), '10px solid #7f9db9' );
			return false;
		}
		disableElement( 'dataContent', true );

		var queryString = 'tr=7';
		queryString += '&uid=' + tourDateSelectionField.value;
		queryString += '&numberOfMandatoryTours=' + numberOfMandatoryTours;
		queryString += '&cityCounter=' + cityCounter;
		queryString += '&totalCities=' + totalCities;

		var asynchronousRequest = new AsynchronousRequest();
		asynchronousRequest.url = _webLoc + '/tourResults.act';
		asynchronousRequest.queryString = queryString;
		asynchronousRequest.useAjax = true;
		asynchronousRequest.target = cityUid;
		asynchronousRequest.callbackFunctionName = 'callbackIncludeExcludeTourItem';

		var splashScreenRequest = new SplashScreenRequest();
		splashScreenRequest.splashScreenText = "Please Wait...";
		asynchronousRequest.splashScreenRequest = splashScreenRequest;
		asynchronousRequest.splashScreenDisplayFunctionName = "displaySearchingPopup";
		asynchronousRequest.splashScreenHideFunctionName = "hideSearchingPopup";

		makeAjaxCallWithRequest( asynchronousRequest, '' );
	} else {
		disableElement( 'dataContent', true );

		var queryString = 'tr=8';
		queryString += '&uid=' + cityUid;
		queryString += '&tourItemId=' + tourItemId;
		queryString += '&numberOfMandatoryTours=' + numberOfMandatoryTours;
		queryString += '&cityCounter=' + cityCounter;
		queryString += '&totalCities=' + totalCities;

		var asynchronousRequest = new AsynchronousRequest();
		asynchronousRequest.url = _webLoc + '/tourResults.act';
		asynchronousRequest.queryString = queryString;
		asynchronousRequest.useAjax = true;
		asynchronousRequest.target = cityUid;
		asynchronousRequest.callbackFunctionName = 'callbackIncludeExcludeTourItem';

		var splashScreenRequest = new SplashScreenRequest();
		splashScreenRequest.splashScreenText = "Please Wait...";
		asynchronousRequest.splashScreenRequest = splashScreenRequest;
		asynchronousRequest.splashScreenDisplayFunctionName = "displaySearchingPopup";
		asynchronousRequest.splashScreenHideFunctionName = "hideSearchingPopup";

		makeAjaxCallWithRequest( asynchronousRequest, '' );
	}
	return true;
}

function callbackIncludeExcludeTourItem( message, errorCode ) {
	disableElement( 'dataContent', false );
	showMessage( message, errorCode, 'dataContent' );
	return true;
}

function updateTourItemDate( tourItemIndex, tourItemId, numberOfMandatoryTours, cityUid, cityCounter, totalCities ) {
	window.clearTimeout( _tickingPriceTicker );
	clearErrorElements();
	document.getElementById( "tourItemSelection_" + tourItemIndex ).checked = true;
	var tourDateSelectionField = document.getElementById( "tourDateSelection_" + tourItemIndex );
	if( tourDateSelectionField.value != "" ) {
		disableElement( 'dataContent', true );

		var queryString = 'tr=9';
		queryString += '&uid=' + tourDateSelectionField.value;
		queryString += '&tourItemId=' + tourItemId;
		queryString += '&numberOfMandatoryTours=' + numberOfMandatoryTours;
		queryString += '&cityCounter=' + cityCounter;
		queryString += '&totalCities=' + totalCities;

		var asynchronousRequest = new AsynchronousRequest();
		asynchronousRequest.url = _webLoc + '/tourResults.act';
		asynchronousRequest.queryString = queryString;
		asynchronousRequest.useAjax = true;
		asynchronousRequest.target = cityUid;
		asynchronousRequest.callbackFunctionName = 'callbackIncludeExcludeTourItem';

		var splashScreenRequest = new SplashScreenRequest();
		splashScreenRequest.splashScreenText = "Please Wait...";
		asynchronousRequest.splashScreenRequest = splashScreenRequest;
		asynchronousRequest.splashScreenDisplayFunctionName = "displaySearchingPopup";
		asynchronousRequest.splashScreenHideFunctionName = "hideSearchingPopup";

		makeAjaxCallWithRequest( asynchronousRequest, '' );
	} else {
		disableElement( 'dataContent', true );

		var queryString = 'tr=8';
		queryString += '&uid=' + cityUid;
		queryString += '&tourItemId=' + tourItemId;
		queryString += '&numberOfMandatoryTours=' + numberOfMandatoryTours;
		queryString += '&cityCounter=' + cityCounter;
		queryString += '&totalCities=' + totalCities;

		var asynchronousRequest = new AsynchronousRequest();
		asynchronousRequest.url = _webLoc + '/tourResults.act';
		asynchronousRequest.queryString = queryString;
		asynchronousRequest.useAjax = true;
		asynchronousRequest.target = cityUid;
		asynchronousRequest.callbackFunctionName = 'callbackIncludeExcludeTourItem';

		var splashScreenRequest = new SplashScreenRequest();
		splashScreenRequest.splashScreenText = "Please Wait...";
		asynchronousRequest.splashScreenRequest = splashScreenRequest;
		asynchronousRequest.splashScreenDisplayFunctionName = "displaySearchingPopup";
		asynchronousRequest.splashScreenHideFunctionName = "hideSearchingPopup";

		makeAjaxCallWithRequest( asynchronousRequest, '' );
	}
}

function applyTourChanges( cityUid, numberOfMandatoryTours, cityCounter, totalCities  ) {
	clearErrorElements();
	disableElement( 'dataContent', true );

	var numberOfTourItems = parseInt( document.getElementById( "numberOfTourItems" ).value );
	var numberOfTourItemsSelected = 0;
	for( var tourItemIndex = 0 ; tourItemIndex < numberOfTourItems ; tourItemIndex++ ) {
		if( document.getElementById( "tourItemSelection_" + tourItemIndex ).checked ) {
			if( document.getElementById( "tourDateSelection_" + tourItemIndex ).value == "" ) {
				showErrorMessage( 'Please pick a date for sightseeing item #' + ( tourItemIndex + 1 ), 'dataContent', ( 'tourDateSelection_' + tourItemIndex ), '10px solid #7f9db9' );
				return false;
			}
			numberOfTourItemsSelected++;
		}
	}

	if( numberOfTourItemsSelected < numberOfMandatoryTours ) {
		showErrorMessage( 'This package requires a selection of at least ' + numberOfMandatoryTours + ' sightseeing item(s)', 'dataContent' );
		return false;
	}
	window.scroll( 0, 0 );
	_cityUid = cityUid;
	window.clearTimeout( _tickingPriceTicker );
	var queryString = 'tr=5';
	queryString += '&uid=' + cityUid;
	queryString += '&cityCounter=' + cityCounter;
	queryString += '&totalCities=' + totalCities;
	makeAjaxCall( 'tourResults.act', queryString, null, 'rightContent', 'callbackApplyTourChanges', '' );
}

function callbackApplyTourChanges( message, errorCode ) {
	disableElement( 'dataContent', false );

	showMessage( message, errorCode, 'dataContent' );
	loadTourSummaryBlock( _cityUid, false );
	return true;
}

function ignoreTourChanges( cityUid, cityCounter, totalCities ) {
	window.scroll( 0, 0 );
	window.clearTimeout( _tickingPriceTicker );
	disableElement( 'dataContent', true );

	var queryString = 'tr=6';
	_cityUid = cityUid;
	queryString += '&uid=' + cityUid;
	queryString += '&cityCounter='+cityCounter;
	queryString += '&totalCities='+totalCities;
	//Make Ajax call with '/vp/booking/searchOptions/<destinationCode>/<regionCode>/<packageId>' as the description to be passed into Google Analytics
	var trackingText = '/vp/booking/searchOptions/' + _destinationCode + '/' + _regionCode + '/package/' + _packageId; 
	makeAjaxCall( 'tourResults.act', queryString, null, 'rightContent', 'callbackIgnoreTourChanges', trackingText );	
}

function callbackIgnoreTourChanges( message, errorCode ) {
	disableElement( 'dataContent', false );

	showMessage( message, errorCode, 'dataContent' );
	loadTourSummaryBlock( _cityUid, false );
	return true;
}

function sortToursByPrice( cityUid ) {
	var queryString = 'tr=10';
	queryString += '&uid=' + cityUid;
	makeAjaxCall( 'tourResults.act', queryString, null, cityUid, 'callbackSortToursByPrice', '' );
}

function callbackSortToursByPrice( message, errorCode ) {
	showMessage( message, errorCode, 'dataContent' );
	return true;
}

function sortToursByDescription( cityUid ) {
	var queryString = 'tr=11';
	queryString += '&uid=' + cityUid;
	makeAjaxCall( 'tourResults.act', queryString, null, cityUid, 'callbackToursByDescription', '' );
}

function callbackToursByDescription( message, errorCode ) {
	showMessage( message, errorCode, 'dataContent' );
	return true;
}
/***********************************package summary(lef content) section ***************************************/
function loadTripSummary() {
	var queryString = 'lc=1';
	if( ( _productUid != null ) && ( _productUid != undefined ) && ( _productUid != "" ) ) {
		queryString += "&highlightedProductUid=" + _productUid;
	}
	makeAjaxCall( 'leftContent.act', queryString, null, 'leftContent', 'callbackLoadTripSummary', '' );
}

function callbackLoadTripSummary() {
	showMessage( this.errorMessage, this.errorCode, 'dataContent' );
	_productUid = "";
	_targetAct = "";
	_fromSearchResults = "";
	return true;
}

function getLoadProductSummaryInvokeInfo( targetActivity, productUid ) {
	var targetAct ="";
	var queryString = targetActivity;	 
	if( targetActivity.indexOf( "fr" ) != -1 ) {
		targetAct = "flightResults.act";
	} else if( targetActivity.indexOf( "hr" ) != -1 ) {
		targetAct = "hotelResults.act";
	} 
	queryString += '&uid=' + productUid;
	queryString += '&highlightedProduct=false';
	return [targetAct, queryString, "summary_" + productUid, 'callbackLoadProductSummary'];
}

function loadProductSummary( targetActivity, productUid ) {
	var invokeInfo = getLoadProductSummaryInvokeInfo(targetActivity, productUid );
	makeAjaxCall( invokeInfo[0], invokeInfo[1], null, invokeInfo[2], invokeInfo[3], '' );
}

function callbackLoadProductSummary() {
	showMessage( this.errorMessage, this.errorCode, 'dataContent' );
	_productUid = "";
	_targetAct = "";
	_fromSearchResults = "";
	return true;
}

function loadTransportationTripSummary( cityUid, highlightedProduct ) {
	var queryString = 'trr=15';
	queryString += '&uid=' + cityUid;
	queryString += '&highlightedProduct='+highlightedProduct;
	makeAjaxCall( 'transferResults.act', queryString, null, 'transportationSummary_' + cityUid, 'callbackLoadTransportationTripSummary', '' );
}

function callbackLoadTransportationTripSummary( message, errorCode ) {
	showMessage( message, errorCode, 'dataContent' );
	_cityUid = "";
	return true;
}

function loadFlightSummaryBlock( productUid ){
	var queryString = 'fr=12';
	queryString += '&uid=' + productUid;
	queryString += '&highlightedProduct=true';
	makeAjaxCall( 'flightResults.act', queryString, null, "summary_" + productUid, 'callbackLoadFlightSummaryBlock', '' );
}

function callbackLoadFlightSummaryBlock() {
	showMessage( this.errorMessage, this.errorCode, 'dataContent' );
	return true;
}

function loadHotelSummaryBlock( productUid ){
	var queryString = 'hr=13';
	queryString += '&uid=' + productUid;
	queryString += '&highlightedProduct=true';
	makeAjaxCall( 'hotelResults.act', queryString, null, "summary_" + productUid, 'callbackLoadHotelSummaryBlock', '' );
}

function callbackLoadHotelSummaryBlock() {
	showMessage( this.errorMessage, this.errorCode, 'dataContent' );
	return true;
}

function loadTourSummaryBlock( cityUid, isHighlightBlock ){
	var queryString = 'tr=4';
	queryString += '&uid=' + cityUid;	
	queryString += '&highlightedProduct=' + isHighlightBlock;	
	makeAjaxCall( 'tourResults.act', queryString, null, "tour_" + cityUid, 'callbackLoadTourSummaryBlock', '' );
}

function callbackLoadTourSummaryBlock( message, errorCode ) {
	showMessage( message, errorCode, 'dataContent' );
	_cityUid = "";
	return true;
}

function loadFerrySummaryBlock( ferryProductUid, isHighlightBlock ){
	var queryString = 'fer=5';
	queryString += '&uid=' + ferryProductUid;	
	queryString += '&highlightedProduct=' + isHighlightBlock;	
	makeAjaxCall( 'ferryResults.act', queryString, null, "summary_" + ferryProductUid, 'callbackLoadFerrySummaryBlock', '' );
}

function callbackLoadFerrySummaryBlock() {
	showMessage( this.errorMessage, this.errorCode, 'dataContent' );
	_productUid = "";
	return true;
}

function loadRailSummaryBlock( railProductUid, isHighlightBlock ){
	var queryString = 'rr=5';
	queryString += '&uid=' + railProductUid;
	queryString += '&highlightedProduct=' + isHighlightBlock;	
	makeAjaxCall( 'railResults.act', queryString, null, "summary_" + railProductUid, 'callbackLoadRailSummaryBlock', '' );
}

function callbackLoadRailSummaryBlock( message, errorCode ) {
	showMessage( message, errorCode, 'dataContent' );
	_productUid = "";
	return true;
}
/************************************trip protection section**************************/
function loadTripProtectionPopup() {
	if( !isNull( _sightseeingDates ) ) {
		var multipleSightseeingsSelectedOnSameDate = false;
		for( var sightseeingDateIndex1 = 0 ; sightseeingDateIndex1 < _sightseeingDates.length ; sightseeingDateIndex1++ ) {
			for( var sightseeingDateIndex2 = ( sightseeingDateIndex1 + 1 ) ; sightseeingDateIndex2 < _sightseeingDates.length ; sightseeingDateIndex2++ ) {
				if( _sightseeingDates[ sightseeingDateIndex1 ] == _sightseeingDates[ sightseeingDateIndex2 ] ) {
					multipleSightseeingsSelectedOnSameDate = true;
					break;
				}
			}
			if( multipleSightseeingsSelectedOnSameDate ) {
				break;
			}
		}
		if( multipleSightseeingsSelectedOnSameDate && !( confirm( "You have selected multiple Sightseeing Tours for the same date. Are you sure you want to proceed with this?" ) ) ) {
				return false;
		}
	}

	// create pop up div for search criteria.	
	var tripProtectionPopupDivContainer = document.getElementById( 'tripProtectionPopupDivContainer' ); 
	if( isNull( tripProtectionPopupDivContainer ) ) {
		tripProtectionPopupDivContainer = createPopupDiv('tripProtectionPopupDivContainer', 0, 0, 700, 200, false, true,  "tal popupDivBig");
		tripProtectionPopupDivContainer.onkeypress = function( event ) { onKeyDownOnTripProtectionPopup(event) };
		//tripProtectionPopupDivContainer = document.createElement('DIV');
		//tripProtectionPopupDivContainer.id = 'tripProtectionPopupDivContainer';
		//tripProtectionPopupDivContainer.onmouseover = function( event ) { setDragEvent( 'tripProtectionPopupDivContainer', event ) };
		//document.body.insertBefore( tripProtectionPopupDivContainer, document.body.firstChild );
	}
	
	//tripProtectionPopupDivContainer.style.position = "absolute";
	//tripProtectionPopupDivContainer.style.width = "700";
	//tripProtectionPopupDivContainer.style.zIndex = "200";
	//tripProtectionPopupDivContainer.innerHTML = '';
	
	var queryString = 'sr=5';
	//while loading trip protection popup,by default trip protection is added. 	
	//Make Ajax call with '/vp/booking/searchIns/<destinationCode>/<regionCode>/package/<packageId>' as the description to be passed into Google Analytics
	var trackingText = '/vp/booking/searchIns/' + _destinationCode + '/' + _regionCode + '/package/' + _packageId; 
	makeAjaxCall( 'searchResults.act', queryString, null, 'tripProtectionPopupDivContainer', 'callbackLoadTripProtectionPopup', trackingText );
}

function callbackLoadTripProtectionPopup( message, errorCode ) {
	showMessage(message, errorCode, 'tripProtectionPopupDivContainer');
	showBlock( 'tripProtectionPopupDivContainer' );
	positionBlockCentrally( 'tripProtectionPopupDivContainer' );	
	disableElement( 'dataContent', true );
	return true;
}

function toggleTripProtection( isRemoveTripProtection ) {
	window.clearTimeout( _tickingPriceTicker );
	var addTripProtectionCheckBox = document.getElementById( "addTripProtectionCheckbox" );
	var declineTripProtectionCheckBox = document.getElementById( "declineTripProtectionCheckbox" );
	var queryString = 'sr=7';

	if(isRemoveTripProtection) {
		if(addTripProtectionCheckBox) {
			addTripProtectionCheckBox.checked = false;
		}
		if(declineTripProtectionCheckBox) {
			declineTripProtectionCheckBox.checked = true;
		}
	}
	else {
		if(addTripProtectionCheckBox) {
			addTripProtectionCheckBox.checked = true;
		}
		if(declineTripProtectionCheckBox) {
			declineTripProtectionCheckBox.checked = false;
		}

		queryString = 'sr=6'
	}
	var bookingPrice = parseFloat( document.getElementById( "totalPackagePrice" ).value );
	makeAjaxCall( 'searchResults.act', queryString, null, null, 'callbackToggleTripProtection', '' );
}

function callbackToggleTripProtection( message, errorCode, packagePrice ) {
	if( message != "" ) {
		showMessage( message, errorCode, 'tripProtectionPopupDivContainer' );
	} else {
		updatePackagePrice( parseFloat( packagePrice ).toFixed( 2 ), 'totalPackagePriceDisplayTripProtection', 'totalPackagePriceTripProtection');
	}
	return true;
}

function showHideContinueButton( validToBook ) {
	if( !( validToBook ) ) {
		document.getElementById( "continueButton_1" ).style.display = 'none';
		document.getElementById( "continueButton_2" ).style.display = 'none';
	}
}

function loadOnTripProtectionPopup(){
	var tripProtectionPopupDiv = document.getElementById( "tripProtectionPopupDiv" )
	if ( tripProtectionPopupDiv != undefined ){
		if(!isIE() ) {
			tripProtectionPopupDiv.style.overflow = "auto";
			tripProtectionPopupDiv.style.outline = "none";
		}
		tripProtectionPopupDiv.focus();
	}
}
/************************************ferry results section**************************/
function chooseDifferentFerry( ferryProductUid ) {
	var queryString = 'fer=2';
	queryString += '&uid=' + ferryProductUid;
	makeAjaxCall( 'ferryResults.act', queryString, null, 'rightContent', 'callbackChooseDifferentFerry', '' );
}

function callbackChooseDifferentFerry() {
	showMessage( this.errorMessage, this.errorCode, 'dataContent' );
	return true;
}

function applyFerryChanges(  ferryProductUid ) {
	window.clearTimeout( _tickingPriceTicker );
	var queryString = 'fer=6';
	_productUid = ferryProductUid;	
	queryString += '&uid=' + ferryProductUid;	
	makeAjaxCall( 'ferryResults.act', queryString, null, 'rightContent', 'callbackApplyFerryChanges', '' );
}

function callbackApplyFerryChanges() {
	showMessage( this.errorMessage, this.errorCode, 'dataContent' );
	loadFerrySummaryBlock( _productUid, false );
	return true;
}

function changeFerryItem( ferryItemUid, ferryProductUid ) {
	window.clearTimeout( _tickingPriceTicker );
	var queryString = 'fer=4';
	queryString += '&uid=' + ferryItemUid;
	makeAjaxCall( 'ferryResults.act', queryString, null, ferryProductUid, 'callbackChangeFerryItem', '' );
}

function callbackChangeFerryItem() {
	showMessage( this.errorMessage, this.errorCode, 'dataContent' );
	return true;
}

function ignoreFerryChanges( ferryProductUid ) {
	window.clearTimeout( _tickingPriceTicker );
	var queryString = 'fer=7';	
	_productUid = ferryProductUid;
	queryString += '&uid=' + ferryProductUid;
	//Make Ajax call with '/vp/booking/searchOptions/<destinationCode>/<regionCode>/<packageId>' as the description to be passed into Google Analytics
	var trackingText = '/vp/booking/searchOptions/' + _destinationCode + '/' + _regionCode + '/package/' + _packageId; 
	makeAjaxCall( 'ferryResults.act', queryString, null, 'rightContent', 'callbackIgnoreFerryChanges', trackingText );	
}

function callbackIgnoreFerryChanges() {
	showMessage( this.errorMessage, this.errorCode, 'dataContent' );
	loadFerrySummaryBlock( _productUid, false );
	return true;
}
/************************************rail results section**************************/
function chooseDifferentRail( railProductUid ) {
	var queryString = 'rr=2';
	queryString += '&uid=' + railProductUid;
	makeAjaxCall( 'railResults.act', queryString, null, 'rightContent', 'callbackChooseDifferentRail', '' );
}

function callbackChooseDifferentRail( message, errorCode ) {
	showMessage( message, errorCode, 'dataContent' );
	return true;
}

function applyRailChanges(  railProductUid ) {
	window.clearTimeout( _tickingPriceTicker );
	var queryString = 'rr=6';
	_productUid = railProductUid;	
	queryString += '&uid=' + railProductUid;
	makeAjaxCall( 'railResults.act', queryString, null, 'rightContent', 'callbackApplyRailChanges', '' );
}

function callbackApplyRailChanges( message, errorCode 	) {
	showMessage( message, errorCode, 'dataContent' );
	loadRailSummaryBlock( _productUid, false );
	return true;
}

function changeRailItem( railItemUid, railProductUid ) {
	window.clearTimeout( _tickingPriceTicker );
	var queryString = 'rr=4';
	queryString += '&uid=' + railItemUid;
	makeAjaxCall( 'railResults.act', queryString, null, railProductUid, 'callbackChangeRailItem', '' );
}

function callbackChangeRailItem( message, errorCode ) {
	showMessage( message, errorCode, 'dataContent' );
	return true;
}

function ignoreRailChanges( railProductUid ) {
	window.clearTimeout( _tickingPriceTicker );
	var queryString = 'rr=7';	
	_productUid = railProductUid;
	queryString += '&uid=' + railProductUid;
	//Make Ajax call with '/vp/booking/searchOptions/<destinationCode>/<regionCode>/<packageId>' as the description to be passed into Google Analytics
	var trackingText = '/vp/booking/searchOptions/' + _destinationCode + '/' + _regionCode + '/package/' + _packageId; 
	makeAjaxCall( 'railResults.act', queryString, null, 'rightContent', 'callbackIgnoreRailChanges', trackingText );	
}

function callbackIgnoreRailChanges( message, errorCode ) {
	showMessage( message, errorCode, 'dataContent' );
	loadRailSummaryBlock( _productUid, false );
	return true;
}

/* On change of pickup or drop off times from search results02 page for selected car. */
function reLoadSearchResults02( cityUid, productUid, cityCounter, totalCities, previousPickupTime, previousDropoffTime ) {
	window.clearTimeout( _tickingPriceTicker );
	clearErrorElements();
	var pickupTimeField = document.getElementById( "pickupTime" );
	var dropoffTimeField = document.getElementById( "dropoffTime" );
	if( isNull( pickupTimeField ) || isNull( dropoffTimeField ) ) {
		return false;
	}
	var pickupTime = pickupTimeField.value;
	var dropoffTime = dropoffTimeField.value;

	if( pickupTime != "-1" && dropoffTime != "-1" ){
		
		if( showConfirmMessageForCar( pickupTime, dropoffTime ) ){
			_cityUid = cityUid;
			var queryString = 'trr=25';
			queryString += '&uid=' + productUid;
			queryString += '&pickupTime=' + pickupTime;
			queryString += '&dropoffTime=' + dropoffTime;
			queryString += '&cityCounter='+cityCounter;
			queryString += '&totalCities='+totalCities;
			disableElement( 'dataContent', true );
			makeAjaxCallWithWaitingDiv( 'transferResults.act', queryString, null, 'rightContent', 'callbackReLoadSearchResults02' );
		} else {
			pickupTimeField.value = previousPickupTime;
			dropoffTimeField.value = previousDropoffTime;
		}
	} else {
		showErrorMessage( 'Please select a pick-up/drop-off time', 'dataContent' );
		return false;
	}
}

function showConfirmMessageForCar( pickupTime, dropoffTime ){
	var pickupHours = getHoursFromTime( pickupTime );
	var dropoffHours = getHoursFromTime( dropoffTime );
	var numberOfHours = dropoffHours - pickupHours;

	if( numberOfHours > HOURS_ALLOWED_WITHOUT_EXTRA_CHARGE ){
		return confirm( "The car company calculates a rental day as a 24-hour period. Selecting a return time that is later than your pick-up time will add a day to your rental and you will be charged accordingly. To avoid being charged for an extra day, select a return time that is the same as the pick-up time",'','dataContent' );
	}
	return true;
}
function callbackReLoadSearchResults02( message, errorCode ) {
	disableElement( 'dataContent', false );
	showMessage( message, errorCode, 'dataContent' );
	loadTransportationTripSummary( _cityUid, false );
	return true;
}/*-- global variables section --*/
var _type;
var _cabinLocation;
var _itemUid;
var _cruiseAmenitiesId;

/* This method show cruise results in single page as pagination. */
function showCruiseResultsPage ( pageIndex ) {
	_selectedPage = pageIndex;
	var queryString = "csr=2";
	queryString += "&selectedPage=" + pageIndex;
	makeAjaxCall ( 'cruiseSailingResults.act' , queryString , null , 'cruiseSailingResultsDiv' , 'callbackShowCruiseResultsPage' , '' );
}

/* Callback function to load the cruise search results on click of selected page. */
function callbackShowCruiseResultsPage () {
	if ( this.cancelled ) {
		disableElement ( "dataContent" , false );
	} else if ( ! showMessage ( this.errorMessage , this.errorCode , 'dataContent' ) ) {
		disableElement ( "dataContent" , false );
		loadPaginationDivs ();
	}
}

/* Load the pagination div after perform the cruise search. */
function loadPaginationDivs () {
	//update page selection	when
	// moving to right side , which meance increasing page number
	// moving to left side , which meance decreasing page number
	if ( _selectedPage != _startPage && _selectedPage != _endPage ) {
		updatePageSelection ( _selectedPage );
	}

	//create page numbers when 
	// selected page is first page displayed and has more pages downwards to display
	if ( _selectedPage == _startPage ) {
		setPageRange ( ( _selectedPage - _numberOfPagesToDisaplay ) > 0 ? ( _selectedPage - _numberOfPagesToDisaplay ) : 1 );
		updatePageSelection ( _selectedPage );
		return;
	}
	//selected page is last page displayed and has more pages upwards to display
	if ( _selectedPage == _endPage ) {
		setPageRange ( _selectedPage );
		updatePageSelection ( _selectedPage );
	}
}

/* On click of next link from the cruise search results page selection changes to the next page.*/
function nextPage () {
	_selectedPage = ( parseInt ( _currentPage ) + parseInt ( 1 ) ) <= _cruiseSailingResultsPageCount ? ( parseInt ( _currentPage ) + parseInt ( 1 ) )
			: _cruiseSailingResultsPageCount;
	if ( _selectedPage > _endPage ) {
		_endPage = _selectedPage;
	}
	showCruiseResultsPage ( _selectedPage )
}

/* On click of previous link from the cruise search results page selection changes to the previous page.*/
function previousPage () {
	_isNextPrevious = true;
	_selectedPage = ( _currentPage - 1 ) > 1 ? ( _currentPage - 1 ) : 1;
	if ( _selectedPage < _startPage ) {
		_startPage = _selectedPage;
	}
	showCruiseResultsPage ( _selectedPage )
}

/* Sets the start and end pages to the showing pagination of the cruise search results page*/
function setPageRange ( startPage ) {
	_startPage = startPage;
	var temp = parseInt ( startPage , 10 ) + parseInt ( _numberOfPagesToDisaplay , 10 );
	_endPage = temp < ( _cruiseSailingResultsPageCount ) ? temp : _cruiseSailingResultsPageCount;
	
	//When the displayed end page is equal to total available pages make sure we are displaying 
	//nuber of pages equal to number of pages to be displayed 
	if(((_endPage - _startPage) < _numberOfPagesToDisaplay) && (_endPage == _cruiseSailingResultsPageCount)){	
		_startPage = _cruiseSailingResultsPageCount - _numberOfPagesToDisaplay;
	}
	_startPage = ( _startPage < 1 ) ? 1 : _startPage;
	createPaginationDiv ( _startPage , _endPage , true , "topPaginationdiv" );
	createPaginationDiv ( _startPage , _endPage , false , "bottomPaginationDiv" );
}

/* Creates all pagination numbers */
function createPaginationDiv ( startPage, endPage, isTop, paginationDiv ) {
	var paginationDiv = document.getElementById ( paginationDiv );
	paginationDiv.innerHTML = "";
	paginationDiv.style.display = "none";
	var span = document.createElement ( 'SPAN' );
	span.className = 'b';
	span.appendChild ( document.createTextNode ( "Pages: " ) );
	paginationDiv.appendChild ( span );

	var imageSpacer1 = document.createElement ( 'IMG' );
	imageSpacer1.src = _webLoc + "/shared/images/core/spacer.gif";
	imageSpacer1.alt = "";
	imageSpacer1.width = '5';
	imageSpacer1.height = '1';
	paginationDiv.appendChild ( imageSpacer1 );

	var anchorPrevious = document.createElement ( 'A' );
	anchorPrevious.className = 'u';
	anchorPrevious.href = "javascript:;";
	anchorPrevious.onclick = function () {
		previousPage ();
	};
	anchorPrevious.appendChild ( document.createTextNode ( "Previous" ) );
	if ( isTop == true ) {
		anchorPrevious.id = 'previousTop';
	} else {
		anchorPrevious.id = 'previousBottom';
	}
	paginationDiv.appendChild ( anchorPrevious );

	var imageSpacer2 = document.createElement ( 'IMG' );
	imageSpacer2.src = _webLoc + "/shared/images/core/spacer.gif";
	imageSpacer2.alt = "";
	imageSpacer2.width = '5';
	imageSpacer2.height = '1';
	paginationDiv.appendChild ( imageSpacer2 );

	for ( var pageIndex = startPage; pageIndex <= endPage; pageIndex++ ) {
		createPage ( pageIndex , isTop , paginationDiv );
		if ( pageIndex != endPage ) {
			paginationDiv.appendChild ( document.createTextNode ( ' | ' ) );
		}
	}
	var imageSpacer3 = document.createElement ( 'IMG' );
	imageSpacer3.src = _webLoc + "/shared/images/core/spacer.gif";
	imageSpacer3.alt = "";
	imageSpacer3.width = '5';
	imageSpacer2.height = '1';
	paginationDiv.appendChild ( imageSpacer3 );
	
	var anchorNext = document.createElement ( 'A' );
	anchorNext.className = 'u';
	anchorNext.style.display = 'inline';
	anchorNext.href = "javascript:;";
	anchorNext.onclick = function () {
		nextPage ();
	};
	anchorNext.appendChild ( document.createTextNode ( "Next" ) );
	if ( isTop == true ) {
		anchorNext.id = 'nextTop';
	} else {
		anchorNext.id = 'nextBottom';
	}
	paginationDiv.appendChild ( anchorNext );
	paginationDiv.style.display = "";
}

/* Creates perticuler page number from the pagination div. */
function createPage ( pageIndex, isTop, paginationDiv ) {
	var pageNumberDiv = document.createElement ( 'DIV' );
	pageNumberDiv.style.display = 'inline';
	var pageNumberAnchor = document.createElement ( 'A' );
	pageNumberAnchor.className = 'pagenos';
	pageNumberAnchor.href = "javascript:;";
	pageNumberAnchor.onclick = function () {
		showCruiseResultsPage ( pageIndex );
	};
	pageNumberAnchor.appendChild ( document.createTextNode ( pageIndex ) );

	if ( isTop == true ) {
		pageNumberAnchor.id = "cruisePageTopAnchor_" + pageIndex;
	} else {
		pageNumberAnchor.id = "cruisePageBottomAnchor_" + pageIndex;
	}
	pageNumberDiv.appendChild ( pageNumberAnchor );
	paginationDiv.appendChild ( pageNumberDiv );
}

/* Updates the selection from the pagination div. */
function updatePageSelection ( selectedPage ) {
	_previousPage = _currentPage;
	_currentPage = selectedPage;
	
	// de select the previous page from top and bottom
	var cruisePageTopAnchor = document.getElementById ( "cruisePageTopAnchor_" + _previousPage );
	if ( cruisePageTopAnchor ) {
		cruisePageTopAnchor.className = "pagenos";
		cruisePageTopAnchor.href = "javascript:;";
		cruisePageTopAnchor.onclick = new Function ( "showCruiseResultsPage('" + _previousPage + "')" );
	}
	var cruisePageBottomAnchor = document.getElementById ( "cruisePageBottomAnchor_" + _previousPage );
	if ( cruisePageBottomAnchor ) {
		cruisePageBottomAnchor.className = "pagenos";
		cruisePageBottomAnchor.href = "javascript:;";
		cruisePageBottomAnchor.onclick = new Function ( "showCruiseResultsPage('" + _previousPage + "')" );
	}
	// select the current page	
	var cruisePageTopAnchor = document.getElementById ( "cruisePageTopAnchor_" + _currentPage );
	if ( cruisePageTopAnchor ) {
		cruisePageTopAnchor.className = "pagenos-sel";
		cruisePageTopAnchor.onclick = "";
		cruisePageTopAnchor.removeAttribute ( "href" );
	}
	var cruisePageBottomAnchor = document.getElementById ( "cruisePageBottomAnchor_" + _currentPage );
	if ( cruisePageBottomAnchor ) {
		cruisePageBottomAnchor.className = "pagenos-sel";
		cruisePageBottomAnchor.removeAttribute ( "href" );
		cruisePageBottomAnchor.onclick = "";
	}
	// If current page is more than 1 then show the previous page(top previous and bottom previous)
	if ( _currentPage == 1 ) {
		//hide Previous link
		document.getElementById ( "previousTop" ).style.display = 'none';
		document.getElementById ( "previousBottom" ).style.display = 'none';
	} else {
		//Show Previous link
		document.getElementById ( "previousTop" ).style.display = 'inline';
		document.getElementById ( "previousBottom" ).style.display = 'inline';
	}
	// Handling next link( top next and bottom next ).
	if ( _currentPage == _cruiseSailingResultsPageCount ) {
		//hide Next link
		document.getElementById ( "nextTop" ).style.display = 'none';
		document.getElementById ( "nextBottom" ).style.display = 'none';
	} else {
		//Show Next link
		document.getElementById ( "nextTop" ).style.display = 'inline';
		document.getElementById ( "nextBottom" ).style.display = 'inline';
	}
}

/* This method sorts the cruise search results by soft field input. */
function sortCruiseResults ( sortField, sortAscending ) {
	var queryString = "csr=3";
	queryString += "&sortField=" + sortField;
	queryString += "&sortAscending=" + sortAscending;

	disableElement ( 'dataContent' , true );
	makeAjaxCallWithWaitingDiv ( 'cruiseSailingResults.act' , queryString , null , 'rightContent' , 'callbackSortCruiseResults' );

}

/* Call back function for sorting the cruise search results by soft field input. */
function callbackSortCruiseResults () {
	if ( this.cancelled ) {
		disableElement ( "dataContent" , false );
	} else if ( ! showMessage ( this.errorMessage , this.errorCode , 'dataContent' ) ) {
		disableElement ( "dataContent" , false );
		setPageRange ( 1 );
		updatePageSelection ( 1 );
	}
}

/* Shows the member benefit popup on click of ship board credit or cash card component link */
function showMemberBenefitsPopup ( itemUid, type, cruiseAmenitiesId, isMember, destination, cruiseLine, ship, departureDate ) {
	createPopupDiv ( "memberBenefitsPopupDivContainer" , - 1 , - 1 , - 1 , 200 , false , true , "" );
	
	var queryString = "csr=4";
	queryString += "&cruiseSailingItemUid=" + itemUid;
	queryString += "&type=" + type;
	if( cruiseAmenitiesId != null && cruiseAmenitiesId != undefined ) {
		queryString += "&cruiseAmenitiesId=" + cruiseAmenitiesId;
	}
	
	var year = '';
	var month = '';
	var day = '';
	if (departureDate){
		year = departureDate.substring(departureDate.length - 4, departureDate.length);
		month = departureDate.substring(0, 2);
		day = departureDate.substring(3, 5);
	}	

	//Load the cruise itinerary with '/cr/booking/searchWidget/sailing<Non>MemberAddedValues/<destination>/<cruiseLine>/<ship>/<date>' as the description to be passed into Google Analytics
	var trackingText = '/cr/booking/searchWidget/sailing' + (isMember ? '' : 'Non')+ 'MemberAddedValues/' + destination + '/' + cruiseLine + '/' + ship + '/' + year + month + day;
	makeAjaxCall ( 'cruiseSailingResults.act' , queryString, null , 'memberBenefitsPopupDivContainer' , 'callbackShowMemberBenefitsPopup' , trackingText );
}

/* Call back function for member benefit popup on click of ship board credit or cash card component link */
function callbackShowMemberBenefitsPopup () {
	if ( !( showMessage( this.errorMessage, this.errorCode , "memberBenefitsPopupDivContainer" ) ) ) {
		showBlock ( "memberBenefitsPopupDivContainer" );
		positionBlockCentrally ( "memberBenefitsPopupDivContainer" );
		disableElement ( "dataContent" , true );
		document.getElementById("membershipNumber").focus();
	}
}

function showCruiseSailingDetails( cruiseSailingItemUid, selectedTab, backgroundDivId, type, destination, cruiseLine, ship, departureDate ) {
	var callbackFunctionParams = new Array();
	callbackFunctionParams.push( backgroundDivId );
	
	createPopupDiv ( "detailedItineraryPopupDivContainer" , - 1 , - 1 , - 1 , 200 , false , true , "" );
	disableElement ( backgroundDivId, true );

	var queryString = "csr=1";
	queryString += "&cruiseSailingItemUid=" + cruiseSailingItemUid;
	queryString += "&selectedTab=" + selectedTab;
	
	var trackingText = null;
	var year = '';
	var month = '';
	var day = '';
	var widgetType = 'searchWidget';
	if (departureDate){
		year = departureDate.substring(departureDate.length - 4, departureDate.length);
		month = departureDate.substring(0, 2);
		day = departureDate.substring(3, 5);
	}	
	
	if (type == 'sailing'){
		widgetType = 'searchWidget';
	}
	else if (type = 'category'){
		widgetType = 'bookingWidget';
	}
	
	if (selectedTab == 0){
		//Load the cruise itinerary with '/cr/booking/searchWidget/sailingPopupItinerary/<destination>/<cruiseLine>/<ship>/<date>' as the description to be passed into Google Analytics
		trackingText = '/cr/booking/' + widgetType + '/' +  type + 'PopupItinerary/' + destination + '/' + cruiseLine + '/' + ship + '/' + year + month + day;
	} 
	else if (selectedTab == 1){
		//Load the cruise overview with '/cr/booking/searchWidget/sailingPopupOverview/<destination>/<cruiseLine>/<ship>/<date>' as the description to be passed into Google Analytics
		trackingText = '/cr/booking/' + widgetType + '/' +  type + 'PopupOverview/' + destination + '/' + cruiseLine + '/' + ship + '/' + year + month + day;
	}	
	else if (selectedTab == 2){
		//Load the cruise activities with '/cr/booking/searchWidget/sailingPopupActivities/<destination>/<cruiseLine>/<ship>/<date>' as the description to be passed into Google Analytics
		trackingText = '/cr/booking/' + widgetType + '/' +  type + 'PopupActivities/' + destination + '/' + cruiseLine + '/' + ship + '/' + year + month + day;
	}	
	else if (selectedTab == 3){
		//Load the cruise dining with '/cr/booking/searchWidget/sailingPopupDining/<destination>/<cruiseLine>/<ship>/<date>' as the description to be passed into Google Analytics
		trackingText = '/cr/booking/' + widgetType + '/' +  type + 'PopupDining/' + destination + '/' + cruiseLine + '/' + ship + '/' + year + month + day;
	}	
	
	makeAjaxCallWithWaitingDiv ( "cruiseSailingResults.act" , queryString , null , "detailedItineraryPopupDivContainer" , "callbackShowCruiseSailingDetails", callbackFunctionParams, trackingText );
}

function callbackShowCruiseSailingDetails( backgroundDivId ) {
	disableElement ( backgroundDivId, false );

	if ( !( showMessage( this.errorMessage, this.errorCode , backgroundDivId ) ) ) {
		disableElement( "dataContent", true );
		showBlock ( "detailedItineraryPopupDivContainer" );
		positionBlockCentrally ( "detailedItineraryPopupDivContainer" );
	}
}

function showCruiseRatingPopup (destination, cruiseLine, ship, departureDate) {
	createPopupDiv ( "cruiseRatingPopupDivContainer" , - 1 , - 1 , - 1 , 200 , false , true , "" );
	disableElement ( "dataContent" , true );

	var year = '';
	var month = '';
	var dat = '';
	var widgetType = 'searchWidget';
	if (departureDate){
		year = departureDate.substring(departureDate.length - 4, departureDate.length);
		month = departureDate.substring(0, 2);
		day = departureDate.substring(3, 5);
	}	

	//Load the cruise rating popup with '/cr/booking/searchWidget/sailingStarRating/<destination>/<cruiseLine>/<ship>/<date>' as the description to be passed into Google Analytics
	trackingText = '/cr/booking/searchWidget/sailingStarRating/' + destination + '/' + cruiseLine + '/' + ship + '/' + year + month + day;
	
	makeAjaxCall ( 'cruiseSailingResults.act' , "csr=6" , null , 'cruiseRatingPopupDivContainer' , 'callbackShowCruiseRatingPopup' ,	trackingText );
}

function callbackShowCruiseRatingPopup () {
	showBlock ( "cruiseRatingPopupDivContainer" );
	positionBlockCentrally ( "cruiseRatingPopupDivContainer" );
}

function verifyMembershipNumber( type, itemUid, cabinLocation, cruiseAmenitiesId, event, isKeyEvent ) {
	if ( ( ! isNull ( isKeyEvent ) ) && ( ! isEnterKey ( event ) ) ) {
		return false;
	}
	var membershipNumber = trim ( document.getElementById ( "membershipNumber" ).value );
	if ( membershipNumber == "" ) {
		showErrorMessage ( 'Please enter member number' , 'memberBenefitsPopupDivContainer' , 'membershipNumber' , '1px solid #7f9db9' );
		return;
	}
	_type = type;
	_itemUid = itemUid;
	_cabinLocation = cabinLocation;
	_cruiseAmenitiesId = cruiseAmenitiesId;
	var queryString = 'md=11';
	queryString += '&membershipNumber=' + membershipNumber;

	disableElement ( "memberBenefitsPopupDivContainer" , true );
	makeAjaxCallWithWaitingDiv ( 'membershipDetail.act' , queryString , null , null , 'callbackVerifyMembershipNumber' );
}

function callbackVerifyMembershipNumber () {
	if ( ! ( showMessage ( this.errorMessage , this.errorCode , 'memberBenefitsPopupDivContainer' ) ) ) {
		disableElement ( "memberBenefitsPopupDivContainer" , false );
		if ( trim ( _cabinLocation ) != '' ) {
			loadCruiseCategoryOrSailingResults ( false );
		} else {
			loadCruiseCategoryOrSailingResults ( true );
		}
	}
}

function loadCruiseCategoryOrSailingResults ( isCruiseSailing ) {
	if ( isCruiseSailing ) {
		var queryString = "rc=27";
		makeAjaxCall ( 'rightContent.act' , queryString , null , 'rightContent' , 'callbackLoadCruiseCategoryOrSailingResults' , '' );
	} else {
		var queryString = "ccr=0";
		makeAjaxCall ( 'cruiseCategoryResults.act' , queryString , null , 'rightContent' , 'callbackLoadCruiseCategoryOrSailingResults' ,	'' );
	}
}

function callbackLoadCruiseCategoryOrSailingResults () {
	if ( ! ( showMessage ( this.errorMessage , this.errorCode , 'dataContent' ) ) ) {
		if( _cruiseAmenitiesId != '' ) {
			showMemberBenefitsPopup ( _itemUid , _type , _cruiseAmenitiesId );
		} else {
			showMemberBenefitsPopup ( _itemUid , _type );
		}
	}
}

function loadMemberVerificationPopup(cruiseSailingItemUid, destination, cruiseLine, ship, departureDate) {
	createPopupDiv ( "memberVerificationDivContainer" , - 1 , - 1 , - 1 , 200 , false , true , "" );
	disableElement ( "dataContent" , true );

	var year = '';
	var month = '';
	var day = '';
	if (departureDate){
		year = departureDate.substring(departureDate.length - 4, departureDate.length);
		month = departureDate.substring(0, 2);
		day = departureDate.substring(3, 5);
	}	
	
	//Load the membership verification popup with '/cr/booking/searchWidget/sailingMemberVerification/<destination>/<cruiseLine>/<ship>/<date>' as the description to be passed into Google Analytics
	var trackingText = '/cr/booking/searchWidget/sailingMemberVerification/' + destination + '/' + cruiseLine + '/' + ship + '/' + year + month + day;
	makeAjaxCall ( 'cruiseSailingResults.act' , "csr=7&cruiseSailingItemUid=" + cruiseSailingItemUid , null , 'memberVerificationDivContainer' ,
			'callbackLoadMemberVerificationPopup' , trackingText, '' );
}

function callbackLoadMemberVerificationPopup() {
	showBlock ( "memberVerificationDivContainer" );
	positionBlockCentrally ( "memberVerificationDivContainer" );
	document.getElementById("membershipNumber").select();
}

function loadCruiseResultsOnValidMembership( event, isKeyEvent, destination, cruiseLine, ship, departureDate ) {
	if( ( !isNull( isKeyEvent ) ) && ( !isEnterKey( event ) ) ) {
		return false;
	}
	var membershipNumber = trim( document.getElementById( "membershipNumber" ).value );
	if( membershipNumber == "" ) {
		showErrorMessage('Please enter member number', 'memberVerificationDivContainer', 'membershipNumber', '1px solid #7f9db9');
    	return;
	}
	var queryString = 'md=12';
	queryString += '&membershipNumber='+ membershipNumber;
	queryString += '&selectedPage='+ _selectedPage;
	disableElement ( "memberVerificationDivContainer" , true );
	
	var year = '';
	var month = '';
	var dat = '';
	if (departureDate){
		year = departureDate.substring(departureDate.length - 4, departureDate.length);
		month = departureDate.substring(0, 2);
		day = departureDate.substring(3, 5);
	}	

	//Load the category selection page with '/cr/booking/bookingWidget/categorySelectionInside/<destination>/<cruiseLine>/<ship>/<date>' as the description to be passed into Google Analytics
	//var trackingText = '/cr/booking/bookingWidget/categorySelectionInside/' + destination + '/' + cruiseLine + '/' + ship + '/' + year + month + day;
	
	makeAjaxCallWithWaitingDiv( 'membershipDetail.act', queryString, null, 'cruiseSailingResultsDiv', 'callbackLoadCruiseResultsOnValidMembership' );
}

function callbackLoadCruiseResultsOnValidMembership() {
	if ( !( showMessage( this.errorMessage, this.errorCode , 'memberVerificationDivContainer' ) ) ) {
		disableElement( 'memberVerificationDivContainer', false );
		hideBlock( 'memberVerificationDivContainer' );
		disableElement( 'dataContent', false);
	}
}

function proceedToPassengerDetailPage( cruiseSailingItemUid, destination, cruiseLine, ship, departureDate ) {
	var queryString = 'csr=8';
	queryString += "&cruiseSailingItemUid=" + cruiseSailingItemUid;

	var year = '';
	var month = '';
	var dat = '';
	if (departureDate){
		year = departureDate.substring(departureDate.length - 4, departureDate.length);
		month = departureDate.substring(0, 2);
		day = departureDate.substring(3, 5);
	}	

	//Load the passener information page with '/cr/booking/bookingWidget/passengerInfo/<destination>/<cruiseLine>/<ship>/<date>' as the description to be passed into Google Analytics
	var trackingText = '/cr/booking/bookingWidget/passengerInfo/' + destination + '/' + cruiseLine + '/' + ship + '/' + year + month + day;
	
	disableElement( 'dataContent', true );
	makeAjaxCallWithWaitingDiv( 'cruiseSailingResults.act', queryString, null, 'mainContent', 'callbackProceedToPassengerDetailPage', null, trackingText);
}

function callbackProceedToPassengerDetailPage() {
	if ( !( showMessage( this.errorMessage, this.errorCode , 'dataContent' ) ) ) {
		disableElement ( "dataContent" , false );
	}
	setSupportPhoneNumber(supportPhoneNumber);
}

function loadCruiseResults() {
	var queryString = "lc=7&lbc=2&rc=27";
	disableElement ( "dataContent" , true );
	makeAjaxCallWithWaitingDiv( 'mainContent.act', queryString, null, 'mainContent', 'callbackLoadCruiseResults' );
}

function callbackLoadCruiseResults() {
	if ( !( showMessage( this.errorMessage, this.errorCode , 'dataContent' ) ) ) {
		disableElement ( "dataContent" , false );
	}
	setSupportPhoneNumber(bookingPhoneNumber);
}function loadCruiseLinesForDestination ( displayAllSeaports ) {
	var destinationCode = document.getElementById ( "cruiseDestination" ).value;
	var queryString = "";
	queryString += "lc=8";
	queryString += '&destinationCode=' + destinationCode;
	makeAjaxCall ( 'leftContent.act' , queryString , null , 'mainContent' , 'callbackLoadCruiseLinesForDestination' , '' );
}

function callbackLoadCruiseLinesForDestination ( cruiseLinesJSON, regionList ) {
	replaceOptions ( "cruiseLine" , cruiseLinesJSON );
	document.getElementById ( "cruiseLine" ) [ 0 ].text = "Any";
	document.getElementById ( "cruiseShips" ).length = 1;
	document.getElementById ( "cruiseShips" ) [ 0 ].text = "Any";
	document.getElementById("regionList").innerHTML = regionList;
}

function callbackLoadShipsToursAndPorts ( shipsJSON, seaportsJSON ) {
	replaceOptions ( "cruiseShips" , shipsJSON );
	replaceOptions ( "portOfEmbarkation" , seaportsJSON );
	document.getElementById ( "cruiseShips" ) [ 0 ].text = "Any";
	document.getElementById ( "portOfEmbarkation" ) [ 0 ].text = "Any";
}
function showHideMoreSearchOptions () {
	var displayStatus = document.getElementById ( "moreSearchOptionBlock" ).style.display;
	if ( displayStatus == "block" ) {
		document.getElementById ( "moreSearchOptionBlock" ).style.display = "none";
		document.getElementById ( "cruiseShips" ) [ 0 ].selected = true;
		document.getElementById ( "portOfEmbarkation" ) [ 0 ].selected = true;
	} else {
		document.getElementById ( "moreSearchOptionBlock" ).style.display = "block";
	}
}

function loadCruiseShipsAndPorts () {
	var destinationCode = document.getElementById ( "cruiseDestination" ).value;
	var cruiseLine = document.getElementById ( "cruiseLine" ).value;
	var queryString = "lc=9&destinationCode=" + destinationCode;
	queryString += "&cruiseLineCodes=" + cruiseLine;
	makeAjaxCall ( "leftContent.act" , queryString , null , 'mainContent' , 'callbackLoadShipsAndPorts' , '' );
}

function callbackLoadShipsAndPorts ( shipsJSON, seaportsJSON ) {
	if ( ! showMessage ( this.errorType , this.errorCode , this.errorMessage , 'dataContent' ) ) {
		disableElement ( "dataContent" , false );
		replaceOptions ( "cruiseShips" , shipsJSON );
		replaceOptions ( "portOfEmbarkation" , seaportsJSON , 1 );
		document.getElementById ( "cruiseShips" ) [ 0 ].text = "Any";
		document.getElementById ( "portOfEmbarkation" ) [ 0 ].text = "Any";
	}
}

function doCruiseSearch () {
	clearErrorElements();
	var destinationCode = document.getElementById ( "cruiseDestination" ).value;
	var departureDateString = document.getElementById ( "departureDate" ).value;
	var cruiseLineCode = document.getElementById ( "cruiseLine" ).value;
	var cruiseLength = document.getElementById ( "cruiseLength" ).value;
	var shipCode = document.getElementById ( "cruiseShips" ).value;
	var portOfEmbarkation = document.getElementById ( "portOfEmbarkation" );
	if ( departureDateString == '' ) {
		var msg = "Please select departure month.";
		showErrorMessage ( msg , 'dataContent', 'departureDateDiv', '#7f9db9' );
		return false;
	}
	
	var departureDateText = document.getElementById ( "departureDate" )[document.getElementById ( "departureDate" ).selectedIndex].text;
	var year = departureDateText.substring(departureDateText.length - 4, departureDateText.length);
	var month = departureDateText.substring(0, departureDateText.length - 5);
	
	var queryString = "css=1";
	queryString += "&destinationCode=" + destinationCode
	if ( cruiseLineCode != 0 ) {
		queryString += "&cruiseLineCodes=" + cruiseLineCode;
	}
	queryString += "&departureDateString=" + departureDateString;
	if ( document.getElementById ( "moreSearchOptionBlock" ).style.display == "block" ) {
		if ( shipCode != 0 ) {
			queryString += "&shipCodes=" + shipCode;
		}
		queryString += "&portOfEmbarkation=" + portOfEmbarkation.value;
	}
	queryString += "&cruiseLength=" + cruiseLength;

	disableElement ( 'dataContent' , true );
	
	//Load the cruise search results with '/cr/booking/searchWidget/sailingResults/<destination>/<cruiseLine>/<ship>/<date>' as the description to be passed into Google Analytics
	var trackingText = '/cr/booking/searchWidget/sailingResults/' 
						+ (destinationCode == '' ? 'ALL': destinationCode) + '/' 
						+ (cruiseLineCode == '' ? 'ALL' : cruiseLineCode) 
						+ '/ALL/' + year + month;
	
	makeAjaxCallWithWaitingDiv( 'cruiseSearch.act', queryString, null, 'rightContent', 'callbackDoCruiseSailingSearch', null, trackingText );
}

function callbackDoCruiseSailingSearch () {
	if ( ! showMessage ( this.errorMessage , this.errorCode , 'dataContent' ) ) {
		disableElement ( 'dataContent' , false );
	}
	return true;
}

function loadCruiseChildrenAges() {
	var maxChildrensInCabin = 4;
	var childrenAgesTd = document.getElementById ( "childrenAgesDiv" );
	var numberOfChildren = document.getElementById ( "childrenInCabin" ).value;
	if ( numberOfChildren == 0 ) {
		childrenAgesTd.style.display = "none";
	} else {
		childrenAgesTd.style.display = "block";
	}
	for( var childCounter = 1; childCounter <= maxChildrensInCabin ; childCounter++ ) {
		document.getElementById( "childrenAge_" + childCounter ).style.display = "none";
	}
	for( var childCounter = 1; childCounter <= numberOfChildren ; childCounter++ ) {
		document.getElementById( "childrenAge_" + childCounter ).style.display = "";
	}
}

function loadCruiseInfantAges() {
	var maxInfantsInCabin = 4;
	var infantAgesTd = document.getElementById ( "infantAgesDiv" );
	var numberOfInfants = document.getElementById ( "infantsInCabin" ).value;
	if ( numberOfInfants == 0 ) {
		infantAgesTd.style.display = "none";
	} else {
		infantAgesTd.style.display = "block";
	}
	for( var infantCounter = 1; infantCounter <= maxInfantsInCabin ; infantCounter++ ) {
		document.getElementById( "infantAge_" + infantCounter ).style.display = "none";
	}
	for( var infantCounter = 1; infantCounter <= numberOfInfants ; infantCounter++ ) {
		document.getElementById( "infantAge_" + infantCounter ).style.display = "";
	}
}

function loadCruiseTripSummary(){
	var queryString = "lc=10";
	makeAjaxCall( 'leftContent.act', queryString, null, 'leftContent', 'callbackReLoadCruiseTripSummary' );
}

function callbackReLoadCruiseTripSummary(){
	if ( !( showMessage( this.errorMessage, this.errorCode , 'dataContent' ) ) ) {
		disableElement ( "dataContent" , false );
	}
}

function showHidePastPassengerNumber(){
	if( document.getElementById( "isPastPassenger" ).checked ){
		document.getElementById ( "pastPassengerNumberRow" ).style.display = "block";
	} else {
		document.getElementById ( "pastPassengerNumberRow" ).style.display = "none";
	}
}

function showDOBCalendar ( fieldName ) {
	showCalendar ( fieldName , null , null , null , true );
}function loadCruiseCategories( cabinLocation, selectedCabinDiv, selectedCabinLink, destination, cruiseLine, ship, departureDate  ) {
	inActivateAllCabinTabs();
	activateCabinTab( selectedCabinDiv, selectedCabinLink );
	var queryString = "ccr=1";
	queryString += '&cabinLocation=' + cabinLocation;
	disableElement ( "dataContent" , true );
	
	var year = '';
	var month = '';
	var day = '';
	if (departureDate){
		year = departureDate.substring(departureDate.length - 4, departureDate.length);
		month = departureDate.substring(0, 2);
		day = departureDate.substring(3, 5);
	}	

	//Load the category selection page with '/cr/booking/bookingWidget/categorySelection<cabinLocation>/<destination>/<cruiseLine>/<ship>/<date>' as the description to be passed into Google Analytics
	var trackingText = '/cr/booking/bookingWidget/categorySelection' + cabinLocation.replace(' ','')+ '/' + destination + '/' + cruiseLine + '/' + ship + '/' + year + month + day;
		
	makeAjaxCallWithWaitingDiv ( 'cruiseCategoryResults.act' , queryString , null , 'cruiseCategoryResultsDiv' , 'callbackLoadCruiseCategories' , null, trackingText );
}

function callbackLoadCruiseCategories() {
	disableElement ( "dataContent" , false );
}

function inActivateAllCabinTabs() {
	var oceanViewCabinTab = document.getElementById( "oceanViewCabinDiv" );
	var balconyCabinTab = document.getElementById( "balconyCabinDiv" );
	var suiteCabinTab = document.getElementById( "suiteCabinDiv" );
	inActivateCabinTab( 'insideCabinDiv', 'insideCabinLink' );
	inActivateCabinTab( 'oceanViewCabinDiv', 'oceanViewCabinLink' );
	inActivateCabinTab( 'balconyCabinDiv', 'balconyCabinLink' );
	inActivateCabinTab( 'suiteCabinDiv', 'suiteCabinLink' );
}

function inActivateCabinTab( cabinDivId, cabinLinkId ) {
	var cabinTab = document.getElementById( cabinDivId );
	if( !isNull( cabinTab ) ) {
		cabinTab.className = "tab02 nob";
	}
}

function activateCabinTab( cabinDivId, cabinLinkId ) {
	var cabinTab = document.getElementById( cabinDivId );
	if( !isNull( cabinTab ) ) {
		cabinTab.className = "tab-sel02 nob";
	}
}

function reLoadCruiseCategoryResults(){
	var queryString = "ccr=0";

	disableElement( 'dataContent', true );
	makeAjaxCallWithWaitingDiv( 'cruiseCategoryResults.act', queryString, null, 'rightContent', 'callbackReLoadCruiseCategoryResults' );
}

function callbackReLoadCruiseCategoryResults(){
	if ( !( showMessage( this.errorMessage, this.errorCode , 'dataContent' ) ) ) {
		loadCruiseTripSummary();
		disableElement ( "dataContent" , false );
	}
}

/* Shows the category rate type popup on click of link */
function showCategoryRateTypePopup( rateCode ) {
	var queryString = "ccr=2";
	queryString += "&rateCode=" + rateCode;
	createPopupDiv ( "categoryRateTypePopupDivContainer" , - 1 , - 1 , - 1 , 200 , false , true , "" );
	disableElement ( "dataContent" , true );
	makeAjaxCall ( 'cruiseCategoryResults.act' , queryString, null , 'categoryRateTypePopupDivContainer' ,
			'callbackShowCategoryRateTypePopup' , '' );
}

/* Call back function for category rate type popup */
function callbackShowCategoryRateTypePopup() {
	showBlock ( "categoryRateTypePopupDivContainer" );
	positionBlockCentrally ( "categoryRateTypePopupDivContainer" );
	disableElement ( "dataContent" , true );
}

/* Shows the member benefit popup on click of ship board credit or cash card component link */
function showMemberValueAddsPopup ( cabinLocation, type, isMember, destination, cruiseLine, ship, departureDate ) {
	createPopupDiv ( "memberBenefitsPopupDivContainer" , - 1 , - 1 , - 1 , 200 , false , true , "" );
	disableElement ( "dataContent" , true );
	var queryString = "ccr=3";
	queryString +="&cabinLocation=" + cabinLocation;
	queryString +="&type=" + type;
	
	var year = '';
	var month = '';
	var day = '';
	if (departureDate){
		year = departureDate.substring(departureDate.length - 4, departureDate.length);
		month = departureDate.substring(0, 2);
		day = departureDate.substring(3, 5);
	}	

	//Load the cruise itinerary with '/cr/booking/searchWidget/sailing<Non>MemberAddedValues/<destination>/<cruiseLine>/<ship>/<date>' as the description to be passed into Google Analytics
	var trackingText = '/cr/booking/bookingWidget/category' + (isMember ? '' : 'Non')+ 'MemberAddedValues/' + destination + '/' + cruiseLine + '/' + ship + '/' + year + month + day;
	makeAjaxCall ( 'cruiseCategoryResults.act' , queryString, null , 'memberBenefitsPopupDivContainer' , 'callbackShowMemberValueAddsPopup' , trackingText );
}

/* Call back function for member value adds popup.*/
function callbackShowMemberValueAddsPopup() {
	showBlock ( "memberBenefitsPopupDivContainer" );
	positionBlockCentrally ( "memberBenefitsPopupDivContainer" );
	disableElement ( "dataContent" , true );
}

function loadCruiseDeckPlans( cruiseCategoryItemUid, selectedDeckName,  destination, cruiseLine, ship, departureDate ) {
	var queryString = "ccr=4";
	queryString += "&uid=" + cruiseCategoryItemUid;
	queryString += "&selectedDeckName=" + selectedDeckName;
	disableElement( "dataContent" , true );
	createPopupDiv( "cruiseDeckPlansPopupDivContainer" , -1, -1, -1, 200, false, true, "" );
	
	var year = '';
	var month = '';
	var day = '';
	if (departureDate){
		year = departureDate.substring(departureDate.length - 4, departureDate.length);
		month = departureDate.substring(0, 2);
		day = departureDate.substring(3, 5);
	}	

	//Load the cruise deck plans popup with '/cr/booking/bookingWidget/categoryPopupDeckPlans/<destination>/<cruiseLine>/<ship>/<date>' as the description to be passed into Google Analytics
	var trackingText = '/cr/booking/bookingWidget/categoryPopupDeckPlans/' + destination + '/' + cruiseLine + '/' + ship + '/' + year + month + day;
	makeAjaxCall( 'cruiseCategoryResults.act' , queryString, null , 'cruiseDeckPlansPopupDivContainer', 'callbackLoadCruiseDeckPlans' , trackingText );
}

function callbackLoadCruiseDeckPlans() {
	showBlock( "cruiseDeckPlansPopupDivContainer" );
	positionBlockCentrally( "cruiseDeckPlansPopupDivContainer" );
}

function closeCruiseDeckPlansPopupDiv() {
	removeElement( 'cruiseDeckPlansPopupDivContainer' );
	disableElement( 'dataContent', false );
}function proceedToCruiseCabinSearch ( cruiseCategoryItemUid, destination, cruiseLine, ship, departureDate ) {
	var queryString = "css=3";
	queryString += "&cruiseCategoryItemUid=" + cruiseCategoryItemUid;
	
	var year = '';
	var month = '';
	var day = '';
	if (departureDate){
		year = departureDate.substring(departureDate.length - 4, departureDate.length);
		month = departureDate.substring(0, 2);
		day = departureDate.substring(3, 5);
	}	

	//Load the cabin selection page with '/cr/booking/bookingWidget/cabinSelection/<destination>/<cruiseLine>/<ship>/<date>' as the description to be passed into Google Analytics
	var trackingText = '/cr/booking/bookingWidget/cabinSelection/' + destination + '/' + cruiseLine + '/' + ship + '/' + year + month + day;
	
	disableElement ( 'dataContent' , true );
	makeAjaxCallWithWaitingDiv ( 'cruiseSearch.act' , queryString , null , 'rightContent' , 'callbackProceedToCruiseCabinSearch', null, trackingText );
}

function callbackProceedToCruiseCabinSearch () {
	if ( ! ( showMessage ( this.errorMessage , this.errorCode , 'dataContent' ) ) ) {
		loadCruiseTripSummary ();
		disableElement ( "dataContent" , false );
	}
}

function selectCabin ( cabinCode, cabinItemUid ) {
	var queryString = "crcr=1";

	queryString += "&cruiseCabinItemUid=" + cabinItemUid;
	makeAjaxCall ( "cruiseCabinResults.act" , queryString , null , "rightContent" , "callbackSelectCabin" );
}

function callbackSelectCabin ( bedOptionJSON ) {
	if ( ! ( showMessage ( this.errorMessage , this.errorCode , 'dataContent' ) ) ) {
		disableElement ( "dataContent" , false );
		var options = bedOptionJSON.parseJSON ();
		if( options.length > 0 ){
			document.getElementById( "beddingConfigDiv" ).style.display = "";
			replaceOptions ( "bedOption" , bedOptionJSON );
		}else {
			document.getElementById ( "bedOption" ).length = 1;
			document.getElementById ( "bedOption" ) [ 0 ].text = "Select";
		}
	}
}

function loadCruiseCabins ( cruiseCategoryItemUid ) {
	var queryString = "crcr=2";
	var deckName = document.getElementById ( "cruiseDeckName" ).value;
	queryString += "&selectedDeckName=" + deckName;
	queryString += "&cruiseCategoryItemUid=" + cruiseCategoryItemUid;
	makeAjaxCall ( "cruiseCabinResults.act" , queryString , null , "cruiseCabinInfoDiv" , "callLoadCruiseCabins" );
}

function callLoadCruiseCabins () {
	if ( ! ( showMessage ( this.errorMessage , this.errorCode , 'dataContent' ) ) ) {
		disableElement ( "dataContent" , false );
	}
}

function proceedToMemberLogin( isReturn ) {
	var cabinOptions = document.getElementsByName( "cabinOption" );
	var isCabinSelected = false;
	for ( var cabinIndex = 0; cabinIndex < cabinOptions.length; cabinIndex++ ) {
		if ( cabinOptions [ cabinIndex ].checked ) {
			isCabinSelected = true;
			break;
		}
	}

	if( isCabinSelected ) {
		if( !isReturn ) {
			var queryString = "md=13";
			disableElement( 'dataContent' , true );
			
			//Load the passenger details screen with '/cr/booking/bookingWidget/passengerDetails/<destination>/<cruiseLine>/<ship>/<date>' as the description to be passed into Google Analytics
			var trackingText = '/cr/booking/bookingWidget/passengerDetails/' + _destinationName + '/' + _cruiseLineName + '/' + _shipName + '/' + _departureDate;
			makeAjaxCallWithWaitingDiv ( 'membershipDetail.act' , queryString , null , 'rightContent' , 'callbackProceedToMemberLogin', null, trackingText );
		} else {
			disableElement( 'dataContent' , true );
		    var splashScreenRequest = new SplashScreenRequest();
		    splashScreenRequest.splashScreenText = "Please Wait...";
		    displaySearchingPopup( splashScreenRequest );
			return true;
		}
	} else {
		showErrorMessage( 'Before you continue, please select a stateroom', 'dataContent' );
		return false;
	}
}

function callbackProceedToMemberLogin() {
	if( !showMessage( this.errorMessage, this.errorCode, 'dataContent' ) ) {
		disableElement ( "dataContent" , false );
		loadCruiseTripSummary ();
		showGeneralMessage( message, 'dataContent' );
	}
	return true;
}

function reLoadCruiseCabinResults( cruiseCategoryItemUid ) {
	var queryString = "crcr=0";
	if( !isNull( cruiseCategoryItemUid ) ) {
		queryString += "&cruiseCategoryItemUid=" + cruiseCategoryItemUid; 
	}
	disableElement ( 'dataContent' , true );
	makeAjaxCallWithWaitingDiv ( 'cruiseCabinResults.act' , queryString , null , 'rightContent' , 'callReLoadCruiseCabinResults' );
}

function callReLoadCruiseCabinResults(){
	if ( ! ( showMessage ( this.errorMessage , this.errorCode , 'dataContent' ) ) ) {
		loadCruiseTripSummary ();
		disableElement ( "dataContent" , false );
	}
}

function selectCabinBedConfiguration () {
	var selectedBedConfigurationUid = document.getElementById ( "bedOption" ).value;
	if ( selectedBedConfigurationUid != "" ) {
		var queryString = "crcr=3";
		queryString += "&cabinBedConfigurationItemUid=" + selectedBedConfigurationUid;
		makeAjaxCall ( "cruiseCabinResults.act" , queryString , null , null , "callbackSelectCabinBedConfiguration" );
	}
}

function callbackSelectCabinBedConfiguration () {
	showMessage ( this.errorType , this.errorCode , this.errorMessage , 'dataContent' );
}

function loadDeckPlan( deckCounter, travtechShipId, configId, deckId, deckName, numberOfDecks ) {
	var deckLevelImage = document.getElementById( "deckLevelImage" );
	var deckPlanImage = document.getElementById( "deckPlanImage" );
	var deckPlanTitle = document.getElementById( "deckPlanTitle" );
	deckLevelImage.src = _sharedLoc + "/images/core/icons/ship/decks/shipDeckPlan_" + ( 19 - deckCounter ) + ".gif";
	deckPlanImage.src = _sharedLoc + "/images/cruise/deckPlans/ships/" + travtechShipId + "/" + configId + "/Decks/" + deckId + ".gif";
	deckPlanImage.title = deckName;
	deckPlanTitle.innerHTML = deckName;
	for( var i = 0; i < numberOfDecks; i++ ) {
		var deckNameObject = document.getElementById( "deckName_" + i );
		if( i == deckCounter ) {
			modifyClassName( deckNameObject, "+b +bgc09" );
		} else {
			modifyClassName( deckNameObject, "-b -bgc09" );
		}
	}
}
function proceedToCruiseCategorySearch () {
	var numberOfAdults = document.getElementById ( "adultsInCabin" ).value;
	var numberOfChildren = document.getElementById ( "childrenInCabin" ).value;
	var numberOfInfants = document.getElementById ( "infantsInCabin" ).value;
	var pastPassengerNumber = document.getElementById ( "pastPassengerNumber" ).value;
	var residentCityCode = document.getElementById ( "residencyCity" ).value;
	var isPastPassenger = document.getElementById ( "isPastPassenger" ).checked;
 	if( isPastPassenger ) {
 		if ( ! ( validateField ( 'pastPassengerNumber', 'Please enter past passenger number' ) ) ) {
			return false;
		}
 	}
	var queryString = "pi=3";
	queryString += "&numAdults=" + numberOfAdults;
	queryString += "&numChildren=" + numberOfChildren;
	queryString += "&numInfants=" + numberOfInfants;

	for ( var childrenCounter = 1; childrenCounter <= numberOfChildren; childrenCounter++ ) {
		queryString += "&childrenAges=" + document.getElementById ( "childrenAge_" + childrenCounter ).value;
	}
	for ( var infantCounter = 1; infantCounter <= numberOfInfants; infantCounter++ ) {
		queryString += "&infantAges=" + document.getElementById ( "infantAge_" + infantCounter ).value;
	}
	queryString += "&someOneSenior=" + document.getElementById ( "isSomeOneSenior" ).checked;
	queryString += "&pastPassenger=" + document.getElementById ( "isPastPassenger" ).checked;
	if ( document.getElementById ( "isPastPassenger" ).checked ) {
		queryString += "&pastPassengerNumber=" + pastPassengerNumber;
	}
	queryString += "&residentCityCode=" + residentCityCode;

	disableElement ( 'dataContent' , true );
	makeAjaxCallWithWaitingDiv ( 'passengerInfo.act' , queryString , null , 'mainContent' , 'callbackProceedToCruiseCategorySearch' );
}

function callbackProceedToCruiseCategorySearch () {
	if ( ! ( showMessage ( this.errorMessage , this.errorCode , 'dataContent' ) ) ) {
		disableElement ( "dataContent" , false );
	}
}

function reLoadCruisePassengerDetailPage () {
	var queryString = "pi=2";

	disableElement ( 'dataContent' , true );
	makeAjaxCallWithWaitingDiv ( 'passengerInfo.act' , queryString , null , 'rightContent' , 'callbackReLoadCruisePassengerDetailPage' );
}

function callbackReLoadCruisePassengerDetailPage () {
	if ( ! ( showMessage ( this.errorMessage , this.errorCode , 'dataContent' ) ) ) {
		loadCruiseTripSummary ();
		disableElement ( "dataContent" , false );
	}
}

function updatePassengerInformationAndContinue () {
	clearErrorElements ();
	var jsonFormattedString = "";
	var numPax = parseInt ( document.getElementById ( "paxIndex" ).value );
	for ( var paxIndex = 0; paxIndex < numPax; paxIndex++ ) {
		var paxType = document.getElementById ( "paxType_" + paxIndex ).value;
		if ( ! ( validateDropDownField ( 'paxTitle_' + paxIndex , 'Please select a title for passenger No. ' + ( paxIndex + 1 ) , 'paxTitle_' + paxIndex + '_div' ) ) ) {
			return false;
		}
		if ( ! ( validateField ( 'paxFirstName_' + paxIndex , 'Please enter first name for passenger No. ' + ( paxIndex + 1 ) ) ) ) {
			return false;
		}
		if ( ! ( validateField ( 'paxLastName_' + paxIndex , 'Please enter last name for passenger No. ' + ( paxIndex + 1 ) ) ) ) {
			return false;
		} else  {
			 var lastNameField = document.getElementById ( "paxLastName_" + paxIndex );
			 var lastNameLength = lastNameField.value.length;
			 if ( lastNameLength < 2 ) {
			 	if( ! ( validateTextLength( lastNameField, 2) ) ) {
			 		return false;
			 	}
			 } 	
		}
		if ( ! ( validateField ( 'paxDateOfBirth_' + paxIndex , 'Please enter date of birth for passenger No. ' + ( paxIndex + 1 ) ) ) ) {
			return false;
		}
		if ( ! ( validateDropDownField ( 'paxCitizenship_' + paxIndex , 'Please enter citizenship country for passenger No. ' + ( paxIndex + 1 ) , 'paxCitizenship_' + paxIndex + '_div' ) ) ) {
			return false;
		}
		if ( ! ( calculateAge( paxIndex ) ) ) {
			return false;
		}
		var paxId = document.getElementById ( "paxId_" + paxIndex ).value;
		var paxTitle = document.getElementById ( "paxTitle_" + paxIndex ).value;
		var paxFirstName = document.getElementById ( "paxFirstName_" + paxIndex ).value;
		var paxMedInitial = document.getElementById ( "paxMedInitial_" + paxIndex ).value;
		var paxLastName = document.getElementById ( "paxLastName_" + paxIndex ).value;
		var paxSuffix = document.getElementById ( "paxSuffix_" + paxIndex ).value;
		var paxDateOfBirth = document.getElementById ( "paxDateOfBirth_" + paxIndex ).value;
		var paxGender = document.getElementById ( "paxGender_" + paxIndex ).value;
		var paxCitizenship = document.getElementById ( "paxCitizenship_" + paxIndex ).value;
		var frequentTravellerNumber = document.getElementById ( "pastPassengerNumber_" + paxIndex ).value;
		var frequentTravellerId = document.getElementById ( "frequentTravellerId_" + paxIndex ).value;
		var cruiseLineCode = document.getElementById ( "cruiseLineCode" ).value;

		jsonFormattedString += "{'paxId':" + "'" + paxId + "',";
		jsonFormattedString += "'paxType':" + "'" + paxType + "',";
		jsonFormattedString += "'paxTitle':" + "'" + paxTitle + "',";
		jsonFormattedString += "'paxFirstName':" + "'" + paxFirstName + "',";
		jsonFormattedString += "'paxMedInitial':" + "'" + paxMedInitial + "',";
		jsonFormattedString += "'paxLastName':" + "'" + paxLastName + "',";
		jsonFormattedString += "'paxSuffix':" + "'" + paxSuffix + "',";
		jsonFormattedString += "'paxDateOfBirth':" + "'" + paxDateOfBirth + "',";
		jsonFormattedString += "'paxGender':" + "'" + paxGender + "',";		
		jsonFormattedString += "'paxCitizenship':" + "'" + paxCitizenship + "',";
		jsonFormattedString += "'cruiseLineCode':" + "'" + cruiseLineCode + "',";
		jsonFormattedString += "'pastPassengerNumber':" + "'" + frequentTravellerNumber + "',";
		jsonFormattedString += "'frequentTravellerId':" + "'" + frequentTravellerId + "'},";
	}
	if ( ! document.getElementById ( "termsAndConditions" ).checked ) {
		showErrorMessage ( 'Please check terms and conditions' , 'dataContent' , 'termsAndConditionsDiv' , '#7f9db9' );
		return false;
	}
	jsonFormattedString = "{'PASSENGER_INFO':[" + jsonFormattedString.substring ( 0 , jsonFormattedString.lastIndexOf ( "," ) ) + "]}";
	var queryString = 'pi=6';
	queryString += "&passengerDetail=" + jsonFormattedString;

	asynchronousRequest = new AsynchronousRequest ();
	asynchronousRequest.url = _webLoc + '/passengerInfo.act';
	asynchronousRequest.queryString = queryString;
	asynchronousRequest.useAjax = true;
	asynchronousRequest.target = 'rightContent';
	asynchronousRequest.callbackFunctionName = 'callbackUpdatePassengerInformationAndContinue';

	var splashScreenRequest = new SplashScreenRequest ();
	splashScreenRequest.splashScreenText = "Please Wait...";
	asynchronousRequest.splashScreenRequest = splashScreenRequest;
	asynchronousRequest.splashScreenDisplayFunctionName = "displaySearchingPopup";
	asynchronousRequest.splashScreenHideFunctionName = "hideSearchingPopup";

	disableElement ( 'dataContent' , true );
	makeAjaxCallWithRequest ( asynchronousRequest , '' );
}

function callbackUpdatePassengerInformationAndContinue ( message, errorCode ) {
	disableElement ( 'dataContent' , false );
	showMessage ( message , errorCode , 'dataContent' );
	return true;}

function reLoadCruisePassengerDetails(){
	var queryString = "pi=5";
	disableElement ( 'dataContent' , true );
	makeAjaxCallWithWaitingDiv ( 'passengerInfo.act' , queryString , null , 'rightContent' , 'callbackReLoadCruisePassengerDetails' );
}

function callbackReLoadCruisePassengerDetails(){
	if ( ! ( showMessage ( this.errorMessage , this.errorCode , 'dataContent' ) ) ) {
		loadCruiseTripSummary ();
		disableElement ( "dataContent" , false );
	}
}

function setGenderByTitle(paxIndex){
	var title = document.getElementById("paxTitle_" + paxIndex).value;
	
	if (title == "Mr." || title == "Master"){
		document.getElementById("paxGender_" + paxIndex)[1].selected = true;	
	}	
	else if (title == "Ms." || title == "Mrs." || title == "Miss"){
		document.getElementById("paxGender_" + paxIndex)[2].selected = true;	
	}	
	else{
		document.getElementById("paxGender_" + paxIndex)[0].selected = true;
	}	
}
function calculateAge( paxIndex ){
	clearErrorElements();
	var paxType = document.getElementById("paxType_" + paxIndex).value;
	if( ! ( validateDOB( 'paxDateOfBirth_' + paxIndex, 'dataContent', paxType ) )  ) {
		return false;
	}
	var dateOfBirthField = document.getElementById( "paxDateOfBirth_" + paxIndex );
	var dateOfBirth = new Date( dateOfBirthField.value );
	if( !isNaN( dateOfBirth ) ) {
		var referenceDate = new Date( _referenceDate );
		var oneYear = 1000*60*60*24*365; 
		var oneMonth = 1000*60*60*24*30;
		var age = "";
		var ageInMonths = "";
		age = Math.floor( ( referenceDate.getTime() - dateOfBirth.getTime() ) / oneYear );
		if ( paxType == 1 || paxType == 2 ) {
			ageInMonths = Math.floor( (referenceDate.getTime() - dateOfBirth.getTime() ) / oneMonth );
		}
		if( paxType == 0 ){
			if(  age < 18 ){
				showErrorMessage( "Please verify that the date of birth entered for this passenger is correct. The age does not match the type for passenger No. " + ( parseInt( paxIndex ) + 1 ), 'dataContent', trim( 'paxDateOfBirth_' + paxIndex ) , '1px solid #7f9db9' );
				dateOfBirthField.focus();
				dateOfBirthField.select();
				return false;
			}
		}else if( paxType == 1 ){
			if( ! ( ageInMonths > 23 && age < 18 ) ){
				showErrorMessage( "Please verify that the date of birth entered for this passenger is correct. The age does not match the type for passenger No. " + ( parseInt( paxIndex )  + 1 ), 'dataContent', trim( 'paxDateOfBirth_' + paxIndex ) , '1px solid #7f9db9' );
				dateOfBirthField.focus();
				dateOfBirthField.select();
				return false;
			}
		}else {
			if( ageInMonths > 23 ){
				showErrorMessage( "Please verify that the date of birth entered for this passenger is correct. The age does not match the type for passenger No. " + ( parseInt( paxIndex )  + 1 ), 'dataContent', trim( 'paxDateOfBirth_' + paxIndex ), '1px solid #7f9db9' );
				dateOfBirthField.focus();
				dateOfBirthField.select();
				return false;
			}
		}
	}
	return true;	
}var _packageId;
var _modifySearchOptions = false;

function createBooking() {
	var queryString = 'b=2';
	var activity = "booking.act";
	
	var addTripProtectionCheckBox = document.getElementById( "addTripProtectionCheckbox" );
	var declineTripProtectionCheckBox = document.getElementById( "declineTripProtectionCheckbox" );
	if(addTripProtectionCheckBox!=null	&&	addTripProtectionCheckBox!= undefined	&&	declineTripProtectionCheckBox!=null	&&	declineTripProtectionCheckBox!=undefined)
	{
		if(addTripProtectionCheckBox.checked == false && declineTripProtectionCheckBox.checked ==false)
		{
			showErrorMessage('Please add or decline Trip Protection.', 'tripProtectionPopupDivContainer', 'addTripProtectionCheckBox', '1px solid #7f9db9');
			return false;
		}
		
	}
	
	removeElement( 'tripProtectionPopupDivContainer' );
	disableElement( 'dataContent', true );
	asynchronousRequest = new AsynchronousRequest();
	asynchronousRequest.url = _webLoc + '/' + activity;
	asynchronousRequest.queryString = queryString;
	asynchronousRequest.useAjax = true;
	asynchronousRequest.target = 'mainContent';
	asynchronousRequest.callbackFunctionName = 'callbackCreateBooking';

	var splashScreenRequest = new SplashScreenRequest();
	splashScreenRequest.splashScreenText = "Please Wait...";
	asynchronousRequest.splashScreenRequest = splashScreenRequest;
	asynchronousRequest.splashScreenDisplayFunctionName = "displaySearchingPopup";
	asynchronousRequest.splashScreenHideFunctionName = "hideSearchingPopup";
	//Make Ajax call with '/vp/booking/bookingRecap/<destinationCode>/<regionCode>/<packageId>' as the description to be passed into Google Analytics'
	makeAjaxCallWithRequest( asynchronousRequest, '/vp/booking/bookingRecap/' + _destinationCode + '/' + _regionCode + '/package/' + _packageId);
}

function callbackCreateBooking() {
	disableElement( 'dataContent', false );
	showMessage( this.errorMessage, this.errorCode, 'dataContent' );
	return true;
}

function loadBookingRecap() {
	var queryString = 'b=1';
	//Make Ajax call with '/vp/booking/bookingRecap/<destinationCode>/<regionCode>/<packageId>' as the description to be passed into Google Analytics'
	var trackingText = '/vp/booking/bookingRecap/' + _destinationCode + '/' + _regionCode + '/package/' + _packageId;
	makeAjaxCall( 'booking.act', queryString, null, 'mainContent', 'callbackLoadBookingRecap', trackingText );
}

function callbackLoadBookingRecap() {
	showMessage( this.errorMessage, this.errorCode, 'dataContent' );
	return true;
}

function loadBooking( bookingId ) {
	var queryString = 'b=8';
	queryString += '&bookingId=' + bookingId;	
	//Making Ajax call with '/vp/booking/itinerary' as the description to be passed into Google Analytics
	makeAjaxCall( 'booking.act', queryString, null, 'rightContent', 'callbackLoadBooking', '/vp/booking/itinerary' );
}

function callbackLoadBooking() {
	showMessage( this.errorMessage, this.errorCode, 'dataContent' );
	return true;
}

function addTripProtection() {
	var queryString = 'b=9';
	makeAjaxCallWithWaitingDiv( 'booking.act', queryString, null, 'tripProtectionAndPricingSummaryDiv', 'callbackAddTripProtection' );
}

function callbackAddTripProtection() {
	showMessage( this.errorMessage, this.errorCode, 'dataContent' );
	return true;
}

function removeTripProtection() {
	var queryString = 'b=10';
	makeAjaxCallWithWaitingDiv( 'booking.act', queryString, null, 'tripProtectionAndPricingSummaryDiv', 'callbackRemoveTripProtection' );
}

function callbackRemoveTripProtection() {
	showMessage( this.errorMessage, this.errorCode, 'dataContent' );
	return true;
}

function clearBookingResultObjectFromSession( fromWidget, showPopup, packageId, modifySearchOptions ){
	if( modifySearchOptions == undefined ){
		_modifySearchOptions = false;
	}
	var queryString;
	_packageId = packageId;
	if( showPopup == 'true' ) {
		_modifySearchOptions = modifySearchOptions;	
		queryString = 'b=13';
		makeAjaxCall( 'booking.act', queryString, null, 'rightContent', 'callbackShowPopup', '' );
	} else {
		queryString = 'lc=4&lbc=1&rc=23';
		queryString += '&fromWidget=true';
		
		//Submit Ajax call with '/vp/booking/searchWidget/<destinationCode>/<regionCode>' as the description to be passed into Google Analytics
		//The three '/' are put on purpose as place holders to retain the general format
		var trackingText = '/vp/booking/searchWidget/' + _destinationCode + '/' + _regionCode;
		searchAllPackagesForDestinationAndRegion(queryString, false, trackingText);
	}
}

function callbackShowPopup( isSuccessfull ) {
	if( isSuccessfull != "true" ) {
		showMessage( this.errorMessage, this.errorCode, 'dataContent' );			
	} else {
		if( !_modifySearchOptions ) {
			var searchPopupDivContainer = document.getElementById('searchPopupDivContainer');
			if ( searchPopupDivContainer != undefined || searchPopupDivContainer != null ) {
				showHiddenSearchPopup();
			}
		}else {
			initiatePackageSearch( _packageId , false );
		}
	}
	return true;
}

function createTripProtectionDetailsDiv(disabledBaseElement) {
	var tripProtectionDetailsPopupDiv = document.getElementById('tripProtectionDetailsPopupDiv');
	if(!tripProtectionDetailsPopupDiv){
		tripProtectionDetailsPopupDiv = createPopupDiv('tripProtectionDetailsPopupDiv', 0, 0, 700, 300, false, true,  "tal popupDivBig");
	}
	tripProtectionDetailsPopupDiv.disabledBaseElement = disabledBaseElement;
}

function loadTripProtectionDetailsFromTripProtectionPopup() {
	disableElement('tripProtectionPopupDivContainer', true);
	createTripProtectionDetailsDiv('tripProtectionPopupDivContainer');
	makeAjaxCall('booking/tripProtectionDetailsPopup.jsp', 'tripProtection=true', null, 'tripProtectionDetailsPopupDiv', 'callbackLoadTripProtectionDetailsFromTripProtectionPopup', '');	
}

function callbackLoadTripProtectionDetailsFromTripProtectionPopup() {
	document.title = "Costco Travel";	
	showBlock('tripProtectionDetailsPopupDiv');
	positionBlockCentrally('tripProtectionDetailsPopupDiv'); 
}

function loadCruiseTripProtectionDetails() {
	disableElement('cruiseTripProtectionPopupDivContainer', true );
	createTripProtectionDetailsDiv('cruiseTripProtectionPopupDivContainer');
	makeAjaxCall('booking/tripProtectionDetailsPopup.jsp', 'tripProtection=true', null, 'tripProtectionDetailsPopupDiv', 'callbackLoadCruiseTripProtectionDetails', '');	
}

function callbackLoadCruiseTripProtectionDetails() {
	document.title = "Costco Travel";	
	showBlock('tripProtectionDetailsPopupDiv'); 
	positionBlockCentrally('tripProtectionDetailsPopupDiv'); 
}

function loadTripProtectionDetailsFromBookingRecap() {
	createTripProtectionDetailsDiv('dataContent');
	disableElement('dataContent', true);
	makeAjaxCall('booking/tripProtectionDetailsPopup.jsp', 'tripProtection=true', null, 'tripProtectionDetailsPopupDiv', 'callbackLoadTripProtectionDetailsFromBookingRecap', '');	
}

function callbackLoadTripProtectionDetailsFromBookingRecap() {
	document.title = "Costco Travel";	
	showBlock('tripProtectionDetailsPopupDiv'); 
	positionBlockCentrally('tripProtectionDetailsPopupDiv'); 
}

function hideTripProtectionDetails() {
	var tripProtectionDetailsPopupDiv = document.getElementById('tripProtectionDetailsPopupDiv');
	
	if(tripProtectionDetailsPopupDiv) {
		disableElement( tripProtectionDetailsPopupDiv.disabledBaseElement, false );		
	}
	hideBlock( 'tripProtectionDetailsPopupDiv' ); 
}

function loadCardIdNumberDetailsPopup() {
	var cardIdNumberDetailsPopupDiv = document.getElementById('cardIdNumberDetailsPopupDiv');
	if(!cardIdNumberDetailsPopupDiv){
		cardIdNumberDetailsPopupDiv = createPopupDiv('cardIdNumberDetailsPopupDiv', 0, 0, 700, 300, false, true,  "tal popupDivBig");
	}
	disableElement('dataContent', true);
	makeAjaxCall('booking/cardIdNumberDetailsPopup.jsp', 'cardIdNumberDetails=true', null, 'cardIdNumberDetailsPopupDiv', 'callbackLoadCardIdNumberDetailsPopup', '');	
}

function callbackLoadCardIdNumberDetailsPopup() {
	document.title = "Costco Travel";	
	showBlock('cardIdNumberDetailsPopupDiv'); 
	positionBlockCentrally('cardIdNumberDetailsPopupDiv'); 
}

function loadTaxesAndFeesPopup() {
	var taxesAndFeesPopupDiv = document.getElementById('taxesAndFeesPopupDiv');
	if(!taxesAndFeesPopupDiv){
		taxesAndFeesPopupDiv = createPopupDiv('taxesAndFeesPopupDiv', 0, 0, 700, 300, false, true,  "tal popupDivBig");
	}
	disableElement('dataContent', true);
	makeAjaxCall('booking/taxesAndFeesPopup.jsp', 'taxesAndFeesPopup=true', null, 'taxesAndFeesPopupDiv', 'callbackLoadTaxesAndFeesPopup', '');	
}

function callbackLoadTaxesAndFeesPopup() {
	document.title = "Costco Travel";	
	showBlock('taxesAndFeesPopupDiv'); 
	positionBlockCentrally('taxesAndFeesPopupDiv'); 
}
function onKeyDownOnTripProtectionPopup( event ){
	if ( event && event.keyCode == 13 ){
		var tripProtectionPopupDiv = document.getElementById( "tripProtectionPopupDiv" );
		if ( tripProtectionPopupDiv != undefined ){
			createBooking();
		}
	}
}

function printItinerary(bookingId) {
	var queryString = 'b=16';
	queryString += '&bookingId='+ bookingId;
	makeAjaxCall( 'booking.act', queryString, null, 'rightContent', 'callbackPrintItinerary', '/home/rightContentHome.jsp' );
}

function callbackPrintItinerary( attachmentName ,attachmentPath ){
	window.open( _webLoc + "/booking/emailDownLoadAttachment.jsp?attachmentName="+attachmentName+"&attachmentPath="+attachmentPath,"_blank","alwaysLowered=true,width=800,height=500,resizable,scrollbars,left=80,top=80");		

}
function emailItinerary( bookingId ){
	var emailItineraryPopupDiv = document.getElementById( 'emailItineraryPopupDiv' );
	if( isNull( emailItineraryPopupDiv ) ) {
		emailItineraryPopupDiv = createPopupDiv('emailItineraryPopupDiv', 0, 0, 400, 200, false, true,  "tal popupDivSmall");
		emailItineraryPopupDiv.style.height = "100"; 
	}
	
	// create action code to open email itinerary pop up.
	var queryString = 'b=17';
	queryString += '&bookingId='+ bookingId;
	makeAjaxCall( 'booking.act', queryString, null, 'emailItineraryPopupDiv', 'callbackEmailItinerary', '/home/rightContentHome.jsp' );
}

function callbackEmailItinerary(){
	positionBlockCentrally('emailItineraryPopupDiv');
	showBlock('emailItineraryPopupDiv');
	disableElement('dataContent', true);
	var emailIdField = document.getElementById( "emailId" );
	if( emailIdField != null && emailIdField != undefined ) {
		emailIdField.focus();
	}
	return true;
}

function sendEmailItinerary( bookingId ){
	clearErrorElements();
	var queryString = 'b=18';
	var emailId = document.getElementById("emailId").value;
	if( emailId == "" ){
		showErrorMessage('Please enter email address.', 'emailItineraryPopupDivContainer', 'emailId', '1px solid #7f9db9');
		return;
	}
	if( !( validateEmail( 'emailId','emailItineraryPopupDivContainer' ) ) ) {
		disableElement( 'emailItineraryPopupDivContainer', true );
		return false;
	}
	queryString += '&bookingId='+ bookingId;
	queryString += '&emailId='+ emailId;
	makeAjaxCall( 'booking.act', queryString, null, 'emailItineraryPopupDivContainer', 'callbackSendEmailItinerary', '/home/rightContentHome.jsp' );
}

function callbackSendEmailItinerary(successMessage){
	removeElement( 'emailItineraryPopupDiv' );
	if(!showMessage( this.errorMessage, this.errorCode, 'dataContent' )) {
		showMessage( successMessage, null, 'dataContent');
	}
	return true;
}

function forgotPassword() {
	var queryString = 'md=6';
	var membershipId = document.getElementById( "membershipNumber" ).value; 
	 if( membershipId == "" ) {
    	showErrorMessage('Please enter member number', 'dataContent', 'membershipId', '1px solid #7f9db9');
    	return;
    }
	queryString += '&membershipNumber='+ membershipId;
	makeAjaxCall( 'membershipDetail.act', queryString, null, 'rightContent', 'callbackForgotPassword', '/home/rightContentHome.jsp' );
}

function callbackForgotPassword( message ) {	
	if(!showMessage( this.errorMessage, this.errorCode, 'dataContent' )) {
		showGeneralMessage(message, 'dataContent');
	}
	return true;
}

function changePassword() {
	var currentPassword = document.getElementById( "currentPassword" ).value;
	var newPassword = document.getElementById( "newPassword" ).value;
	var confirmNewPassword = document.getElementById( "confirmNewPassword" ).value;
	
	if( currentPassword == "" ){
		showErrorMessage('Please enter your current password', 'dataContent', 'currentPassword', '1px solid #7f9db9');
		return;
	}
	if( newPassword == "" ){
		showErrorMessage('Please enter your new password ', 'dataContent', 'newPassword', '1px solid #7f9db9');
		return;
	}
	if( confirmNewPassword == "" ){
		showErrorMessage('Please confirm your new password', 'dataContent', 'confirmNewPassword', '1px solid #7f9db9');
		return;
	}
	if( newPassword != confirmNewPassword ){
		showErrorMessage('Passwords do not match. Please type your password again and confirm it', 'dataContent', 'newPassword', '1px solid #7f9db9');					
		return;
	}
	
	var queryString = 'md=7';
	queryString += '&newPassword='+ newPassword;
	queryString += '&password='+ currentPassword;
	makeAjaxCall( 'membershipDetail.act', queryString, null, 'rightContent', 'callbackChangePassword', '/home/rightContentHome.jsp' );
}

function callbackChangePassword( message ) {
	if(!showMessage( this.errorMessage, this.errorCode, 'dataContent' )){
		showGeneralMessage(message, 'dataContent');
		showHideChangePasswordDiv();
	}
	return true;
}

function changeEmailId() {
	var currentEmailId = trim( document.getElementById( "currentEmailId" ).value );
	var newEmailId = trim( document.getElementById( "newEmailId" ).value );
	var confirmNewEmailId = trim( document.getElementById( "confirmNewEmailId" ).value );
	if( currentEmailId == "" ){
		showErrorMessage('Please enter current email address.', 'dataContent', 'currentEmailId', '1px solid #7f9db9');
		return;
	}
	if( newEmailId == "" ){
		showErrorMessage('Please enter new email address.', 'dataContent', 'newEmailId', '1px solid #7f9db9');
		return;
	}
	if( confirmNewEmailId == "" ){
		showErrorMessage('Please confirm email address.', 'dataContent', 'confirmNewEmailId', '1px solid #7f9db9');
		return;
	}
	if( !( validateEmail( 'currentEmailId', 'dataContent') ) ) {
		return false;
	}
	if( !( validateEmail( 'newEmailId', 'dataContent' ) ) ) {
		return false;
	}
	if( !( validateEmail( 'confirmNewEmailId', 'dataContent' ) ) ) {
		return false;
	}
	if( newEmailId != confirmNewEmailId ){
		showErrorMessage('The e-mail address you entered does not match your confirmed e-mail address. Please try again.', 'dataContent', 'newEmailId', '1px solid #7f9db9');					
		return;
	}
	var queryString = 'md=8';
	queryString += '&emailId='+ currentEmailId;
	queryString += '&newEmailId='+ newEmailId;
	makeAjaxCall( 'membershipDetail.act', queryString, null, 'rightContent', 'callbackChangeEmailId', '/home/rightContentHome.jsp' );
}

function callbackChangeEmailId( message ) {
	if( !showMessage( this.errorMessage, this.errorCode, 'dataContent' ) ){
		showGeneralMessage(message, 'dataContent');
		showHideChangeEmailIdDiv();
		return true;
	}
}

function showHideChangePasswordDiv() {
	clearErrorElements();
	expandCollaspeUpDown( '','changePasswordUserDiv' );
	clearField( 'currentPassword' );
	clearField( 'newPassword' );
	clearField( 'confirmNewPassword' );
	document.getElementById( 'changeEmailUserDiv' ).style.display = 'none';
}

function showHideChangeEmailIdDiv() {
	clearErrorElements();
	expandCollaspeUpDown( '','changeEmailUserDiv' );
	clearField( 'currentEmailId' );
	clearField( 'newEmailId' );
	clearField( 'confirmNewEmailId' );
	document.getElementById( 'changePasswordUserDiv' ).style.display = 'none';
}

function clearField( fieldName ) {
	document.getElementById( fieldName ).value = "";;
}

// display the booking ids for perticular member
function loadBookingsOfMember( ) {
	clearErrorElements();
	var userType;
	var userTypes = document.getElementsByName( "userType" );	
	for( i = 0; i < userTypes.length; i++ ) {
	if( userTypes[i].checked == true ) {
		userType =  userTypes[i].id;
		if( userTypes[i].id == "firstTimeUser" ) {
		var memberId = trim( document.getElementById( "firstTimeUserMemberId" ).value );
		var lastName = trim( document.getElementById( "lastName" ).value );
		var emailId = trim( document.getElementById( "emailId" ).value );
		var confirmEmailId = trim( document.getElementById( "confirmEmailId" ).value );
		var password =  trim( document.getElementById( "firstTimeUserPassword" ).value );
		var confirmPassword = trim( document.getElementById( "confirmPassword" ).value );
		if( memberId == "" ) {
			showErrorMessage('Please enter membership number', 'dataContent', 'firstTimeUserMemberId', '1px solid #7f9db9');
			return;
		}
		if( lastName == "" ) {
			showErrorMessage('Please enter last name', 'dataContent', 'lastName', '1px solid #7f9db9');
			return;
		}
		if( emailId == "" ) {
			showErrorMessage('Please enter your e-mail address.', 'dataContent', 'emailId', '1px solid #7f9db9');
			return;
 		}
		if( confirmEmailId == "" ) {
			showErrorMessage('Please confirm your e-mail address', 'dataContent', 'confirmEmailId', '1px solid #7f9db9');
			return;
		}
		if( !( validateEmail( 'emailId' , 'dataContent') ) ) {
			return false;
		}
		if( !( validateEmail( 'confirmEmailId', 'dataContent' ) ) ) {
			return false;
		}
		if( emailId != confirmEmailId ) {
			showErrorMessage( 'Email Addresses do not match, please re-type email id(s)', 'dataContent', 'emailId', '1px solid #7f9db9' );
			return;
		}
		if( password == "" ) {
			showErrorMessage( 'Please enter a password', 'dataContent', 'firstTimeUserPassword', '1px solid #7f9db9' );
			return;
		}
		if( confirmPassword == "" ) {
			showErrorMessage( 'Please confirm password', 'dataContent', 'confirmPassword', '1px solid #7f9db9' );					
			return;
		}
		if( password != confirmPassword ) {
			showErrorMessage( 'Passwords do not match, please re-type passwords', 'dataContent', 'firstTimeUserPassword', '1px solid #7f9db9' );					
			return;
		}
    	var queryString = 'md=10';
		queryString += '&userType=' + userType;
		queryString += '&membershipNumber=' + memberId;
		queryString += '&lastName=' + lastName;
		queryString += '&password=' + password;
		queryString += '&emailId=' + emailId;
		} else {
			var membershipId = document.getElementById( "membershipNumber" ).value;  
			var password = document.getElementById( "password" ).value; 
			if( membershipId == "" ) {
				showErrorMessage('Please enter member number', 'dataContent', 'membershipNumber', '1px solid #7f9db9');
				return;
			}
			if( password == "" ){
				showErrorMessage('Please enter a password', 'dataContent', 'password', '1px solid #7f9db9');
				return;
			}
			var queryString = 'md=3';
			queryString += '&membershipNumber=' + membershipId;
			queryString += '&password=' + password;
			queryString += '&retrieveBooking=true'
	        }
	 	}
	 }			
	asynchronousRequest = new AsynchronousRequest();
	asynchronousRequest.url = _webLoc + '/membershipDetail.act';
	asynchronousRequest.queryString = queryString;
	asynchronousRequest.useAjax = true;
	asynchronousRequest.target = 'rightContent';
	asynchronousRequest.callbackFunctionName = 'callbackValidateMemberNumber';

	var splashScreenRequest = new SplashScreenRequest();
	splashScreenRequest.splashScreenText = "Please Wait...";
	asynchronousRequest.splashScreenRequest = splashScreenRequest;
	asynchronousRequest.splashScreenDisplayFunctionName = "displaySearchingPopup";
	asynchronousRequest.splashScreenHideFunctionName = "hideSearchingPopup";
	
	disableElement( 'dataContent', true);
	makeAjaxCallWithRequest(asynchronousRequest, '');	
	//makeAjaxCall( 'membershipDetail.act', queryString, null, 'rightContent', 'callbackLoadBookingsOfMember','' );
}

function callbackLoadBookingsOfMember() {
	if (!this.errorCode || this.errorCode ==""){
		document.getElementById("logoutDiv").style.display = "block";
	} else {
		document.getElementById("logoutDiv").style.display = "none";
	} 
	if( this.errorMessage != undefined ){
		document.getElementById( "password" ).value = "";
		document.getElementById( "membershipNumber" ).focus();
		showMessage( this.errorMessage, this.errorCode, 'dataContent' );		
	}
	else {
		disableElement( 'dataContent', false);
	}
	return true;	
}

function validateMemberNumber( isCruiseFlow ) {
	clearErrorElements();
	var fromYourItinerary = document.getElementById( "fromYourItinerary" ).value;
	if( fromYourItinerary == "true" ){
		loadBookingsOfMember();
	} else {
		var queryString = ''; 
		var userType;
		var userTypes = document.getElementsByName( "userType" );	
		for( i = 0; i < userTypes.length; i++ ) {
			if( userTypes[i].checked == true ) {
			    userType =  userTypes[i].id;
			    if( userTypes[i].id == "firstTimeUser" ) {
				    var memberId = trim( document.getElementById( "firstTimeUserMemberId" ).value );
					var lastName = trim( document.getElementById( "lastName" ).value );
					var emailId = trim( document.getElementById( "emailId" ).value );
					var confirmEmailId = trim( document.getElementById( "confirmEmailId" ).value );
					var password =  trim( document.getElementById( "firstTimeUserPassword" ).value );
					var confirmPassword = trim( document.getElementById( "confirmPassword" ).value );
					if( memberId == "" ) {
						showErrorMessage('Please enter membership number', 'dataContent', 'firstTimeUserMemberId', '1px solid #7f9db9');
						return;
					}
					if( lastName == "" ) {
						showErrorMessage('Please enter last name', 'dataContent', 'lastName', '1px solid #7f9db9');
						return;
					}
					if( emailId == "" ) {
						showErrorMessage('Please enter your e-mail address.', 'dataContent', 'emailId', '1px solid #7f9db9');
						return;
			 		}
					if( confirmEmailId == "" ) {
						showErrorMessage('Please confirm your e-mail address', 'dataContent', 'confirmEmailId', '1px solid #7f9db9');
						return;
					}
					if( !( validateEmail( 'emailId', 'dataContent' ) ) ) {
						return false;
					}
					if( !( validateEmail( 'confirmEmailId', 'dataContent' ) ) ) {
						return false;
					}
					if( emailId != confirmEmailId ) {
						showErrorMessage( 'Email Addresses do not match, please re-type email id(s)', 'dataContent', 'emailId', '1px solid #7f9db9' );
						return;
					}
					if( password == "" ) {
						showErrorMessage( 'Please enter a password', 'dataContent', 'firstTimeUserPassword', '1px solid #7f9db9' );
						return;
					}
					if( confirmPassword == "" ) {
						showErrorMessage( 'Please confirm password', 'dataContent', 'confirmPassword', '1px solid #7f9db9' );					
						return;
					}
					if( password != confirmPassword ) {
						showErrorMessage( 'Passwords do not match, please re-type passwords', 'dataContent', 'firstTimeUserPassword', '1px solid #7f9db9' );					
						return;
					}
			    	var queryString = 'md=4';
					queryString += '&userType=' + userType;
					queryString += '&membershipNumber=' + memberId;
					queryString += '&lastName=' + lastName;
					queryString += '&password=' + password;
					queryString += '&emailId=' + emailId;
					queryString += '&cruiseFlow=' + isCruiseFlow;
				} else {
					if( document.getElementById( "membershipNumber" ).value == "" ) {
						showErrorMessage( 'Please enter membership number', 'dataContent', 'membershipNumber', '1px solid #7f9db9' );
						return;
					}
					if( document.getElementById( "password" ).value == "" ) {
						showErrorMessage( 'Please enter a password', 'dataContent', 'password', '1px solid #7f9db9' );
						return;
					}
					queryString = 'md=3';
					queryString += '&membershipNumber=' + document.getElementById( "membershipNumber" ).value;
					queryString += '&password=' + document.getElementById( "password" ).value;
					queryString += '&userType='+ userType;
					queryString += '&cruiseFlow=' + isCruiseFlow;
				}
			}
		}
		
		asynchronousRequest = new AsynchronousRequest();
		asynchronousRequest.url = _webLoc + '/membershipDetail.act';
		asynchronousRequest.queryString = queryString;
		asynchronousRequest.useAjax = true;
		asynchronousRequest.target = 'rightContent';
		asynchronousRequest.callbackFunctionName = 'callbackValidateMemberNumber';
	
		var splashScreenRequest = new SplashScreenRequest();
		splashScreenRequest.splashScreenText = "Please Wait...";
		asynchronousRequest.splashScreenRequest = splashScreenRequest;
		asynchronousRequest.splashScreenDisplayFunctionName = "displaySearchingPopup";
		asynchronousRequest.splashScreenHideFunctionName = "hideSearchingPopup";
		
		disableElement( 'dataContent', true);
		var trackingText = '';
		
		if (isCruiseFlow){
			//Submit Ajax call with '/vp/booking/bookingWidget/passengerDetails/<destination>/<cruiseLine>/<shipName>/<departureDate>' as the description to be passed into Google Analytics
			trackingText = '/vp/booking/bookingWidget/passengerDetails/' + _destinationName + '/' + _cruiseLineName + '/' + _shipName + '/' + _departureDate;
		}
		else{
			//Submit Ajax call with '/vp/booking/passengerDetails/<destinationCode>/<regionCode>/package/<packageId>' as the description to be passed into Google Analytics
			trackingText = '/vp/booking/passengerDetails/' + _destinationCode + '/' + _regionCode + '/package/' + _packageId;
		}
		
		makeAjaxCallWithRequest(asynchronousRequest, trackingText);		
		//makeAjaxCall( 'membershipDetail.act', queryString, null, 'rightContent', 'callbackValidateMemberNumber', '' );
  }
}

function callbackValidateMemberNumber() {	
	if (!this.errorCode || this.errorCode ==""){
		document.getElementById("logoutDiv").style.display = "block";
		document.getElementById("yourItinerary").innerHTML = "Your Account";
	} else {
		document.getElementById("logoutDiv").style.display = "none";
		document.getElementById("yourItinerary").innerHTML = "Login";
	} 
	if( this.errorMessage != undefined ){
		document.getElementById( "confirmPassword" ).value == "";
		document.getElementById( "firstTimeUserPassword" ).value == "";
		document.getElementById( "password" ).value == "";
		showMessage( this.errorMessage, this.errorCode, 'dataContent' );		
	}else {
		disableElement( 'dataContent', false);
	}
	return true;
}

function showHideMemberDiv() {
	var isFirstTimeUserTypeSelected = document.getElementById( "firstTimeUser" ).checked;
	if( isFirstTimeUserTypeSelected ) {
		document.getElementById( "returningUserDiv" ).style.display = "none";
		document.getElementById( "firstTimeUserDiv" ).style.display = "block";
		document.getElementById( "errorMessage" ).style.display = "none";
		document.getElementById( "optionsDiv" ).style.display = "none";
	} else {
	    document.getElementById( "firstTimeUserDiv" ).style.display = "none";
	    document.getElementById( "returningUserDiv" ).style.display = "block";
	    document.getElementById( "errorMessage" ).style.display = "none";
	    document.getElementById( "optionsDiv" ).style.display = "inline";
	    if( document.getElementById( "passwordHeader" ).style.display == "none" ){
			document.getElementById( "passwordHeader" ).style.display = "block";
		}
		if( document.getElementById( "password" ).style.display == "none" ){
			document.getElementById( "password" ).style.display = "block";
		}	
	}
}

function memberLogout() {
	var queryString = 'md=5';
	makeAjaxCall( 'membershipDetail.act', queryString, null, 'mainContent', 'callbackMemberLogout', '' );
}

function callbackMemberLogout() {
	return true;
}

function disableCtrlKeyCombination( e , t ) {
	var forbiddenKeys = new Array('c','v');
	var key;
	var isCtrl;
	if( window.event ){
	key = window.event.keyCode;     //IE
	    if( window.event.ctrlKey )
	        isCtrl = true;
	        else
	        isCtrl = false;
	 } else {
	 	key = e.which;     //firefox
	    if( e.ctrlKey )
	    	isCtrl = true;
	    else
	    	isCtrl = false;
	}
	  //if ctrl is pressed check if other key is in forbidenKeys array
	if( isCtrl ){
		for( i = 0; i < forbiddenKeys.length; i++ ){
		    //case-insensitive comparation
			if( forbiddenKeys[i].toLowerCase() == String.fromCharCode( key ).toLowerCase()) {
			    return false;
			}
		} 
	}
	if( key == 13 && t.id == "confirmPassword" ){
		validateMemberNumber();
		return false;
	}
	return true;
}

function checkEnterKey( event , cruiseFlow ) {
	if( isEnterKey( event ) ) {
		validateMemberNumber( cruiseFlow );
		return false;
	}
}
function loadPassengerInformation( ) {
	var queryString = 'pi=0';
	//Make Ajax call with '/vp/booking/passengerDetails/<destinationCode>/<regionCode>/<packageId>' as the description to be passed into Google Analytics'
	var trackingText = '/vp/booking/passengerDetails/' + _destinationCode + '/' + _regionCode + '/package/' + _packageId;
	makeAjaxCall( 'passengerInfo.act', queryString, null, 'rightContent', 'callbackLoadPassengerInformation', trackingText );
}

function callbackLoadPassengerInformation() {
	showMessage( this.errorMessage, this.errorCode, 'dataContent' );
	return true;
}

function assignPassengersToBooking() {
	clearErrorElements();
	var passengerArray = [];
	var numPax = parseInt( document.getElementById( "paxIndex" ).value );
	var bookingHasValidFlights = (document.getElementById("bookingHasValidFlights").value == "true");
	var trackingText;
	for( var paxIndex = 0 ; paxIndex < numPax ; paxIndex++ ) {
		var paxType = document.getElementById( "paxType_" + paxIndex ).value;		
		if( !( validateField( 'paxTitle_' + paxIndex , 'Please select a title for passenger No. ' + ( paxIndex + 1 ) ) ) ) {
			return false;
		}
		if( !( validateField( 'paxFirstName_' + paxIndex , 'Please enter first name for passenger No. ' + ( paxIndex + 1 ) ) ) ) {
			return false;
		}
		if( !( validateField( 'paxLastName_' + paxIndex , 'Please enter last name for passenger No. ' + ( paxIndex + 1 ) ) ) ) {
			return false;
		}
		if( !( validateField( 'paxGender_' + paxIndex , 'Please enter gender for passenger No. ' + ( paxIndex + 1 ) ) ) ) {
			return false;
		}
		
		var paxId = document.getElementById( "paxId_" + paxIndex ).value;
		var paxTitle = document.getElementById( "paxTitle_" + paxIndex ).value;
		var paxFirstName = document.getElementById( "paxFirstName_" + paxIndex ).value;
		var paxMedInitial = document.getElementById( "paxMedInitial_" + paxIndex ).value;
		var paxLastName = document.getElementById( "paxLastName_" + paxIndex ).value;
		var paxSuffix = document.getElementById( "paxSuffix_" + paxIndex ).value;
		
		var paxGenderField = document.getElementById( "paxGender_" + paxIndex );
		var paxGender = paxGenderField!= null ? paxGenderField.value: null;
		var paxDateOfBirthField = document.getElementById( "paxDateOfBirth_" + paxIndex );
		var paxDateOfBirth = paxDateOfBirthField != null ? paxDateOfBirthField.value : null;

		var paxAge = 0;
		if(document.getElementById( "paxAge_" + paxIndex )) {
			paxAge = document.getElementById( "paxAge_" + paxIndex ).value;
		} else if(paxType == 0) {
			paxAge = -1;
		} 		
		
		var passengerObject = {
				paxId: paxId,
				paxType: paxType,
				paxTitle: paxTitle,
				paxFirstName: paxFirstName,
				paxMedInitial: paxMedInitial,
				paxLastName: paxLastName,
				paxSuffix: paxSuffix,
				paxDateOfBirth: paxDateOfBirth,
				paxAge: paxAge
			};		
		if(paxGenderField != null) {
			passengerObject.paxGender = paxGender;
		}
		
		passengerArray[paxIndex] = passengerObject;
	}
	if( !document.getElementById( "termsAndConditions").checked ) {
		showErrorMessage('To proceed with booking, you must read and accept the Terms and Conditions', 'dataContent', 'termsAndConditions', '1px solid #7f9db9');
		return false;
	}
	
	var jsonFormattedString = {PASSENGER_INFO: passengerArray}.toJSONString();	
	var queryString = 'pi=1';
	queryString += "&passengerDetail=" + jsonFormattedString;
	
	asynchronousRequest = new AsynchronousRequest();
	asynchronousRequest.url = _webLoc + '/passengerInfo.act';
	asynchronousRequest.queryString = queryString;
	asynchronousRequest.useAjax = true;
	asynchronousRequest.target = 'rightContent';
	asynchronousRequest.callbackFunctionName = 'callbackAssignPassengersToBooking';

	var splashScreenRequest = new SplashScreenRequest();
	splashScreenRequest.splashScreenText = "Please Wait...";
	asynchronousRequest.splashScreenRequest = splashScreenRequest;
	asynchronousRequest.splashScreenDisplayFunctionName = "displaySearchingPopup";
	asynchronousRequest.splashScreenHideFunctionName = "hideSearchingPopup";
	
	disableElement( 'dataContent', true);

	if (bookingHasValidFlights == true){
		//Make Ajax call with '/vp/booking/flightSeatSelection/<destinationCode>/<regionCode>/<packageId>' as the description to be passed into Google Analytics'
		trackingText = '/vp/booking/flightSeatSelection/' + _destinationCode + '/' + _regionCode + '/package/' + _packageId;
	}	
	else {	
		//Make Ajax call with '/vp/booking/specialRequests/<destinationCode>/<regionCode>/<packageId>' as the description to be passed into Google Analytics'
		trackingText = '/vp/booking/specialRequests/' + _destinationCode + '/' + _regionCode + '/package/' + _packageId;
	}	
	
	makeAjaxCallWithRequest(asynchronousRequest, trackingText);
	//makeAjaxCall( 'passengerInfo.act', queryString, null, 'rightContent', 'callbackAssignPassengersToBooking', '' );	
}

function callbackAssignPassengersToBooking( message, errorCode ) {
	disableElement('dataContent', false);
	showMessage( message, errorCode, 'dataContent' );
	return true;
}

function loadTitleAndSuffix( title, suffix ) {
	var titleArray = title.split(",");
	var suffixArray = suffix.split(",");
	var numPax = parseInt( document.getElementById( "paxIndex" ).value );
	var titleAndSuffixFlag = false;
	var paxIndex = 0;
	for( var titleIndex = 0 ; titleIndex <titleArray.length-1; titleIndex++ ) {
	titleAndSuffixFlag = false
		for(  ; paxIndex <numPax; paxIndex++ ) {
				for ( var index =0 ;index < document.getElementById( "paxTitle_" + paxIndex ).options.length; index++ ) {
					if (document.getElementById("paxTitle_"+paxIndex).options[index].value == titleArray[titleIndex] ) {
						document.getElementById("paxTitle_"+paxIndex).options[index].selected = true;
						titleAndSuffixFlag = true;
						paxIndex++;			
					}
					if( titleAndSuffixFlag )break;
				}
				if( titleAndSuffixFlag )break;
		}
	}
	paxIndex = 0;
	for( var suffixIndex = 0 ; suffixIndex <suffixArray.length-1; suffixIndex++ ) {
	titleAndSuffixFlag = false
		for(  ; paxIndex <numPax; paxIndex++ ) {
				for ( var index =0 ;index < document.getElementById( "paxSuffix_" + paxIndex ).options.length; index++ ) {
					if (document.getElementById("paxSuffix_"+paxIndex).options[index].value == suffixArray[suffixIndex] ) {
						document.getElementById("paxSuffix_"+paxIndex).options[index].selected = true;
						titleAndSuffixFlag = true;
						paxIndex++;			
					}
					if( titleAndSuffixFlag )break;
				}
				if( titleAndSuffixFlag )break;
		}
	}	
}

function validateDOBForFlights(){
	var numPax = parseInt( document.getElementById( "paxIndex" ).value );
	if (document.getElementById("bookingHasValidFlights")){
		var bookingHasValidFlights = (document.getElementById("bookingHasValidFlights").value == "true");
	
		if (bookingHasValidFlights){
			for( var paxIndex = 0 ; paxIndex < numPax ; paxIndex++ ) {
				if (document.getElementById( "paxDateOfBirth_" + paxIndex )){
					paxDateOfBirth = document.getElementById( "paxDateOfBirth_" + paxIndex ).value;
					if (paxDateOfBirth == '' || paxDateOfBirth == 'mm/dd/yyyy'){
						document.getElementById("dobWarning").style.display = "block";
					}	
					else{
						document.getElementById("dobWarning").style.display = "none";
					}	
				}
			}	
		}	
	}
	return true;
}var _flightSeatMap = new Array();
var _flightSegmentItemUids = new Array();
var _passengerInfoArray = new Array();

var _passengerCount = 0;
var _flightSegmentItemUid= "";
var _seatPreference = 0;


function FlightPassengerSeatInfo(flightSegmentItemUid, passengerId, seatNumber){
	this.flightSegmentItemUid = flightSegmentItemUid;
	this.passengerId = passengerId;
	this.seatNumber = seatNumber;
}

function PassengerSeatInfo(passengerId, title, firstName, lastName, middleInitial, suffix, seatNumber){
	this.title = title;
	this.passengerId = passengerId;
	this.firstName = firstName;
	this.lastName = lastName;
	this.middleInitial = middleInitial;
	this.suffix = suffix;
	this.seatNumber = seatNumber;
}


function getPassengersInfo()
{	
	createPassengerInfoArray();
	return _passengerInfoArray;
}

function getNextPassengerId(currentPassengerId) {
	nextPassengerId = currentPassengerId;
	nextPassengerId = (nextPassengerId + 1) % _passengerCount;	
	return nextPassengerId;
}

function selectSeat(passengerSeatInfo) {	
	var passengerId = getSelectedPassengerId();
	var seatNumber = passengerSeatInfo.seatNumber;
	var seatNumberElement = document.getElementById("passengerSeatNumber" + passengerId);
	var selectedFlightSegmentItemUid = document.getElementById("selectedFlightSegmentItemUid").value;
	_passengerInfoArray[passengerSeatInfo.passengerId] = passengerSeatInfo;	
	if(seatNumberElement != null) {
	 	setInnerText(seatNumberElement, seatNumber);
	 	setSeatNumber(selectedFlightSegmentItemUid, passengerId, seatNumber);	 	
	 }
	 	 
	 var nextPassengerId = getNextPassengerId(passengerId);
	 selectPassenger(nextPassengerId);
}

function highlightPassenger(passengerId) {
	var passengerNameTrElement = document.getElementById("passengerNameTr"+ passengerId);
	passengerNameTrElement.className = "b bgc05";
} 

function deHighlightPassenger(passengerId) {
	var passengerNameTrElement = document.getElementById("passengerNameTr"+ passengerId);
	passengerNameTrElement.className = "nob";
}

function onSelectPassenger(passengerId) {
	var passengerInfo = _passengerInfoArray[passengerId];
	var seatMapObj = document.getElementById("seatMap"); 
	if(seatMapObj && seatMapObj.getCurrentPassengerInfo) {
		seatMapObj.getCurrentPassengerInfo(passengerInfo);
	}
	selectPassenger(passengerId);
}

function selectPassenger(passengerId) {	
	for(var i=0; i<_passengerCount; i++) {
 		if(i != passengerId) {
 			deHighlightPassenger(i)
 		}
 		highlightPassenger(passengerId);
	} 
	
	var optionElements = document.getElementsByName("radioPassengerName");
	if(optionElements && optionElements.length) {
		for(var i=0; i<_passengerCount; i++) {
			if(i != passengerId) {
 				optionElements[i].checked = false;
 			}
 			else {
 				optionElements[i].checked = true;
 			}
		} 
	 }
}

function createPassengerInfoArray() {
	_passengerInfoArray = new Array();
	for(var i=0; i<_passengerCount; i++) {
		var passengerTitle = getInnerText(document.getElementById("passengerTitle" + i));
		var passengerFirstName = getInnerText(document.getElementById("passengerFirstName" + i));
		var passengerMiddleInitials = getInnerText(document.getElementById("passengerMiddleInitials" + i));
		var passengerLastName = getInnerText(document.getElementById("passengerLastName" + i));
		var passengerSuffix = getInnerText(document.getElementById("passengerSuffix" + i));
		var seatNumber = getInnerText(document.getElementById("passengerSeatNumber" + i));
		_passengerInfoArray[i] = new PassengerSeatInfo(i, passengerTitle, passengerFirstName, passengerLastName, passengerMiddleInitials, passengerSuffix, seatNumber, '1');
	}
}

function populateSeatPassengerInfo(flightSegmentItemUid, passengerCount) { 
	_flightSegmentItemUid = flightSegmentItemUid;
	_passengerCount = passengerCount;	
	for(var i =0; i<passengerCount; i++) { 
		var seatNumber = getSeatNumber(flightSegmentItemUid, i); 
		if(seatNumber && seatNumber != "") {
			var seatNumberElement = document.getElementById("passengerSeatNumber" + i);	
			setInnerText(seatNumberElement, seatNumber);			
		}
	}
}

function populateSeatPassengerInfoFromJSON(passengerInfoJSON) { 	
	var flightSeatMapInfo = passengerInfoJSON.parseJSON();
	var flightSeatPassengerInfoArray = flightSeatMapInfo.flightPassengerSeatInfoArray;
	
	_flightSeatMap = new Array();	
	for(var i=0; i< flightSeatPassengerInfoArray.length; i++) {
	 	var flightPassengerSeatInfo = flightSeatPassengerInfoArray[i];
	 	setSeatNumber(flightPassengerSeatInfo.flightSegmentItemUid, flightPassengerSeatInfo.passengerId, flightPassengerSeatInfo.seatNumber);	 		 	 	
	}

	_flightSegmentItemUids = flightSeatMapInfo.flightSegmentItemUidArray;
	chooseSeatPreference(_seatPreference);
}

function validateAndAssignSeatsToPassengers() {
	var seatMapObj = document.getElementById("seatMap"); 
	var isSeatMapObjPresent = seatMapObj && seatMapObj.getCurrentPassengerInfo;	
	if(!isSeatMapObjPresent || !isSeatsPreferred() || areSeatsSelectedForAllFlights()) {
		assignSeatsToPassengers();
	}else {
		loadFlightSeatMapErrorPopupDiv();
	}
}

function loadFlightSeatMapErrorPopupDiv() {
	var flightSeatMapErrorPopupDiv = document.getElementById('flightSeatMapErrorPopupDiv');
	if(flightSeatMapErrorPopupDiv == null){
		flightSeatMapErrorPopupDiv = createPopupDiv('flightSeatMapErrorPopupDiv', 0, 0, 450, 500, false, true,  "popupDivSmall tal")
		//flightSeatMapErrorPopupDiv = document.createElement('DIV');
		//flightSeatMapErrorPopupDiv.id = 'flightSeatMapErrorPopupDiv';
		//flightSeatMapErrorPopupDiv.style.display = "none"; 
		//flightSeatMapErrorPopupDiv.style.position = "absolute";
		//flightSeatMapErrorPopupDiv.style.width = "450";
		//flightSeatMapErrorPopupDiv.style.zIndex = "500";
		//flightSeatMapErrorPopupDiv.className="popupDivSmall tal";
		//flightSeatMapErrorPopupDiv.innerHTML = '';
		//flightSeatMapErrorPopupDiv.onmouseover = function( event ) { setDragEvent( 'flightSeatMapErrorPopupDiv', event ) };
		//document.body.insertBefore( flightSeatMapErrorPopupDiv, document.body.firstChild );
	}
	makeAjaxCall('booking/flightSeatMapErrorPopup.jsp', 'flightSeatMapErrorPopup=true', null, 'flightSeatMapErrorPopupDiv', 'callbackLoadFlightSeatMapErrorPopupDiv');
}

function callbackLoadFlightSeatMapErrorPopupDiv() {
	document.title = "Costco Travel";	
	showBlock('flightSeatMapErrorPopupDiv'); 
	positionBlockCentrally('flightSeatMapErrorPopupDiv'); 
	disableElement( 'dataContent', true );
}

function hideFlightSeatMapErrorPopupDiv() {
	hideBlock('flightSeatMapErrorPopupDiv');
	disableElement( 'dataContent', false);
}


function isSeatsPreferred() {
	var radioSeatPreferenceOption = document.getElementsByName("radioSeatPreference");
	return radioSeatPreferenceOption[1].checked;		
}

function getSelectedPassengerId() {
	 var optionElements = document.getElementsByName("radioPassengerName");
	 if(optionElements && optionElements.length) {
	 	for(var i=0; i< optionElements.length; i++) {
	 		if(optionElements[i].checked) {
	 			return i;
	 		}
	 	}
	 }
	 return 0;
}

function assignSeatsToPassengers() {	
	var queryString = 'smc=3';
	var flightSeatPassengerInfoList = new Array();
	var ctr = 0;
	for (var key in _flightSeatMap) {
		var flightPassengerInfo = key.split("_");
		if(flightPassengerInfo.length ==2) {
			var seatNumber = _flightSeatMap[key];			
			flightSeatPassengerInfoList[ctr] = new FlightPassengerSeatInfo(flightPassengerInfo[0], flightPassengerInfo[1], seatNumber);
			ctr++; 
		}
	}
	queryString+= '&flightSeatMapInfoJSON=' + flightSeatPassengerInfoList.toJSONString();
	queryString+= '&seatsPreferred=' + isSeatsPreferred();
	//Make Ajax call with '/vp/booking/specialRequests/<destinationCode>/<regionCode>/<packageId>' as the description to be passed into Google Analytics'
	var trackingText = '/vp/booking/specialRequests/' + _destinationCode + '/' + _regionCode + '/package/' + _packageId;
	makeAjaxCall( 'seatMapContent.act', queryString, null, 'rightContent', 'callbackAssignSeatsToPassengers', trackingText );
}

function callbackAssignSeatsToPassengers( message, errorCode ) {
	showMessage( message, errorCode, 'dataContent' );
	return true;
}

function areSeatsSelectedForAllFlights() {
	for(var i=0; i< _flightSegmentItemUids.length; i++) {
		for(var j=0; j<_passengerCount; j++) {
			var seatNumber= getSeatNumber(_flightSegmentItemUids[i] , j);
			if(!seatNumber || seatNumber=='') {
				return false;
			}
		} 
	}
	return true;
}

function loadFlightSeatMapPopupDiv(flightItemUid, selectedAirline, isForLIP ) {
	var flightSeatMapPopupDiv = document.getElementById('flightSeatMapPopupDiv');
	if(flightSeatMapPopupDiv == null){
		flightSeatMapPopupDiv = createPopupDiv('flightSeatMapPopupDiv', 0, 0, 700, 204, false, true,  "tal popupDivBig")
		//flightSeatMapPopupDiv = document.createElement('DIV');
		//flightSeatMapPopupDiv.id = 'flightSeatMapPopupDiv';
		//flightSeatMapPopupDiv.style.display = "none"; 
		//flightSeatMapPopupDiv.style.position = "absolute";
		//flightSeatMapPopupDiv.style.width = "700";
		//flightSeatMapPopupDiv.style.zIndex = "200";
		//flightSeatMapPopupDiv.className="tal popupDivBig";
		//flightSeatMapPopupDiv.innerHTML = '';
		//flightSeatMapPopupDiv.onmouseover = function( event ) { setDragEvent( 'flightSeatMapPopupDiv', event ) };
		//document.body.insertBefore( flightSeatMapPopupDiv, document.body.firstChild );
	}
	makeAjaxCall('seatMapContent.act', 'flightItemUid='+flightItemUid +'&selectedAirline='+selectedAirline + '&forLIP=' + isForLIP , null, 'flightSeatMapPopupDiv', 'callbackLoadFlightSeatMapPopupDiv');
}

function callbackLoadFlightSeatMapPopupDiv() {
	document.title = "Costco Travel";	
	showBlock('flightSeatMapPopupDiv'); 
	positionBlockCentrally('flightSeatMapPopupDiv'); 
	disableElement( 'dataContent', true );
	var additionalSearchResultsPopup = document.getElementById( 'additionalSearchResultsPopupDivContainer' );
	if( additionalSearchResultsPopup) { 
		disableElement('additionalSearchResultsPopupDivContainer', true);
	}
}

function loadFlightSeatMapContent(flightItemUid, flightSegmentItemUid, forLIP) {
	makeAjaxCall('seatMapContent.act', 'flightItemUid='+flightItemUid+'&flightSegmentItemUid='+flightSegmentItemUid + '&forLIP='+forLIP, null, 'flightSeatMapPopupDiv', 'callbackLoadFlightSeatMapContent');
}

function callbackLoadFlightSeatMapContent() {
	document.title = "Costco Travel";
}

function loadFlightSeatMapSelection(bookingFlightSegmentItemUid, smc) {
	var queryString = 'smc=' + smc;
	if(bookingFlightSegmentItemUid !=null) {
		queryString+= '&bookingFlightSegmentItemUid='+bookingFlightSegmentItemUid;
	}
	makeAjaxCall('seatMapContent.act', queryString, null, 'seatSelectionDiv', 'callbackLoadFlightSeatMapSelection');
}

function callbackLoadFlightSeatMapSelection() {
	document.title = "Costco Travel";
}

function loadFlightSeatMapForBooking() {
	var queryString = 'smc=6';
	var trackingText;
	var bookingHasValidFlights = (document.getElementById("bookingHasValidFlights").value == "true");

	if (bookingHasValidFlights == true){
		//Make Ajax call with '/vp/booking/flightSeatSelection/<destinationCode>/<regionCode>/<packageId>' as the description to be passed into Google Analytics'
		trackingText = '/vp/booking/flightSeatSelection/' + _destinationCode + '/' + _regionCode + '/package/' + _packageId;
	}	
	else {	
		//Make Ajax call with '/vp/booking/passengerDetails/<destinationCode>/<regionCode>/<packageId>' as the description to be passed into Google Analytics'
		trackingText = '/vp/booking/passengerDetails/' + _destinationCode + '/' + _regionCode + '/package/' + _packageId;
	}	
	
	makeAjaxCall('seatMapContent.act', queryString, null, 'rightContent', 'callbackLoadFlightSeatMapForBooking', trackingText);
}

function callbackLoadFlightSeatMapForBooking() {
	document.title = "Costco Travel";
}

function chooseSeatPreference(seatPreference) {
	_seatPreference = seatPreference;
	var radioSeatPreferenceOption = document.getElementsByName("radioSeatPreference");
	if(seatPreference == 0) {
		hideBlock('seatSelectionDiv');
		showBlock('passengerInfoDiv');		
		radioSeatPreferenceOption[0].checked = true;
		radioSeatPreferenceOption[1].checked = false;
	}else if(seatPreference == 1) {
		showBlock('seatSelectionDiv');
		hideBlock('passengerInfoDiv');
		radioSeatPreferenceOption[0].checked = false;
		radioSeatPreferenceOption[1].checked = true;
	}
}

function getSeatNumber(flightSegmentItemUid, passengerId) {
	return _flightSeatMap[flightSegmentItemUid + "_" + passengerId];
}

function setSeatNumber(flightSegmentItemUid, passengerId, seatNumber) {
	_flightSeatMap[flightSegmentItemUid + "_" + passengerId] = seatNumber;
}


function getInnerText(element) {
	if(isIE()) {
		return element.innerText;
	} else {
		return element.textContent;
	}
}
function setInnerText(element, innerText) {
	if(isIE()) {
		element.innerText = innerText;
	} else {
		element.textContent = innerText;	
	}
}
var maxCreditCards;
var numberOfCreditCards;
var isSchedulePayment;
var isFirstTime;
var numberOfCreditCardsForScheduledPayment;
var numberOfCreditCardsForFullPayment;
var _paymentMode;
var _divIndex;
var _grossAmount;
var _depositAmount;
var _minDepositAmount;
var _isDisplayForCreditCard = true; // This flag is used to display the details like credit card, month and year to scheduled payment objects;
var _isDisplayForShippingAddress = true; // This flag is used to display the details like credit card, month and year to scheduled payment objects;
var _creditCardsAmount;
var _scheduledDate;
var _previousDepositAmount;
var _isCruiseItemIncluded;

function createPayment() {
	clearErrorElements();
	var jsonFormattedString = "";
	var jsonShippingAddress ="";

	var street1 = document.getElementById( "street1").value;
	var street2 = document.getElementById( "street2").value;
	var city = document.getElementById( "city").value;
	var state = document.getElementById( "state").value;
	var country = document.getElementById( "country").value;
	var zip = document.getElementById( "zip").value;
	var primaryPhone = document.getElementById( "primaryPhoneStateCode").value + document.getElementById( "primaryPhoneCityCode").value + document.getElementById( "primaryPhone").value;
	var alternatePhone = document.getElementById( "alternatePhoneStateCode").value + document.getElementById( "alternatePhoneCityCode").value + document.getElementById( "alternatePhone").value;
	var alternatePhoneExtension = document.getElementById( "alternatePhoneExtension").value;
	var email = document.getElementById( "email").value;
	var alternateEmail = document.getElementById( "alternateEmail").value;
	var creditCardScheduledDate = document.getElementById( "creditCardScheduledDate_schedulePayment_0").value;
	var isPromotionApplied = document.getElementById( "isPromotionApplied" ).value;
	var promotionCode;
	var promotionAmount ;
	var isDepositModified
	if( isPromotionApplied == true ){
		 promotionCode = document.getElementById( "promotionCode").value;
		 promotionAmount = document.getElementById( "promotionAmount").value;
		 isDepositModified = document.getElementById( "isDepositModified" ).value;
	}
	
	if( !( validateField( 'street1' , 'Please enter street.' ) ) ) {
		return false;
	}
	if( !( validateField( 'city' , 'Please enter city.' ) ) ) {
		return false;
	}
	if( !( validateDropDownField( 'state' , 'Please select a state.','stateSelectionDiv' ) ) ) {
		return false;
	}
	if( !( validateField( 'zip' , 'Please enter valid zip.' ) ) ) {
		return false;
	}
	if( !( validateField( 'primaryPhoneStateCode' , 'Please enter valid primary phone.' ) ) ) {
		return false;
	}
	if( !( validateField( 'primaryPhoneCityCode' , 'Please enter valid primary phone.' ) ) ) {
		return false;
	}
	if( !( validateField( 'primaryPhone' , 'Please enter valid primary phone.' ) ) ) {
		return false;
	}
	
	if( !( validatePhoneNumber( 'primaryPhoneStateCode', 'primaryPhoneCityCode', 'primaryPhone', 'Please enter a valid ten digits primary phone number' ) ) ) {
		return false;
	}
	
	/*
	if( !( validateField( 'email' , 'Please enter your e-mail address.' ) ) ) {
		return false;
	}
	*/
	// alternate email id is optional field.
	if( document.getElementById( 'alternateEmail' ).value != "" ) {
		if( !( validateEmail( 'alternateEmail') ) ) {
			return false;
		}
	}

	jsonShippingAddress += "'street1':" + "'" + street1 + "',";
	jsonShippingAddress += "'street2':" + "'" + street2 + "',";
	jsonShippingAddress += "'city':" + "'" + city + "',";
	jsonShippingAddress += "'state':" + "'" + state + "',";
	jsonShippingAddress += "'country':" + "'" + country + "',";
	jsonShippingAddress += "'zip':" + "'" + zip + "',";
	jsonShippingAddress += "'primaryPhone':" + "'" + primaryPhone + "',";
	jsonShippingAddress += "'alternatePhone':" + "'" + alternatePhone + "',";
	jsonShippingAddress += "'alternatePhoneExtension':" + "'" + alternatePhoneExtension + "',";
	jsonShippingAddress += "'email':" + "'" + email + "',";
	jsonShippingAddress += "'alternateEmail':" + "'" + alternateEmail + "',";
	jsonShippingAddress += "'isSchedulePayment':" + "'" + isSchedulePayment + "',";
	jsonShippingAddress += "'creditCardScheduledDate':" + "'" + creditCardScheduledDate + "',";
	jsonShippingAddress += "'isFirstTime':" + "'false',";
	jsonShippingAddress += "'_grossAmount':" + "'" + _grossAmount + "',";
	jsonShippingAddress += "'_depositAmount':" + "'" + _depositAmount + "',";
	jsonShippingAddress += "'isPaymentWithinDueDays':" + "'" + isPaymentWithinDueDays + "',";
	jsonShippingAddress += "'numberOfCreditCardsForFullPayment':" + "'" + numberOfCreditCardsForFullPayment + "',";
	jsonShippingAddress += "'numberOfCreditCardsForScheduledPayment':" + "'" + numberOfCreditCardsForScheduledPayment + "',";
	if( isPromotionApplied == "true" ){
		jsonShippingAddress += "'promotionCode':" + "'" + promotionCode + "',";
		jsonShippingAddress += "'promotionAmount':" + "'" + promotionAmount + "',";
		jsonShippingAddress += "'isPromotionExist':'true',";
		jsonShippingAddress += "'isDepositModified':" + "'" + isDepositModified + "',";
	}else{
		jsonShippingAddress += "'isPromotionExist':'false',";
	}
	for( var index =0; index < numberOfCreditCardsForFullPayment; index++ ) {
		jsonShippingAddress += "'fullPaymentCard" + index + "':" + "'" + document.getElementById( "sameAsBillingAddress_fullPayment_"+ index ).checked +   "',";
	}
	if( isSchedulePayment ) {
		for( var index =0; index < numberOfCreditCardsForScheduledPayment; index++ ) {
			jsonShippingAddress += "'scheduledPaymentCard" + index + "':" + "'" + document.getElementById( "sameAsBillingAddress_schedulePayment_"+ index ).checked +   "',";
		}
	}
	jsonShippingAddress = "'PAYMENT_ADDRESS':{" + jsonShippingAddress + "}";

	var creditCardNumber = "";
	var creditCardExpirationMonth = "";
	var creditCardExpirationYear = "";
	var creditCardAmount = "";
	var creditCardSecurityCode = "";
	var cardHolderName = "";
	var cardType ="";
	var currentDate = new Date();
	var currentMonth = currentDate.getMonth();
	var currentYear = currentDate.getFullYear();

	for ( var index = 0; index < numberOfCreditCardsForFullPayment; index++ ) {
		if( !( validateField( 'creditCardNumber_fullPayment_' + index , 'Please enter credit card number.' ) ) ) {
			return false;
		}
		if( !( validateDropDownField( 'creditCardExpirationMonth_fullPayment_' + index , 'Please enter credit card expiration month.', 'creditCardExpirationMonth_fullPayment_div_' + index ) ) ) {
			return false;
		}
		if( !( validateDropDownField( 'creditCardExpirationYear_fullPayment_' + index , 'Please enter credit card expiration year.', 'creditCardExpirationYear_fullPayment_div_' + index ) ) ) {
						return false;
		}
		creditCardExpirationMonth = document.getElementById( "creditCardExpirationMonth_fullPayment_"+index).value;
		creditCardExpirationYear = document.getElementById( "creditCardExpirationYear_fullPayment_"+index).value;
		if( creditCardExpirationYear < currentYear || ( ( currentYear == creditCardExpirationYear ) && creditCardExpirationMonth <= currentMonth ) ) {
			if ( creditCardExpirationYear < currentYear ) {
				showErrorMessage( 'Please enter valid expiration date.', 'dataContent', 'creditCardExpirationYear_fullPayment_div_' + index, '#7f9db9' );
			} else {
				showErrorMessage( 'Please enter valid expiration date.', 'dataContent', 'creditCardExpirationMonth_fullPayment_div_' + index, '#7f9db9' );				
			}
			return false;
		}
		if( !( validateField( 'creditCardAmount_fullPayment_' + index , 'Please enter valid amount.'  ) ) ) {
			return false;
		}
		creditCardAmount = document.getElementById( "creditCardAmount_fullPayment_"+index).value;
		if(!isFloat(creditCardAmount)) {
			showErrorMessage('Amount entered is not valid. Please enter a valid amount.', 'dataContent', 'creditCardAmount_fullPayment_'+index, '1px solid #7f9db9');
			return false;
		}
		if ( parseFloat(creditCardAmount) <= 0 ) {
			showErrorMessage('Amount cannot be zero. Please enter amount greater than zero.', 'dataContent', 'creditCardAmount_fullPayment_'+index, '1px solid #7f9db9');
			return false;
		}
		if ( isSchedulePayment ) {
			_minDepositAmount = parseFloat( _minDepositAmount ).toFixed(2)
			if ( parseFloat( creditCardAmount ) < _minDepositAmount ) {
				showErrorMessage('Deposit amount cannot be less than $'+ _minDepositAmount, 'dataContent', 'creditCardAmount_fullPayment_'+index, '1px solid #7f9db9');
				return false;
			}
		}
		if( !( validateField( 'creditCardSecurityCode_fullPayment_' + index , 'Please enter security number.'  ) ) ) {
			return false;
		}
		creditCardSecurityCode = document.getElementById( "creditCardSecurityCode_fullPayment_"+index).value;
		cardHolderName = document.getElementById( "creditCardHolderName_fullPayment_"+index).value;
		creditCardNumber = document.getElementById( "creditCardNumber_fullPayment_"+index).value;
		cardType = checkCreditCard( creditCardNumber );
		if(cardType == 'UNKNOWN') {
			showErrorMessage('The accepted forms of payment are Visa, MasterCard and American Express' + String.fromCharCode('174') +'.  Please try again using one of these credit cards.', 'dataContent', 'creditCardNumber_fullPayment_' + index, '1px solid #7f9db9');
			return false;
		}
		if ( creditCardSecurityCode.length < 3 || ( cardType == 'AmExCard' && creditCardSecurityCode.length < 4 )) {
			showErrorMessage('Please enter valid security number', 'dataContent', 'creditCardSecurityCode_fullPayment_'+index, '1px solid #7f9db9');
			return false;
		}
		if( !( validateField( 'creditCardHolderName_fullPayment_' + index , 'Please enter Card holder name.'  ) ) ) {
			return false;
		}
		if( !( validateField( 'street1_fullPayment_' + index , 'Please enter street.') ) ) {
			return false;
		}
		if( !( validateField( 'city_fullPayment_' + index, 'Please enter city.') ) ) {
			return false;
		}
		if( !( validateDropDownField( 'state_fullPayment_' + index, 'Please select a state.', 'state_fullPayment_selection_div_' + index ) ) ) {
			return false;
		}
		if( !( validateField( 'zip_fullPayment_' + index, 'Please enter zip.') ) ) {
			return false;
		}

		street1 = document.getElementById( "street1_fullPayment_"+index).value;
		street2 = document.getElementById( "street2_fullPayment_"+index).value;
		city = document.getElementById( "city_fullPayment_"+index).value;
		state = document.getElementById( "state_fullPayment_"+index).value;
		country = document.getElementById( "country_fullPayment_"+index).value;
		zip = document.getElementById( "zip_fullPayment_"+index).value;

		jsonFormattedString += "{'creditCardNumber':" + "'" + creditCardNumber + "',";
		jsonFormattedString += "'cardType':" + "'" + cardType + "',";
		jsonFormattedString += "'cardHolderName':" + "'" + cardHolderName + "',";
		jsonFormattedString += "'creditCardExpirationMonth':" + "'" + creditCardExpirationMonth + "',";
		jsonFormattedString += "'creditCardExpirationYear':" + "'" + creditCardExpirationYear + "',";
		jsonFormattedString += "'creditCardAmount':" + "'" + creditCardAmount + "',";
		jsonFormattedString += "'creditCardSecurityCode':" + "'" + creditCardSecurityCode + "',";
		jsonFormattedString += "'street1':" + "'" + street1 + "',";
		jsonFormattedString += "'street2':" + "'" + street2 + "',";
		jsonFormattedString += "'city':" + "'" + city + "',";
		jsonFormattedString += "'state':" + "'" + state + "',";
		jsonFormattedString += "'country':" + "'" + country + "',";
		jsonFormattedString += "'isSchedulePayment':" + "'false',";
		jsonFormattedString += "'zip':" + "'" + zip + "'},";
	}
	if ( isSchedulePayment ) {
		for ( var index = 0; index < numberOfCreditCardsForScheduledPayment; index++ ) {
			if( !( validateField( 'creditCardNumber_schedulePayment_' + index , 'Please enter credit card number.'  ) ) ) {
				return false;
			}
			if( !( validateDropDownField( 'creditCardExpirationMonth_schedulePayment_' + index , 'Please enter credit card expiration month.', 'creditCardExpirationMonth_schedulePayment_div_' + index ) ) ) {
				return false;
			}
			if( !( validateDropDownField( 'creditCardExpirationYear_schedulePayment_' + index , 'Please enter credit card expiration year.', 'creditCardExpirationYear_schedulePayment_div_' + index ) ) ) {
				return false;
			}
			creditCardExpirationMonth = document.getElementById( "creditCardExpirationMonth_schedulePayment_"+index).value;
			creditCardExpirationYear = document.getElementById( "creditCardExpirationYear_schedulePayment_"+index).value;
			if( creditCardExpirationYear < currentYear || ( ( currentYear == creditCardExpirationYear ) && creditCardExpirationMonth <= currentMonth ) ) {
				if ( creditCardExpirationYear < currentYear ) {
					showErrorMessage( 'Please enter valid expiration date.', 'dataContent', 'creditCardExpirationYear_schedulePayment_div_' + index, '#7f9db9' );
				} else {
					showErrorMessage( 'Please enter valid expiration date.', 'dataContent', 'creditCardExpirationMonth_schedulePayment_div_' + index, '#7f9db9' );				
				}
				return false;
			}
			var creditCardScheduledDate = new Date( document.getElementById( "creditCardScheduledDate_schedulePayment_"+index).value );
			if( ( ( creditCardScheduledDate != "" ) && ( creditCardScheduledDate != "mm/dd/yyyy" ) ) && ( ( _scheduledDate != "" ) && ( _scheduledDate != "mm/dd/yyyy" ) ) ) {
				var creditCardDate = new Date( creditCardScheduledDate );
				var scheduledDate = new Date( _scheduledDate );
				if ( creditCardDate > scheduledDate ) {
					var msg = "Schedule payment due date should not be greater than " + _scheduledDate;
					showErrorMessage( msg ,'dataContent', 'creditCardScheduledDate', '1px solid #7f9db9' );
					return false;
				}
			}
			currentMonth = creditCardScheduledDate.getMonth();
			currentYear = creditCardScheduledDate.getFullYear();
			if( creditCardExpirationYear < currentYear || ( ( currentYear == creditCardExpirationYear ) && creditCardExpirationMonth <= currentMonth ) ) {
				showErrorMessage( 'Expiration date cannot be less than scheduled date', 'dataContent', 'creditCardExpirationMonth_schedulePayment_div_' + index, '#7f9db9' );
				return false;
			}
			if( !( validateField( 'creditCardAmount_schedulePayment_' + index , 'Please enter valid amount.'  ) ) ) {
				return false;
			}
			if( !( validateField( 'creditCardScheduledDate_schedulePayment_' + index , 'Please enter schedule date.'  ) ) ) {
				return false;
			}
			if( !( validateField( 'creditCardHolderName_schedulePayment_' + index , 'Please enter name.'  ) ) ) {
				return false;
			}
			if( !( validateField( 'street1_schedulePayment_' + index , 'Please enter street.') ) ) {
				return false;
			}
			if( !( validateField( 'city_schedulePayment_' + index, 'Please enter city.') ) ) {
				return false;
			}
			if( !( validateDropDownField( 'state_schedulePayment_' + index, 'Please select a state.','state_schedulePayment_selection_div_'+ index ) ) ) {
				return false;
			}
			if( !( validateField( 'zip_schedulePayment_' + index, 'Please enter zip.') ) ) {
				return false;
			}
			creditCardNumber = document.getElementById( "creditCardNumber_schedulePayment_"+index).value;
			creditCardAmount = document.getElementById( "creditCardAmount_schedulePayment_"+index).value;
			if ( parseFloat(creditCardAmount) <= 0 ) {
				showErrorMessage('Amount cannot be zero. Please enter amount greater than zero.', 'dataContent', 'creditCardAmount_schedulePayment_'+index, '1px solid #7f9db9');
				return false;
			}
			creditCardSecurityCode = document.getElementById( "creditCardScheduledDate_schedulePayment_"+index).value;
			cardHolderName = document.getElementById( "creditCardHolderName_schedulePayment_"+index).value;
			cardType = checkCreditCard( creditCardNumber );
			if(cardType == 'UNKNOWN') {
				showErrorMessage('The accepted forms of payment are Visa, MasterCard and American Express' + String.fromCharCode('174') +'.  Please try again using one of these credit cards.', 'dataContent', 'creditCardNumber_schedulePayment_'+index, '1px solid #7f9db9');
				return false;
			}
			street1 = document.getElementById( "street1_schedulePayment_"+index).value;
			street2 = document.getElementById( "street2_schedulePayment_"+index).value;
			city = document.getElementById( "city_schedulePayment_"+index).value;
			state = document.getElementById( "state_schedulePayment_"+index).value;
			country = document.getElementById( "country_schedulePayment_"+index).value;
			zip = document.getElementById( "zip_schedulePayment_"+index).value;

			jsonFormattedString += "{'creditCardNumber':" + "'" + creditCardNumber + "',";
			jsonFormattedString += "'cardType':" + "'" + cardType + "',";
			jsonFormattedString += "'cardHolderName':" + "'" + cardHolderName + "',";
			jsonFormattedString += "'creditCardExpirationMonth':" + "'" + creditCardExpirationMonth + "',";
			jsonFormattedString += "'creditCardExpirationYear':" + "'" + creditCardExpirationYear + "',";
			jsonFormattedString += "'creditCardAmount':" + "'" + creditCardAmount + "',";
			jsonFormattedString += "'creditCardSecurityCode':" + "'" + creditCardSecurityCode + "',";
			jsonFormattedString += "'street1':" + "'" + street1 + "',";
			jsonFormattedString += "'street2':" + "'" + street2 + "',";
			jsonFormattedString += "'city':" + "'" + city + "',";
			jsonFormattedString += "'state':" + "'" + state + "',";
			jsonFormattedString += "'country':" + "'" + country + "',";
			jsonFormattedString += "'isSchedulePayment':" + "'true',";

			jsonFormattedString += "'zip':" + "'" + zip + "'},";


		}
	}
	if( !( validateCreditCardAmount( ) ) ) {
		return false;
	}
	jsonFormattedString = "{'CREDITCARD_INFO':[" + jsonFormattedString.substring( 0, jsonFormattedString.lastIndexOf( "," ) ) + "]," + jsonShippingAddress + " }";
	var queryString = 'pm=1';
	queryString += "&paymentDetail=" + jsonFormattedString;
	var trackingText = '';

	if (_isCruiseItemIncluded && _isCruiseItemIncluded == 'true'){
		//Load the review submit screen with '/cr/booking/bookingWidget/reviewSubmit/<destination>/<cruiseLine>/<ship>/<date>' as the description to be passed into Google Analytics
		trackingText = '/cr/booking/bookingWidget/reviewSubmit/' + _destinationName + '/' + _cruiseLineName + '/' + _shipName + '/' + _departureDate;
	}	
	else {
		//Make Ajax call with '/vp/booking/reviewSubmit/<destinationCode>/<regionCode>/<packageId>' as the description to be passed into Google Analytics'
		trackingText = '/vp/booking/reviewSubmit/' + _destinationCode + '/' + _regionCode + '/package/' + _packageId;
	}
	
	makeAjaxCall( 'payment.act', queryString, null, 'rightContent', 'callbackMakePayment', trackingText );
}

function callbackMakePayment( message, errorCode ) {
	showMessage( message, errorCode, 'dataContent' );
	return true;
}

function validateCreditCardAmount( ) {
	clearErrorElements();
	var totalCreditCardAmount = 0;
	var creditCardAmount;
	var depositAmount = document.getElementById( "depositAmount" ).value;
	depositAmount = parseFloat( depositAmount );
	_depositAmount = document.getElementById( "creditCardAmount_fullPayment_0" ).value;
	_depositAmount = parseFloat( _depositAmount );
	if(  _depositAmount < depositAmount ){
		numberOfCreditCardsForScheduledPayment = 0;
	}
	if ( isSchedulePayment ) {
			for ( var index = 0; index < numberOfCreditCardsForScheduledPayment; index++ ) {
			creditCardAmount = document.getElementById( "creditCardAmount_schedulePayment_" + index ).value;
			totalCreditCardAmount = parseFloat( totalCreditCardAmount + parseFloat( creditCardAmount ) );
		}
		for ( var index = 0; index < numberOfCreditCardsForFullPayment; index++ ) {
			creditCardAmount = document.getElementById( "creditCardAmount_fullPayment_"+index).value;
			totalCreditCardAmount = parseFloat( totalCreditCardAmount + parseFloat( creditCardAmount ) );
		}	
	} else {
		for ( var index = 0; index < numberOfCreditCardsForFullPayment; index++ ) {
			creditCardAmount = document.getElementById( "creditCardAmount_fullPayment_"+index).value;
			totalCreditCardAmount = parseFloat( totalCreditCardAmount + parseFloat( creditCardAmount ) );
		}
	}
	
	totalCreditCardAmount = parseFloat( totalCreditCardAmount ).toFixed(2);
	_grossAmount = parseFloat( _grossAmount ).toFixed(2);
	if ( totalCreditCardAmount < _grossAmount ) {
		showErrorMessage( 'You have entered payments totaling $' + totalCreditCardAmount + ' which is less than the total amount owed on your booking.', 'dataContent', 'creditCardAmount_fullPayment_0', '1px solid #7f9db9');
		return false;
	}
	if( totalCreditCardAmount > _grossAmount ) {
		showErrorMessage( 'You have entered payments totaling $' + totalCreditCardAmount + ' which is greater than the total amount owed on your booking.', 'dataContent', 'creditCardAmount_fullPayment_0', '1px solid #7f9db9');
		return false;

	}
	return true;
}

function displayCreditCardNumber( obj ) {
	if ( isFirstTime ) {
		if ( ( obj == document.getElementById( "creditCardNumber_schedulePayment_0" ) ) || ( obj == document.getElementById( "creditCardExpirationMonth_schedulePayment_0" ) ) || ( obj == document.getElementById( "creditCardExpirationYear_schedulePayment_0" ) ) ) {
			_isDisplayForCreditCard = false;
		} else if ( isSchedulePayment && _isDisplayForCreditCard ) {
			if ( obj == document.getElementById( "creditCardNumber_fullPayment_0" ) ) {
				document.getElementById( "creditCardNumber_schedulePayment_0" ).value = obj.value;
			} else if ( obj == document.getElementById( "creditCardExpirationMonth_fullPayment_0" ) ) {
				document.getElementById( "creditCardExpirationMonth_schedulePayment_0" ).value = obj.value;
			} else if ( obj == document.getElementById( "creditCardExpirationYear_fullPayment_0" ) ) {
				document.getElementById( "creditCardExpirationYear_schedulePayment_0" ).value = obj.value;
			}
		}
	}
}

function displayShippingAddress( obj, index ) {
	if ( ( obj == document.getElementById( "street1_fullPayment_"+index ) ) || ( obj == document.getElementById( "street2_fullPayment_"+index  ) ) || ( obj == document.getElementById( "city_fullPayment_"+index  ) ) || ( obj == document.getElementById( "state_fullPayment_"+index  ) ) || ( obj == document.getElementById( "country_fullPayment_"+index  ) )|| ( obj == document.getElementById( "zip_fullPayment_"+index  ) ) ) {
		_isDisplayForShippingAddress = false;
	} else if ( _isDisplayForShippingAddress ) {
		if ( obj == document.getElementById( "street1" ) ) {
			for( var count = 0; count < maxCreditCards; count++ )
			document.getElementById( "street1_fullPayment_"+count ).value = obj.value;
			for( var count = 0; count < numberOfCreditCardsForScheduledPayment; count++ )
			document.getElementById( "street1_schedulePayment_"+count ).value = obj.value;
		} else if ( obj == document.getElementById( "street2" ) ) {
			for( var count = 0; count < maxCreditCards; count++ )
			document.getElementById( "street2_fullPayment_"+count ).value = obj.value;
			for( var count = 0; count < numberOfCreditCardsForScheduledPayment; count++ )
			document.getElementById( "street2_schedulePayment_"+count ).value = obj.value;
		}  else if ( obj == document.getElementById( "city" ) ) {
			for( var count = 0; count < maxCreditCards; count++ )
			document.getElementById( "city_fullPayment_"+count ).value = obj.value;
			for( var count = 0; count < numberOfCreditCardsForScheduledPayment; count++ )
			document.getElementById( "city_schedulePayment_"+count ).value = obj.value;
		} else if ( obj == document.getElementById( "state" ) ) {
			for( var count = 0; count < maxCreditCards; count++ )
			document.getElementById( "state_fullPayment_"+count ).value = obj.value;
			for( var count = 0; count < numberOfCreditCardsForScheduledPayment; count++ )
			document.getElementById( "state_schedulePayment_"+count ).value = obj.value;
		} else if ( obj == document.getElementById( "country" ) ) {
			for( var count = 0; count < maxCreditCards; count++ )
			document.getElementById( "country_fullPayment_"+count ).value = obj.value;
			for( var count = 0; count < numberOfCreditCardsForScheduledPayment; count++ )
			document.getElementById( "country_schedulePayment_"+count ).value = obj.value;
		} else if ( obj == document.getElementById( "zip" ) ) {
			for( var count = 0; count < maxCreditCards; count++ )
			document.getElementById( "zip_fullPayment_"+count ).value = obj.value;
			for( var count = 0; count < numberOfCreditCardsForScheduledPayment; count++ )
			document.getElementById( "zip_schedulePayment_"+count ).value = obj.value;
		}
	}
}

function displayInitialShippingAddress( index, paymentType ) {
	if ( paymentType == 'FULL_PAYMENT' ) {
		loadStates( paymentType, index, 'sameAsShippingAddress' );
		document.getElementById( "street1_fullPayment_"+index ).value = document.getElementById( "street1" ).value
		document.getElementById( "street2_fullPayment_"+index ).value = document.getElementById( "street2" ).value
		document.getElementById( "city_fullPayment_"+index ).value = document.getElementById( "city" ).value
		document.getElementById( "state_fullPayment_"+index ).value = document.getElementById( "state" ).value
		document.getElementById( "country_fullPayment_"+index ).value = document.getElementById( "country" ).value
		document.getElementById( "zip_fullPayment_"+index ).value = document.getElementById( "zip" ).value
	} else 	if ( paymentType == 'SCHEDULED_PAYMENT' ) {
		loadStates( paymentType, index, 'sameAsShippingAddress' );
		document.getElementById( "street1_schedulePayment_"+index ).value = document.getElementById( "street1" ).value
		document.getElementById( "street2_schedulePayment_"+index ).value = document.getElementById( "street2" ).value
		document.getElementById( "city_schedulePayment_"+index ).value = document.getElementById( "city" ).value
		document.getElementById( "state_schedulePayment_"+index ).value = document.getElementById( "state" ).value
		document.getElementById( "country_schedulePayment_"+index ).value = document.getElementById( "country" ).value
		document.getElementById( "zip_schedulePayment_"+index ).value = document.getElementById( "zip" ).value
	}
}

function checkCreditCard ( cardnumber ) {
	// Array to hold the permitted card characteristics
	var cards = new Array();

	// Define the cards we support. You may add addtional card types.

	//  Name:      As in the selection box of the form - must be same as user's
	//  Length:    List of possible valid lengths of the card number for the card
	//  prefixes:  List of possible prefixes for the card

	cards [0] = {name: "VisaCard",
               length: "13,16",
               prefixes: "4"};
	cards [1] = {name: "MasterCard",
               length: "16",
               prefixes: "51,52,53,54,55"};
	cards [2] = {name: "AmExCard",
               length: "15",
               prefixes: "34,37"};
  	var len = cards.length;
  	// Have a variable that says whether the type matches or not.
  	var cardMatched = false;

  	//Index of the card type
 	var i=0 ;
  	for (;i< len && !cardMatched; ++i ) {
		// We use these for holding the valid lengths and prefixes of a card type
		var prefix = new Array ();
		// Load an array with the valid prefixes for this card
		prefix = cards[i].prefixes.split(",");
  		// An variable that holds the card type
		var index =0;
		// Now see if any of them match what we have in the card number
		for (; index<prefix.length; index++) {
			var expression = new RegExp ("^" + prefix[index]);
			if (expression.test (cardnumber)){
				cardMatched = true;
				break;
			}
		}
  	}

	//Decrement the counter by as it would have incremented once before breaking the loop.
	if ( cardMatched ) {
		i = parseInt (i-1) ;
	}

	if(cardMatched) {
	  	//Check if cardnumber has any non-digit characters
	  	var expression = new RegExp("\\D");
	  	if(expression.test(cardnumber)) {
			cardMatched = false;
	  	}
	}

	// Check if any of the patterns match in the card type array.
	if ( i < len && cardMatched) {
		var lengths = new Array ();
		// Load an array with all the valid lengths for this card
		lengths = cards[i].length.split(",");
		 // Check the length of the card
		 var cardNumberLenghtValid = false;
		//Check if the card size is the one which we have defined
		for (var l=0; l< lengths.length && !cardNumberLenghtValid;++l )	{
			if (parseInt (cardnumber.length) == parseInt (lengths[l]) ){
				cardNumberLenghtValid = true;
				break;
			}
		}

		if (cardNumberLenghtValid) {
			return cards[i].name;
		}
		else {
			return "UNKNOWN" ;
		}
	}
	else {
		return "UNKNOWN" ;
 	}
}

function showHideShippingAddressForFullPayment( obj, index ) {
	if ( obj.checked ) {
		displayInitialShippingAddress( index , 'FULL_PAYMENT');
		_isDisplayForShippingAddress = true;
		document.getElementById( "shippingAddressDiv_fullPayment_"+index).style.display="none";
	} else {
		loadStates( 'FULL_PAYMENT', index, 'sameAsShippingAddress' );
		document.getElementById( "shippingAddressDiv_fullPayment_"+index).style.display="block";
	}
}

function showHideShippingAddressForSchedulePayment( obj, index ) {
	if ( obj.checked ) {
		displayInitialShippingAddress( index , 'SCHEDULED_PAYMENT');
		_isDisplayForShippingAddress = true;
		document.getElementById( "shippingAddressDiv_schedulePayment_"+index).style.display="none";
	} else {
		loadStates( 'SCHEDULED_PAYMENT', index, 'sameAsShippingAddress' );
		document.getElementById( "shippingAddressDiv_schedulePayment_"+index).style.display="block";
	}
}

function showHidePayment( obj ) {
	if ( obj.value == 'SCHEDULED_PAYMENT' ) {
		isSchedulePayment = true;
		var initialDepositAmount =  document.getElementById( "depositAmount" ).value ;
		if( parseFloat( _depositAmount ) >= parseFloat( initialDepositAmount )  ){
			document.getElementById( "schedulePaymentHeaderDiv" ).style.display = "block";
			for( var count = 0; count < numberOfCreditCardsForScheduledPayment; count++ ) {
				document.getElementById( "schedulePaymentDataDiv_" + count ).style.display = "block";
			}
		}	
		if( numberOfCreditCardsForScheduledPayment >= 1 ) {
			for( var count = 1; count < maxCreditCards; count++ ) {
				document.getElementById( "currentPaymentDataDiv_" + count ).style.display="none";
			}
		}
		document.getElementById( "creditCardAmount_fullPayment_div_0" ).innerHTML = getCreditCardRowAsHTML(0, _depositAmount );
		//document.getElementById( "creditCardAmount_schedulePayment_0" ).value = parseFloat( _grossAmount - parseFloat( _depositAmount ) ).toFixed(2);
		numberOfCreditCardsForFullPayment = 1;
	} else if ( obj.value == 'FULL_PAYMENT'  ) {
		isSchedulePayment = false;
		document.getElementById( "grossAmountScheduleSpan" ).innerHTML = "$" + parseFloat( _grossAmount ) .toFixed(2);
		document.getElementById( "schedulePaymentHeaderDiv" ).style.display = "none";
		for( var count = 0; count < numberOfCreditCardsForScheduledPayment; count++ ) {
			document.getElementById( "schedulePaymentDataDiv_"+count ).style.display = "none";
		}
		if( numberOfCreditCardsForFullPayment >= 1 ) {
			for( var count = 0; count < numberOfCreditCardsForFullPayment; count++ ) {
				document.getElementById( "currentPaymentDataDiv_"+count ).style.display = "block";
				document.getElementById( "creditCardAmount_fullPayment_div_"+count ).innerHTML = getCreditCardRowAsHTML(count, _grossAmount );
			}
		}
		document.getElementById( "creditCardAmount_fullPayment_0" ).value = parseFloat( _grossAmount ) .toFixed(2);
	}
}

function loadDefaultPaymentInfo() {
	var currentPayment = "";
	var currentPaymentValue = document.getElementsByName("currentPayment");
	for( i = 0; i < currentPaymentValue.length; i++ ) {
		if( currentPaymentValue[i].checked == true ) {
			currentPayment = currentPaymentValue[i].value;
		}
	}
	if ( currentPayment == 'SCHEDULED_PAYMENT' ) {
		for( var count = 0; count < numberOfCreditCardsForScheduledPayment; count++ ) {
			if ( count == 0 ) {
				document.getElementById( "currentPaymentDataDiv_" +count).style.display = "block";
				document.getElementById( "schedulePaymentDataDiv_" +count).style.display = "block";
				document.getElementById( "creditCardAmount_fullPayment_div_"+count ).innerHTML = getCreditCardRowAsHTML(count, _depositAmount );
			} else {
				document.getElementById( "schedulePaymentDataDiv_" +count).style.display = "block";
			}
		}
		// displaying balance amount into the schedule payment
		document.getElementById( "creditCardAmount_schedulePayment_0").value = parseFloat( _grossAmount - parseFloat( _depositAmount ) ).toFixed(2);
		if ( numberOfCreditCardsForScheduledPayment != 1 )
			document.getElementById( "remove_schedulePayment_" +( numberOfCreditCardsForScheduledPayment-1 ) ).style.display = "block";
		if ( ! isFirstTime ) {
			if( document.getElementById( "schedulePaymentDataDiv_" +( numberOfCreditCards - 1 ) ) ) document.getElementById( "schedulePaymentDataDiv_" +( numberOfCreditCards - 1 ) ).style.display = "none";
		}
	}
	if ( currentPayment == 'FULL_PAYMENT' ) {
		for( var count = 0; count < numberOfCreditCardsForFullPayment; count++ ) {
			document.getElementById( "currentPaymentDataDiv_" +count).style.display = "block";
			document.getElementById( "creditCardAmount_fullPayment_div_"+count ).innerHTML = getCreditCardRowAsHTML(count, 0.0);
		}
		document.getElementById( "schedulePaymentHeaderDiv").style.display="none";
		// displaying gross amount at the first time
		document.getElementById( "creditCardAmount_fullPayment_0" ).value = parseFloat(_grossAmount).toFixed(2);
		if( numberOfCreditCardsForFullPayment > 1 )
		document.getElementById( "remove_fullPayment_" +( numberOfCreditCardsForFullPayment-1 ) ).style.display = "block";
	}
	var creditCardsAmount = _creditCardsAmount.split(",");
	var creditCardsAmountIndex = 0;
	if( !isFirstTime ) {
		for( var index = 0 ; index < numberOfCreditCardsForFullPayment; index++ ) {
			document.getElementById( "creditCardAmount_fullPayment_"+index ).value = parseFloat(creditCardsAmount[ creditCardsAmountIndex ]).toFixed(2);
			creditCardsAmountIndex++;
		}
		if( currentPayment == 'FULL_PAYMENT' ) {
			document.getElementById( "creditCardAmount_schedulePayment_0" ).value = parseFloat( _grossAmount - parseFloat( _depositAmount ) ).toFixed(2);
		} else {
			for( var index = 0 ; index < numberOfCreditCardsForScheduledPayment; index++ ) {
				document.getElementById( "creditCardAmount_schedulePayment_"+index ).value = parseFloat(creditCardsAmount[ creditCardsAmountIndex ]).toFixed(2);
				creditCardsAmountIndex++;
			}
		}
	}
}

function addCreditCard( ) {
	clearErrorElements();
	var previousCardAmount = 0;
	var creditCardAmount;
	if ( isSchedulePayment ) {
		if ( numberOfCreditCardsForScheduledPayment >= 1 && numberOfCreditCardsForScheduledPayment < maxCreditCards ) {
			for ( var index = 0; index < numberOfCreditCardsForScheduledPayment; index++ ) {
				creditCardAmount = document.getElementById( "creditCardAmount_schedulePayment_"+index ).value;
				previousCardAmount = parseFloat( previousCardAmount + parseFloat( creditCardAmount ) );
			}
			if( previousCardAmount >= parseFloat( _grossAmount - parseFloat( _depositAmount ) ).toFixed(2) ) {
				showErrorMessage( 'Total amount already matches total package price.', 'dataContent' ,'creditCardAmount_schedulePayment_'+ ( numberOfCreditCardsForScheduledPayment-1 ), '1px solid #7f9db9' );
				return false;
			} else {
				document.getElementById( "schedulePaymentDataDiv_" +numberOfCreditCardsForScheduledPayment ).style.display = "block";
				document.getElementById( "remove_schedulePayment_" +(numberOfCreditCardsForScheduledPayment-1) ).style.display = "none";
				document.getElementById( "remove_schedulePayment_" +numberOfCreditCardsForScheduledPayment ).style.display = "block";
				var scheduledCreditCardAmount = parseFloat(( _grossAmount - parseFloat( document.getElementById( "creditCardAmount_fullPayment_0" ).value ) ) - parseFloat( previousCardAmount )).toFixed(2);
				if( isNaN ( scheduledCreditCardAmount ) == true ){
					scheduledCreditCardAmount = "";
				}
				document.getElementById( "creditCardAmount_schedulePayment_" + numberOfCreditCardsForScheduledPayment ).value = scheduledCreditCardAmount;
			}
			numberOfCreditCardsForScheduledPayment++;
		} else if ( numberOfCreditCardsForScheduledPayment == maxCreditCards ) {
			showWarningMessage( 'You are allowed only 3 credit cards', 'dataContent' );
		}
	} else {
		if ( numberOfCreditCardsForFullPayment >= 1 && numberOfCreditCardsForFullPayment < maxCreditCards ) {
			for ( var index = 0; index < numberOfCreditCardsForFullPayment; index++ ) {
				creditCardAmount = document.getElementById( "creditCardAmount_fullPayment_"+index).value;
				previousCardAmount = parseFloat( previousCardAmount + parseFloat( creditCardAmount ) );
			}
			if( parseFloat( previousCardAmount ) >= parseFloat( _grossAmount ) ) {
				showErrorMessage( 'Total amount already matches total package price.', 'dataContent', 'creditCardAmount_fullPayment_' + ( numberOfCreditCardsForFullPayment-1 ), '1px solid #7f9db9' );
				return false;
			} else {
				document.getElementById( "currentPaymentDataDiv_" +numberOfCreditCardsForFullPayment ).style.display = "block";
				document.getElementById( "remove_fullPayment_" +( numberOfCreditCardsForFullPayment-1) ).style.display = "none";
				document.getElementById( "remove_fullPayment_" +numberOfCreditCardsForFullPayment ).style.display = "block";
				document.getElementById( "creditCardAmount_fullPayment_div_"+numberOfCreditCardsForFullPayment ).innerHTML = getCreditCardRowAsHTML(numberOfCreditCardsForFullPayment, 0.0);
				var fullPaymentCreditCardAmount = parseFloat( _grossAmount - parseFloat( previousCardAmount ) ).toFixed(2);
				if( isNaN ( fullPaymentCreditCardAmount ) == true ){
					fullPaymentCreditCardAmount = "";
				}
				document.getElementById( "creditCardAmount_fullPayment_"+ numberOfCreditCardsForFullPayment ).value = fullPaymentCreditCardAmount;
			}
			numberOfCreditCardsForFullPayment++;
		} else if ( numberOfCreditCardsForFullPayment == maxCreditCards ) {
			showWarningMessage( 'You are allowed only 3 credit cards', 'dataContent' );
		}
	}
	return true;
}

function removeCreditCard( paymentMode, index ) {
	var previousCardAmount = 0;
	var creditCardAmount;
	if ( paymentMode == 'SCHEDULED_PAYMENT' ) {
		document.getElementById( "schedulePaymentDataDiv_" +index ).style.display = "none";
		if(index != 1 )
		document.getElementById( "remove_schedulePayment_" +(index-1) ).style.display = "block";
		numberOfCreditCardsForScheduledPayment--;
// Re populating the amount
		for ( var count = 0; count < index-1; count++ ) {
			creditCardAmount = document.getElementById( "creditCardAmount_schedulePayment_"+count).value;
			previousCardAmount = parseFloat( previousCardAmount + parseFloat( creditCardAmount ) );
		}
		var scheduledCreditCardAmount = parseFloat(( _grossAmount - parseFloat( document.getElementById( "creditCardAmount_fullPayment_0" ).value ) ) - parseFloat( previousCardAmount )).toFixed(2);
		if( isNaN ( scheduledCreditCardAmount ) == true ){
			scheduledCreditCardAmount = "";
		}
		document.getElementById( "creditCardAmount_schedulePayment_" +(index-1) ).value = scheduledCreditCardAmount;
	} else if ( paymentMode == 'FULL_PAYMENT' ) {
		document.getElementById( "currentPaymentDataDiv_" +index ).style.display = "none";
		if(index != 1 )
		document.getElementById( "remove_fullPayment_" +(index-1) ).style.display = "block";
		numberOfCreditCardsForFullPayment--;
		// Re populating the amount
		for ( var count = 0; count < index-1; count++ ) {
			creditCardAmount = document.getElementById( "creditCardAmount_fullPayment_"+count).value;
			previousCardAmount = parseFloat( previousCardAmount + parseFloat( creditCardAmount ) );
		}
		var fullPaymentCreditCard = parseFloat( _grossAmount - parseFloat( previousCardAmount ) ).toFixed(2);
		if( isNaN ( fullPaymentCreditCard ) == true ){
			fullPaymentCreditCard = "" ; 
		}
		document.getElementById( "creditCardAmount_fullPayment_" +(index-1) ).value = fullPaymentCreditCard;
	}
}

function loadStates( paymentMode, index, sameAsShippingAddress ) {
	var country;
	var state;
	if ( paymentMode == '' || sameAsShippingAddress == 'sameAsShippingAddress' ) {
		country = document.getElementById( "country" ).value;
		state = document.getElementById( "state" ).value;
	}else if ( paymentMode == 'SCHEDULED_PAYMENT' ) {
		country = document.getElementById( "country_schedulePayment_"+index ).value;
		state = document.getElementById( "state_schedulePayment_"+index ).value;
	} else if ( paymentMode == 'FULL_PAYMENT' ) {
		country = document.getElementById( "country_fullPayment_"+index ).value;
		state = document.getElementById( "state_fullPayment_"+index ).value;
	}
	_paymentMode = paymentMode;
	_divIndex = index;
	var queryString = 'pm=4';
	queryString += "&country=" + country;
	queryString += "&state=" + state;
	makeAjaxCall( 'payment.act', queryString, null, 'rightContent', 'callbackStates', '' );
}

function callbackStates( message, errorCode, states ) {
	if( message != "" ) {
		showMessage( message, errorCode, 'dataContent' );
	} else {
		if ( _paymentMode == '' ) {
			document.getElementById( "stateDiv" ).innerHTML = "<label class='fll mt05'>State<span class='sup'>*</span>:&nbsp;</label><div id='stateSelectionDiv' class='fll'><select name='state' id='state' class='fll fs11 textbox w166'> <option value = ''>Select</option>" + states + "</select></div>";
		}else if ( _paymentMode == 'SCHEDULED_PAYMENT' ) {
			document.getElementById( "state_schedulePayment_div_"+_divIndex ).innerHTML = '<div id="state_schedulePayment_selection_div_'+_divIndex+'" class="flr"><label><select name="state_schedulePayment_'+_divIndex+'" id="state_schedulePayment_'+_divIndex+'" class="fs11 textbox w166"><option value = "">Select</option>' + states + '</select></label></div><div class="flr">State<span class="sup">*</span>:&nbsp;</div>';
		} else if ( _paymentMode == 'FULL_PAYMENT' ) {
			document.getElementById( "state_fullPayment_div_"+_divIndex ).innerHTML = '<div id="state_fullPayment_selection_div_'+_divIndex+'" class="flr"><label><select name="state_fullPayment_'+_divIndex+'" id="state_fullPayment_'+_divIndex+'" class="fs11 textbox w166"><option value = "">Select</option>' + states + '</select></label></div><div class="flr">State<span class="sup">*</span>:&nbsp;</div>';
		}
	}
	return true;
}

function primaryPhoneStateCodeOnKeyUp(event ) {
	var primaryPhoneStateCode = document.getElementById("primaryPhoneStateCode").value;
	if( primaryPhoneStateCode.length == 3 && !isShiftTabOrDeleteKey(event)){
		var primaryPhoneCityCodeElement = document.getElementById("primaryPhoneCityCode");
		primaryPhoneCityCodeElement.focus();
		primaryPhoneCityCodeElement.select();
	}
}

function primaryPhoneCityCodeOnKeyUp(event ) {
	var primaryPhoneCityCode = document.getElementById("primaryPhoneCityCode").value;
	if( primaryPhoneCityCode.length == 3 && !isShiftTabOrDeleteKey(event)){
		var primaryPhoneElement = document.getElementById("primaryPhone");
		primaryPhoneElement.focus();
		primaryPhoneElement.select();
	}
}

function alternatePhoneStateCodeOnKeyUp(event ) {
	var alternatePhoneStateCode = document.getElementById("alternatePhoneStateCode").value;
	if( alternatePhoneStateCode.length == 3 && !isShiftTabOrDeleteKey(event)){
		var alternatePhoneCityCodeElement = document.getElementById("alternatePhoneCityCode");
		alternatePhoneCityCodeElement.focus();
		alternatePhoneCityCodeElement.select();
	}
}

function alternatePhoneCityCodeOnKeyUp(event ) {
	var alternatePhoneCityCode = document.getElementById("alternatePhoneCityCode").value;
	if( alternatePhoneCityCode.length == 3 && !isShiftTabOrDeleteKey(event)){
		var alternatePhoneElement = document.getElementById("alternatePhone");
		alternatePhoneElement.focus();
		alternatePhoneElement.select();
	}
}

function alternatePhoneOnKeyUp(event) {
	var alternatePhoneCode = document.getElementById("alternatePhone").value;
	if( alternatePhoneCode.length == 4 && !isShiftTabOrDeleteKey(event)){
		var alternatePhoneExtensionElement = document.getElementById("alternatePhoneExtension");
		alternatePhoneExtensionElement.focus();
		alternatePhoneExtensionElement.select();
	}
}
function validateAndAdjustScheduledOrFullPaymentAmount( ){
 	var selectedPaymentOption = getCheckedValue( document.getElementsByName("currentPayment"));
 	var newDepositAmount = document.getElementById('creditCardAmount_fullPayment_0').value;
 	_depositAmount = newDepositAmount;
 	var isDepositModified = document.getElementById( "isDepositModified" ).value;
	if( isDepositModified != "true" ){
  		_minDepositAmount = document.getElementById( "depositAmount" ).value;
    }
 	if( isFloat( newDepositAmount )){
 		if( selectedPaymentOption == 'SCHEDULED_PAYMENT') {
 			var depositAmount = parseFloat(newDepositAmount).toFixed( 2 );
 			var minimumDepositAmount = parseFloat( _minDepositAmount ).toFixed( 2 );
 			var grossAmount = parseFloat( _grossAmount ).toFixed( 2 );
			if( parseFloat(depositAmount) < parseFloat(minimumDepositAmount) ) {
				document.getElementById('creditCardAmount_fullPayment_0').focus();
				showErrorMessage('Please enter an amount not less than the minimum deposit of '+ formatCurrency(_minDepositAmount) + '.', 'dataContent', 'creditCardAmount_fullPayment_0', '1px solid #7f9db9');
				return;
			} else if( parseFloat(depositAmount) > parseFloat(grossAmount) ) {
				document.getElementById('creditCardAmount_fullPayment_0').focus();
				showErrorMessage('Please enter an amount not more than the full amount of '+ formatCurrency(_grossAmount) + '.', 'dataContent', 'creditCardAmount_fullPayment_0', '1px solid #7f9db9');
				return;
			} else if( parseFloat(depositAmount) == parseFloat(grossAmount) ) {
				document.getElementById('creditCardAmount_fullPayment_0').focus();
				showErrorMessage('Please enter an amount less than the full amount of '+ formatCurrency(_grossAmount) + ' or else you can choose Pay Full Amount option', 'dataContent', 'creditCardAmount_fullPayment_0', '1px solid #7f9db9');
				return;
			} else {
				if(numberOfCreditCardsForScheduledPayment == 1) {
					_depositAmount = newDepositAmount;
					var newScheduledPayment = parseFloat(_grossAmount - newDepositAmount).toFixed(2);
					document.getElementById("creditCardAmount_schedulePayment_0").value = newScheduledPayment;
				}else {
					var creditCardIndex = -1;
					var maxAmount = 0;
					var changedDepositAmount = 0;
					if( _previousDepositAmount != undefined  ){
						changedDepositAmount = newDepositAmount - _previousDepositAmount;
					}else{
						changedDepositAmount = newDepositAmount - _depositAmount
					}
					for( var index = 0; index < numberOfCreditCardsForScheduledPayment; index++ ) {
						var creditCardAmount = parseFloat ( document.getElementById( 'creditCardAmount_schedulePayment_' + index ).value ) ;
						if( ( creditCardAmount >= changedDepositAmount ) && ( creditCardAmount > maxAmount ) ) {
							creditCardIndex = index;
							maxAmount = creditCardAmount;
						}
					}
					if( creditCardIndex != -1 ){
						document.getElementById( 'creditCardAmount_schedulePayment_' + creditCardIndex ).value = parseFloat( parseFloat ( document.getElementById('creditCardAmount_schedulePayment_'+ creditCardIndex ).value )  - changedDepositAmount).toFixed(2);	
					}
				}
				document.getElementById('creditCardAmount_fullPayment_0').value = newDepositAmount;
			}
 		} else if(selectedPaymentOption == 'FULL_PAYMENT') {
 			newFullAmount = parseFloat(newDepositAmount).toFixed(2);
 			if( parseFloat( newFullAmount ) > parseFloat(_grossAmount).toFixed(2)) {
 				document.getElementById('creditCardAmount_fullPayment_0').focus();
				showErrorMessage('Please enter an amount not more than the full amount of '+ formatCurrency(_grossAmount) + '.', 'dataContent', 'creditCardAmount_fullPayment_0', '1px solid #7f9db9');
				return;
			}
 		}
 		_previousDepositAmount = newDepositAmount;
 		clearErrorElements();
	} else {
		showErrorMessage('Amount entered is not valid. Please enter a valid amount', 'dataContent', 'creditCardAmount_fullPayment_0', '1px solid #7f9db9');
	}
}

function validatePaymentAmount(paymentAmountElementName){
	var paymentAmountElement = document.getElementById(paymentAmountElementName);
	if(paymentAmountElement) {
		var paymentAmount = paymentAmountElement.value;
		if(isFloat(paymentAmount)) {
			paymentAmountElement.value = parseFloat(paymentAmount).toFixed(2);
		}
		else {
			showErrorMessage('Amount entered is not valid. Please enter a valid amount.', 'dataContent', paymentAmountElementName, '1px solid #7f9db9');
		}
	}
}

function getCreditCardRowAsHTML(index, amount) {
 return '<input type="text" name="creditCardAmount_fullPayment_'+index+'" id="creditCardAmount_fullPayment_'+index+'" class="fs11 textbox w70"  value=' + parseFloat( amount ).toFixed(2) + '  maxlength="10" onkeypress="return checkDecimal(event);" onblur="formatDecimal( this, 2 ); validateAndAdjustScheduledOrFullPaymentAmount();"/>';
}


function showScheduledPaymentCalendar(elementName) {
	var disabledDateRanges = new Array();
	var currentDate = new Date();
	var scheduledDate = new Date(_scheduledDate);
	var minDateRange = new DateRange(getMinCalendarDate(), currentDate);
	var maxDateRange = new DateRange(addDays(scheduledDate, 1),  getMaxCalendarDate());
	disabledDateRanges = [ minDateRange, maxDateRange ] ;
	showCalendar( elementName, null, disabledDateRanges );
}

//Retaining Same as Shipping Address when we are coming back to payment screen from passenger detail.
function billingAddressForFullPayment( billingAddressStatusForFullPayment ) {
    if( billingAddressStatusForFullPayment.indexOf(",") !=  -1 ){
    	var billingAddressStatusArray = billingAddressStatusForFullPayment.split(",");
     	var noOfCreditCards =  billingAddressStatusArray.length;
    	for( var index = 0; index < noOfCreditCards; index++ ){
	    	if( billingAddressStatusArray[index]== "true" ){
		    	document.getElementById( "sameAsBillingAddress_fullPayment_div_"+ index ).innerHTML = '<input type ="checkbox" id="sameAsBillingAddress_fullPayment_'+index+'"  checked  onClick="showHideShippingAddressForFullPayment(this,'+index+');"/>'+ "Same as Shipping Address";
	    	} else {
	    		document.getElementById( "sameAsBillingAddress_fullPayment_div_"+ index ).innerHTML = '<input type = "checkbox" id="sameAsBillingAddress_fullPayment_'+index+'" onClick="showHideShippingAddressForFullPayment(this,'+index+');" />'+"Same as Shipping Address";
	    		document.getElementById( "shippingAddressDiv_fullPayment_"+index ).style.display="block";
	    	}
  		}
 	} else {
 		if( billingAddressStatusForFullPayment == "true" ){
 	   		document.getElementById( "sameAsBillingAddress_fullPayment_div_0" ).innerHTML = '<input type ="checkbox" id="sameAsBillingAddress_fullPayment_0"  checked  onClick="showHideShippingAddressForFullPayment(this,0);"/>'+ "Same as Shipping Address";
 	   	} else {
 	   		document.getElementById( "sameAsBillingAddress_fullPayment_div_0" ).innerHTML = '<input type ="checkbox" id="sameAsBillingAddress_fullPayment_0"  onClick="showHideShippingAddressForFullPayment(this,0);"/>'+ "Same as Shipping Address";
 	   		document.getElementById( "shippingAddressDiv_fullPayment_0" ).style.display="block";
 	   }
 	}
}

//Retaining Same as Shipping Address when we are coming back to payment screen from passenger detail.
function billingAddressForSchedulePayment( billingAddressStatusForSchedulePayment ) {
	if( billingAddressStatusForSchedulePayment.indexOf(",") !=  -1 ){
    	var billingAddressStatusArray = billingAddressStatusForSchedulePayment.split(",");
     	var noOfCreditCards =  billingAddressStatusArray.length;
    	for( var index = 0; index < noOfCreditCards; index++ ) {
	    	if( billingAddressStatusArray[index]== "true" ) {
		    	document.getElementById( "sameAsBillingAddress_schedulePayment_div_"+ index ).innerHTML = '<input type ="checkbox" id="sameAsBillingAddress_schedulePayment_'+index+'"  checked  onClick="showHideShippingAddressForSchedulePayment(this,'+index+');"/>'+ "Same as Shipping Address";
	    	} else {
	    		document.getElementById( "sameAsBillingAddress_schedulePayment_div_"+ index ).innerHTML = '<input type = "checkbox" id="sameAsBillingAddress_schedulePayment_'+index+'" onClick="showHideShippingAddressForSchedulePayment(this,'+index+');" />'+"Same as Shipping Address";
	    		document.getElementById( "shippingAddressDiv_schedulePayment_"+index ).style.display="block";
	    	}
  		}
 	} else {
 		if( billingAddressStatusForSchedulePayment == "true" ){
 	   		document.getElementById( "sameAsBillingAddress_schedulePayment_div_0" ).innerHTML = '<input type ="checkbox" id="sameAsBillingAddress_schedulePayment_0"  checked  onClick="showHideShippingAddressForSchedulePayment(this,0);"/>'+ "Same as Shipping Address";
 	   	} else {
 	   		document.getElementById( "sameAsBillingAddress_schedulePayment_div_0" ).innerHTML = '<input type ="checkbox" id="sameAsBillingAddress_schedulePayment_0"  onClick="showHideShippingAddressForSchedulePayment(this,0);"/>'+ "Same as Shipping Address";
 	   		document.getElementById( "shippingAddressDiv_schedulePayment_0" ).style.display="block";
 	   }
 	}
}
function applyPromotion( isFromPopup ) {
	clearErrorElements();
	var promotionalCode = document.getElementById( "promotionalCode" ).value; 
	 if( promotionalCode == "" ) {
    	showErrorMessage( 'Please enter promotion code', 'dataContent', 'promotionalCode', '1px solid #7f9db9' );
    	return;
    }
    var commaSeperatedCardType = "";
    if( isFromPopup != "yes" ){
	  	 if( isSchedulePayment ) {
	  	 		var creditCardField = document.getElementById( 'creditCardNumber_fullPayment_0' );
	  	 		if( creditCardField.value != "" ){
	  	 			var cardType = checkCreditCard ( creditCardField.value );
	  	 			commaSeperatedCardType = cardType;
	  	 		}
	  	 }else{
	  	 	for ( var index = 0; index < numberOfCreditCardsForFullPayment; index++ ) {
	  	 		var creditCardField = document.getElementById( 'creditCardNumber_fullPayment_' + index );
	  	 		if( creditCardField.value != "" ){
	  	 			var cardType = checkCreditCard ( creditCardField.value );
	  	 			if( index == 0  ){
	  	 					commaSeperatedCardType += cardType;
  	 				}else {
	  	 					commaSeperatedCardType += "," + cardType;
	  	 			}
	  	 		}
	  	 	}
	  	 }
  	 }else{
  	 	var cardType = document.getElementById( "cardType" ).value; 
	 	if( cardType == "" ) {
    		showErrorMessage( 'Please select card type', 'dataContent', 'cardType', '1px solid #7f9db9' );
    		return;
    	}
    	commaSeperatedCardType = cardType;
  	 }
	var queryString = 'pm=6';
 	queryString += "&cardType=" + commaSeperatedCardType;
 	queryString += "&promotionCode=" + promotionalCode;
	makeAjaxCall( 'payment.act', queryString , null, 'rightContent', 'callbackApplyPromotion', '' );
}

function callbackApplyPromotion( message , promotionCode , promotionAmount ) {
	var isDepositModified = document.getElementById( "isDepositModified" ).value;
	var isDepositChange = false;
	_depositAmount = parseFloat( document.getElementById( "depositAmount" ).value ).toFixed( 2 );
	var grossAmountFromDB = parseFloat( document.getElementById( "grossAmount" ).value );
	if( promotionAmount > 0.0 && promotionAmount < grossAmountFromDB ){
		_grossAmount = parseFloat( grossAmountFromDB - promotionAmount );
		if( _grossAmount <  _depositAmount ){
			_depositAmount = _grossAmount;
			_minDepositAmount =  parseFloat( _depositAmount ).toFixed( 2 );
			isDepositModified = true;
			isDepositChange = true;
			document.getElementById( "isDepositModified" ).value = "true";
		}
		_grossAmount = parseFloat( _grossAmount ).toFixed( 2 );
	}else if( promotionAmount >= grossAmountFromDB ){
			_grossAmount = 0.0;
			_depositAmount = 0.0;
			_minDepositAmount = 0.0;
			isDepositModified = true;
			isDepositChange = true;
			document.getElementById( "isDepositModified" ).value = "true";
			document.getElementById( "previousGrossAmount" ).value = 0.0;
	}else {
		_grossAmount = grossAmountFromDB;
		isDepositModified = false;
	}
	if( message == "cardTypeRequired" ){
		document.getElementById( "promotionalCode" ).value = promotionCode;
		loadPromotionPopup();
	}else {
		hidePromotionDetails();
		var fromConfirmPaymentPage = document.getElementById( "fromConfirmPaymentPage" ).value;
		if( fromConfirmPaymentPage == "true" && isSchedulePayment ){
			if( !isDepositChange ){
				document.getElementById( "promotionalCode" ).value = promotionCode;
				document.getElementById( "promotionCode" ).value = promotionCode;
				document.getElementById( "divPrice" ).innerHTML =  formatCurrency( _grossAmount );
				document.getElementById( "promotionAmount" ).value = promotionAmount;
				document.getElementById( "schedulePaymentHeaderDiv" ).style.display = "block";
				document.getElementById( "schedulePaymentDataDiv_0" ).style.display = "block";
				document.getElementById( "fromConfirmPaymentPage" ).value = false;
				document.getElementById( "depositSpan" ).innerHTML = formatCurrency( _depositAmount );
				document.getElementById( "grossAmountScheduleSpan" ).innerHTML =  formatCurrency( parseFloat( _grossAmount ).toFixed( 2 ) );
				document.getElementById( "creditCardAmount_fullPayment_0" ).value = parseFloat( _depositAmount ).toFixed( 2 );
				document.getElementById( "creditCardAmount_schedulePayment_0" ).value = parseFloat(_grossAmount - _depositAmount).toFixed( 2 );
				numberOfCreditCardsForScheduledPayment = 1;
				if( promotionAmount < 0.0 ) {
					document.getElementById( "isPromotionApplied" ).value = "false";
					document.getElementById( "previousPromotionAmount" ).value = 0.0;
					document.getElementById( "promotionMessage" ).style.display = "none";
					document.getElementById( "promotionMessage" ).innerHTML = "";
					showErrorMessage( message , 'dataContent', 'promotionalCode', '1px solid #7f9db9' );
					return true;
				}else{
					document.getElementById( "previousPromotionAmount" ).value = promotionAmount;
					document.getElementById( "isPromotionApplied" ).value = "true";
					document.getElementById( "promotionMessage" ).style.display = "block";
					document.getElementById( "promotionMessage" ).innerHTML = message;
				}
			}
		}
		if( promotionAmount > 0.0 ){
			document.getElementById( "promotionalCode" ).value = promotionCode;
			document.getElementById( "promotionCode" ).value = promotionCode;
			document.getElementById( "promotionMessage" ).style.display = "block";
			document.getElementById( "promotionMessage" ).innerHTML = message;
			document.getElementById( "divPrice" ).innerHTML =  formatCurrency( _grossAmount );
			document.getElementById( "promotionAmount" ).value = promotionAmount;
			document.getElementById( "isPromotionApplied" ).value = "true";
			if( isSchedulePayment ){
				if( isDepositChange ){
					document.getElementById( "depositSpan" ).innerHTML = formatCurrency( _depositAmount );
					document.getElementById( "creditCardAmount_fullPayment_0" ).value = parseFloat( _depositAmount ).toFixed( 2 );
					document.getElementById( "grossAmountScheduleSpan" ).innerHTML =  formatCurrency( _grossAmount );
					document.getElementById( "schedulePaymentHeaderDiv" ).style.display = "none";
					for( var count = 0; count < numberOfCreditCardsForScheduledPayment; count++ ) {
						document.getElementById( "schedulePaymentDataDiv_" + count ).style.display = "none";
					}
					document.getElementById( "creditCardAmount_fullPayment_0" ).value = _grossAmount;
					document.getElementById( "previousPromotionAmount" ).value = 0;
					numberOfCreditCardsForScheduledPayment = 0;
				}else{
					var isDepositModified = document.getElementById( "isDepositModified" ).value;
					if( isDepositModified == "true" ){
						numberOfCreditCardsForScheduledPayment = 1;
						document.getElementById( "schedulePaymentHeaderDiv" ).style.display = "block";
						for( var count = 0; count < numberOfCreditCardsForScheduledPayment; count++ ) {
							document.getElementById( "schedulePaymentDataDiv_" + count ).style.display = "block";
						}
						document.getElementById( "creditCardAmount_fullPayment_0" ).value = parseFloat( _depositAmount ).toFixed( 2 );
						updatePaymentByPaymentType( promotionAmount );
					}else{
						updatePaymentByPaymentType( promotionAmount );
					}
					document.getElementById( "grossAmountScheduleSpan" ).innerHTML =  formatCurrency( _grossAmount );
					document.getElementById( "depositSpan" ).innerHTML = formatCurrency( _depositAmount );
					document.getElementById( "previousPromotionAmount" ).value = promotionAmount;	
				}
			}else {
				if( _grossAmount > 0.0 ){
					var previousGrossAmount = parseFloat( document.getElementById( "previousGrossAmount" ).value );
					if ( previousGrossAmount == 0.0 ){
						document.getElementById( "creditCardAmount_fullPayment_0" ).value = _grossAmount ;
						if( document.getElementById( "grossAmountSpan" ) != null ){
							document.getElementById( "grossAmountSpan" ).innerHTML =  formatCurrency( _grossAmount );
						}
						for( var index = 1 ; index <= numberOfCreditCardsForFullPayment ; index++ ){
							removeCreditCard( 'FULL_PAYMENT', index );
						} 
						numberOfCreditCardsForFullPayment = 1;
						document.getElementById( "previousPromotionAmount" ).value = promotionAmount;
					} else{
						updatePaymentByPaymentType( promotionAmount );
						document.getElementById( "previousPromotionAmount" ).value = promotionAmount;	
					}
				}else{
					for( var index = 1 ; index <= numberOfCreditCardsForFullPayment ; index++ ){
						removeCreditCard( 'FULL_PAYMENT', index );
					} 
					numberOfCreditCardsForFullPayment = 1;
					updatePaymentByPaymentType( 0.0 );
					document.getElementById( "creditCardAmount_fullPayment_0" ).value = 0.0;
					document.getElementById( "previousPromotionAmount" ).value = 0.0;
				}
			}
		}else if( promotionAmount < 0.0 ){
			document.getElementById( "isPromotionApplied" ).value = "false";
			document.getElementById( "promotionMessage" ).style.display = "none";
			updatePaymentForInvalidPromotion( promotionCode );
			document.getElementById( "previousPromotionAmount" ).value = 0;
			showErrorMessage( message , 'dataContent', 'promotionalCode', '1px solid #7f9db9' );
			return true;
		} else{
			document.getElementById( "isPromotionApplied" ).value = "true";
			document.getElementById( "promotionMessage" ).style.display = "block";
			document.getElementById( "promotionMessage" ).innerHTML = message;
			updatePaymentForInvalidPromotion( promotionCode );
		}
	}
}
function updatePaymentForInvalidPromotion( promotionCode ){
	document.getElementById( "promotionAmount" ).value = 0.0;
	document.getElementById( "promotionalCode" ).value = promotionCode;
	document.getElementById( "promotionCode" ).value = promotionCode;
	document.getElementById( "divPrice" ).innerHTML =  formatCurrency( _grossAmount );
	var previousGrossAmount = parseFloat( document.getElementById( "previousGrossAmount" ).value );
	var previousPromotionAmount = parseFloat( document.getElementById( "previousPromotionAmount" ).value );
	var isDepositModified = document.getElementById( "isDepositModified" ).value;
		if( isSchedulePayment  ){
				if ( isDepositModified == "true" ){
					numberOfCreditCardsForScheduledPayment = 1;
					var depositAmount = document.getElementById( "depositAmount" ).value;
					document.getElementById( "schedulePaymentHeaderDiv" ).style.display = "block";
					for( var count = 0; count < numberOfCreditCardsForScheduledPayment; count++ ) {
						document.getElementById( "schedulePaymentDataDiv_" + count ).style.display = "block";
					}
					document.getElementById( "grossAmountScheduleSpan" ).innerHTML =  formatCurrency( _grossAmount );
					document.getElementById( "depositSpan" ).innerHTML = formatCurrency( depositAmount );
					document.getElementById( "creditCardAmount_fullPayment_0" ).value = parseFloat( depositAmount ).toFixed( 2 );
					document.getElementById( "creditCardAmount_schedulePayment_0" ).value = parseFloat(_grossAmount - depositAmount).toFixed( 2 );
				}else {
					updatePaymentByPaymentType( 0.0 );
				}
			}else { 
				if ( previousGrossAmount == 0.0 ){
					for( var index = 1 ; index < numberOfCreditCardsForFullPayment ; index++ ){
						removeCreditCard( 'FULL_PAYMENT', index );
					} 
					numberOfCreditCardsForFullPayment = 1;
					document.getElementById( "creditCardAmount_fullPayment_0" ).value = _grossAmount ;
					if( document.getElementById( "grossAmountSpan" ) != null ){
						document.getElementById( "grossAmountSpan" ).innerHTML =  formatCurrency( _grossAmount );
					}
				}else {
					updatePaymentByPaymentType( 0.0 );
					}
			}
	document.getElementById( "promotionAmount" ).value = 0.0;
	document.getElementById( "previousPromotionAmount" ).value = 0.0;		
}
function createPromotionDetailsDiv( disabledBaseElement ) {

	var promotionDetailsPopupDiv = document.getElementById( 'promotionPopupDivContainer' );
	if( isNull( promotionDetailsPopupDiv )){
		promotionDetailsPopupDiv = createPopupDiv( 'promotionPopupDivContainer', 0, 0, 410, 300, false, true,  "tal popupDivBig" );
	}
	promotionDetailsPopupDiv.disabledBaseElement = disabledBaseElement;
	disableElement( 'dataContent', true );
}

/*Disply the promotion pop up*/
function loadPromotionPopup(){
	// create pop up div for promotion popup.
	createPromotionDetailsDiv('promotionPopupDivContainer');
	
	// create action code to open promotion pop up.
	var queryString = 'pm=5';
	makeAjaxCall( 'payment.act', queryString, null, 'promotionPopupDivContainer', 'callbackLoadPromotionPopup', '' );
}

function callbackLoadPromotionPopup(){
	showBlock( 'promotionPopupDivContainer' ); 
	positionBlockCentrally( 'promotionPopupDivContainer' ); 
}

function hidePromotionDetails() {
	var promotionPopupDiv = document.getElementById( 'promotionPopupDivContainer' );
	
	if( promotionPopupDiv ) {
		disableElement( promotionPopupDiv.disabledBaseElement, false );		
	}
	hideBlock( 'promotionPopupDivContainer' );
	disableElement( 'dataContent', false );
}
function updateSchedulePaymentCardAmount( promotionAmount ){
	var creditCardIndex = 0;
	var maxAmount = 0;
	for( var index = 0; index < numberOfCreditCardsForScheduledPayment ; index++ ) {
		var creditCardAmount = parseFloat ( document.getElementById( 'creditCardAmount_schedulePayment_' + index ).value ) ;
		if( ( creditCardAmount > promotionAmount ) && ( creditCardAmount > maxAmount ) ) {
			creditCardIndex = index;
			maxAmount = creditCardAmount;
		}
	}
	if( promotionAmount > maxAmount ){
		document.getElementById( 'creditCardAmount_schedulePayment_0' ).value = parseFloat( _grossAmount - _depositAmount ).toFixed( 2 );
		document.getElementById( 'creditCardAmount_schedulePayment_1' ).value = 0.0;
		document.getElementById( 'creditCardAmount_schedulePayment_2' ).value = 0.0;
	}else{
		var previousPromotionAmount = document.getElementById( "previousPromotionAmount" ).value;
		previousPromotionAmount = parseFloat( previousPromotionAmount );
		if ( previousPromotionAmount > 0.0 ) {
			var creditCardField = document.getElementById( 'creditCardAmount_schedulePayment_'  + creditCardIndex );
			var  creditCardValue = parseFloat( creditCardField.value ).toFixed( 2 ) - promotionAmount + previousPromotionAmount;
			creditCardField.value = creditCardValue.toFixed( 2 );
		} else {
			var creditCardField = document.getElementById( 'creditCardAmount_schedulePayment_' + creditCardIndex );
			if( parseFloat( creditCardField.value ) > promotionAmount ) {
				var  creditCardValue = parseFloat( creditCardField.value ).toFixed( 2 ) - promotionAmount;
				creditCardField.value = creditCardValue.toFixed( 2 );
			}
 		}
	}
}

function updateFullPaymentCardAmount( promotionAmount ){
	var creditCardIndex = 0;
	var maxAmount = 0;
	for( var index = 0; index < numberOfCreditCardsForFullPayment ; index++ ) {
		var creditCardAmount = parseFloat ( document.getElementById( 'creditCardAmount_fullPayment_' + index ).value ) ;
		if( ( creditCardAmount > promotionAmount ) && ( creditCardAmount > maxAmount ) ) {
			creditCardIndex = index;
			maxAmount = creditCardAmount;
		}
	}
	if( promotionAmount > maxAmount ){
		document.getElementById( 'creditCardAmount_fullPayment_0' ).value = _grossAmount;
		for( var index = 1; index < numberOfCreditCardsForFullPayment ; index++ ) {
			 document.getElementById( 'creditCardAmount_fullPayment_' + index ).value = 0.0;
		}
	}else {
		var previousPromotionAmount = document.getElementById( "previousPromotionAmount" ).value;
		previousPromotionAmount = parseFloat( previousPromotionAmount );
		if ( previousPromotionAmount > 0.0 ) {
			var creditCardField = document.getElementById( 'creditCardAmount_fullPayment_'  + creditCardIndex );
			var  creditCardValue = parseFloat( creditCardField.value ).toFixed( 2 ) - promotionAmount + previousPromotionAmount;
			creditCardField.value = creditCardValue.toFixed( 2 );
		}else {
			var creditCardField = document.getElementById('creditCardAmount_fullPayment_' + creditCardIndex );
			if( parseFloat( creditCardField.value ) > promotionAmount ) {
				var  creditCardValue = parseFloat( creditCardField.value ).toFixed( 2 ) - promotionAmount;
				creditCardField.value = creditCardValue.toFixed( 2 );
			}
	 	}
	}	
}
function updatePaymentByPaymentType( promotionAmount ){
	_grossAmount = parseFloat( _grossAmount ).toFixed( 2 );
	if( isSchedulePayment ) {
		updateSchedulePaymentCardAmount( promotionAmount );
		document.getElementById( "grossAmountScheduleSpan" ).innerHTML =  formatCurrency( _grossAmount );
	}else {
		updateFullPaymentCardAmount( promotionAmount );
		if( document.getElementById( "grossAmountSpan" ) != null ){
			document.getElementById( "grossAmountSpan" ).innerHTML =  formatCurrency( _grossAmount );
		}else {
			document.getElementById( "grossAmountScheduleSpan" ).innerHTML =  formatCurrency( _grossAmount );
			document.getElementById( "depositSpan" ).innerHTML = formatCurrency( _depositAmount );
		}
	}
}

function loadBookingRecapPage() {
	var queryString = "cb=0"; 
	makeAjaxCall( 'cruiseBooking.act', null, null, 'rightContent', 'callbackLoadBookingRecapPage', '' );
}

function callbackLoadBookingRecapPage() {
	if ( ! ( showMessage ( this.errorMessage , this.errorCode , 'dataContent' ) ) ) {
		loadCruiseTripSummary ();
		disableElement ( "dataContent" , false );
	}
}
var _isCruiseItemIncluded; 

function loadPaymentInformation( ) {
	var queryString = 'pm=0';

	//Make Ajax call with '/vp/booking/paymentDetails/<destinationCode>/<regionCode>/<packageId>' as the description to be passed into Google Analytics'
	var trackingText = '/vp/booking/paymentDetails/' + _destinationCode + '/' + _regionCode + '/package/' + _packageId;
	makeAjaxCall( 'payment.act', queryString, null, 'rightContent', 'callbackLoadPaymentInformation', trackingText );
}
function callbackLoadPaymentInformation( message, errorCode ) {
	showMessage( message, errorCode, 'dataContent' );
	return true;
}

function loadPaymentConfirmation( ) {
	var queryString = 'cf=0';
	makeAjaxCall( 'paymentConfirm.act', queryString, null, 'rightContent', 'callbackLoadPaymentConfirmation', '' );
}
function callbackLoadPaymentConfirmation( message, errorCode ) {
	showMessage( message, errorCode, 'dataContent' );
	return true;
}

function makePayment(bookingId) {
	var queryString = 'cf=1';
	queryString += '&bookingId=' + bookingId;
	disableElement( 'dataContent', true );
	asynchronousRequest = new AsynchronousRequest();
	asynchronousRequest.url = _webLoc + '/paymentConfirm.act';
	asynchronousRequest.queryString = queryString;
	asynchronousRequest.useAjax = true;
	asynchronousRequest.target = 'rightContent';
	asynchronousRequest.callbackFunctionName = 'callbackMakePayment';

	var splashScreenRequest = new SplashScreenRequest();
	splashScreenRequest.splashScreenText = "Please Wait...";
	asynchronousRequest.splashScreenRequest = splashScreenRequest;
	asynchronousRequest.splashScreenDisplayFunctionName = "displaySearchingPopup";
	asynchronousRequest.splashScreenHideFunctionName = "hideSearchingPopup";
	
	var trackingText = '';
	if (_isCruiseItemIncluded && _isCruiseItemIncluded == 'true'){
		//Load the review submit screen with '/cr/booking/bookingWidget/BookingConfirmation/<destination>/<cruiseLine>/<ship>/<date>' as the description to be passed into Google Analytics
		trackingText = '/cr/booking/bookingWidget/BookingConfirmation/' + _destinationName + '/' + _cruiseLineName + '/' + _shipName + '/' + _departureDate;
	}
	else{
		//making Ajax call with '/vp/booking/bookingConfirmation/<destinationCode>/<regionCode>/package/<packageId>' as the description to be passed into Google Analytics
		trackingText =  '/vp/booking/bookingConfirmation/' + _destinationCode + '/' + _regionCode + '/package/' + _packageId;
	}
	
	makeAjaxCallWithRequest( asynchronousRequest, trackingText);
}

function callbackMakePayment( message, errorCode, paymentException ) {
	disableElement( 'dataContent', false );
	if( message != '' ) {
		showMessage( message, errorCode, 'dataContent' );
	} else {
		clearErrorElements();
		if( paymentException != null || paymentException != undefined ) { 
			showErrorMessage( paymentException, 'dataContent' );
			return false;
		}
	}
	return true;
}var _maxCreditCards;
var _numberOfBalanceCreditCards;
var _balanceAmount;

function CreditCardInfo() {
	this.cardType = null;
	this.creditCardNumber = null;
	this.cardType = null; 
	this.cardHolderName = null;
	this.creditCardExpirationMonth = null;
	this.creditCardExpirationYear = null;
	this.creditCardAmount = null;
	this.creditCardSecurityCode = null;
	this.street1 = null;
	this.street2 = null;
	this.city = null;
	this.state = null;
	this.country = null;
	this.zip = null;
}

function BalancePaymentInfo() {
	this.creditCardInfoArray = null;
	this.isBalancePayment = true;
	this.isAnotherPayment = false; 
}	

function loadBalancePaymentInfo(creditCardsAmount, balanceAmount, maxCreditCards, numberOfBalanceCreditCards) {
	_numberOfBalanceCreditCards = parseInt(numberOfBalanceCreditCards);
	_maxCreditCards = parseInt(maxCreditCards);
	_balanceAmount = parseFloat(balanceAmount).toFixed(2);
	var creditCardAmountArray = creditCardsAmount.split(",");
	for( var count = 0; count < _numberOfBalanceCreditCards; count++ ) {
		var creditCardAmount = creditCardAmountArray[count] ? creditCardAmountArray[count] : 0.0;		
		document.getElementById( "currentPaymentDataDiv_" + count).style.display = "block";
		document.getElementById( "creditCardAmount_balancePayment_div_"+count ).innerHTML = getBalanceCreditCardRowAsHTML(count, creditCardAmount);
	}
	
	var firstCreditCardAmount = document.getElementById( "creditCardAmount_balancePayment_0" ).value; 
	if(!firstCreditCardAmount || firstCreditCardAmount == '0') {
		document.getElementById( "creditCardAmount_balancePayment_0" ).value = parseFloat(_balanceAmount).toFixed(2);
	}	
	if( _numberOfBalanceCreditCards > 1 ){
		document.getElementById( "remove_balancePayment_" +( _numberOfBalanceCreditCards-1 ) ).style.display = "block";
	}	
}

function getBalanceCreditCardRowAsHTML(index, amount) {
 	return '<input type="text" name="creditCardAmount_balancePayment_'+index+'" id="creditCardAmount_balancePayment_'+index+'" class="fs11 textbox w70"  value=' + amount + '  maxlength="10" onkeypress="return checkDecimal(event);" onblur="formatDecimal(this, 2)"/>';
}

function showHideShippingAddressForBalancePayment( obj, index ) {
	if ( obj.checked ) {
		document.getElementById( "shippingAddressDiv_balancePayment_"+index).style.display="none";
		
	} else {
		loadInitialBalanceShippingAddress(index, true);					
	}
}

function loadInitialBalanceShippingAddress( index, showAddress ) {
	var country = document.getElementById( "country_balancePayment_"+index ).value;
	var	state = document.getElementById( "state_balancePayment_"+index ).value;
	var queryString = 'pm=4';
	queryString += "&country=" + country;
	queryString += "&state=" + state;
	makeAjaxCall( 'payment.act', queryString, null, 'rightContent', 'callbackLoadInitialBalanceShippingAddress', '', [ index, showAddress ]);
	
}

function callbackLoadInitialBalanceShippingAddress( message, errorCode, states, index, showAddress) {
	if( message != "" ) {
		showMessage( message, errorCode, 'dataContent' );
	} else {
 		document.getElementById( "state_balancePayment_div_"+index ).innerHTML = '<label>State<span class="sup">*</span>:&nbsp;<select name="state_balancePayment_'+index+'" id="state_balancePayment_'+index+'" class="fs11 textbox w166"><option value = "">Select</option>' + states + '</select></label>';
 		document.getElementById( "state_balancePayment_"+index ).value = document.getElementById( "state" ).value;	
 		document.getElementById( "street1_balancePayment_"+index ).value = document.getElementById( "street1" ).value;
		document.getElementById( "street2_balancePayment_"+index ).value = document.getElementById( "street2" ).value;
		document.getElementById( "city_balancePayment_"+index ).value = document.getElementById( "city" ).value;	
		document.getElementById( "country_balancePayment_"+index ).value = document.getElementById( "country" ).value;
		document.getElementById( "zip_balancePayment_"+index ).value = document.getElementById( "zip" ).value;
		if(showAddress) {
			document.getElementById( "shippingAddressDiv_balancePayment_"+index).style.display="block";
		}		
	}
	return true;
}

function loadStatesForBalancePayment(ccIndex) {
	var country = document.getElementById( "country_balancePayment_"+ccIndex ).value;
	var	state = document.getElementById( "state_balancePayment_"+ccIndex ).value;
	var queryString = 'pm=4';
	queryString += "&country=" + country;
	queryString += "&state=" + state;
	makeAjaxCall( 'payment.act', queryString, null, 'rightContent', 'callbackLoadStatesForBalancePayment', '', [ccIndex]);
}


function callbackLoadStatesForBalancePayment( message, errorCode, states, ccIndex) {
	if( message != "" ) {
		showMessage( message, errorCode, 'dataContent' );
	} else {
		document.getElementById( "state_balancePayment_div_"+ccIndex ).innerHTML = '<label>State<span class="sup">*</span>:&nbsp;<select name="state_balancePayment_'+ccIndex+'" id="state_balancePayment_'+ccIndex+'" class="fs11 textbox w166"><option value = "">Select</option>' + states + '</select></label>';
	}
}

function addBalanceCreditCard( ) {
	clearErrorElements();
	var previousCardAmount = 0;
	var creditCardAmount;
	if ( _numberOfBalanceCreditCards >= 1 && _numberOfBalanceCreditCards < _maxCreditCards ) {
	       for ( var index = 0; index < _numberOfBalanceCreditCards; index++ ) {
    				creditCardAmount = document.getElementById( "creditCardAmount_balancePayment_"+index).value;
    				previousCardAmount = parseFloat( previousCardAmount + parseFloat( creditCardAmount ) );
    			}
    			if( parseFloat( previousCardAmount ) >= parseFloat( _balanceAmount ) ) {
    				showErrorMessage( 'Total amount already matches balance.', 'dataContent', 'creditCardAmount_balancePayment_' + ( _numberOfBalanceCreditCards - 1 ), '1px solid #7f9db9' );
    				return false;
    		}
	        var paymentMode= getCheckedValue(document.getElementsByName("paymentMode"));
	        if(paymentMode == 'BALANCE_PAYMENT') {	            			
    			creditCardAmount = parseFloat( parseFloat( _balanceAmount - parseFloat( previousCardAmount ) ) ).toFixed(2);
	        }else {
	            creditCardAmount = "";
	        }	
			document.getElementById( "currentPaymentDataDiv_" + _numberOfBalanceCreditCards ).style.display = "block";
			document.getElementById( "remove_balancePayment_" +( _numberOfBalanceCreditCards-1 ) ).style.display = "none";
			document.getElementById( "remove_balancePayment_" + _numberOfBalanceCreditCards ).style.display = "block";
			document.getElementById( "creditCardAmount_balancePayment_div_"+_numberOfBalanceCreditCards ).innerHTML = getBalanceCreditCardRowAsHTML(_numberOfBalanceCreditCards, 0.0);
			document.getElementById( "creditCardAmount_balancePayment_"+ _numberOfBalanceCreditCards ).value = creditCardAmount;
			loadInitialBalanceShippingAddress(_numberOfBalanceCreditCards, false);
			_numberOfBalanceCreditCards++;			
		} else if ( _numberOfBalanceCreditCards == _maxCreditCards ) {
			showWarningMessage( "You are allowed only " + _maxCreditCards + " credit cards", "dataContent" );
	}
	return true;
}

function removeBalanceCreditCard( index ) {
	var previousCardAmount = 0;
	var creditCardAmount;
	document.getElementById( "currentPaymentDataDiv_" +index ).style.display = "none";
	
	if(index != 1 ){
		document.getElementById( "remove_balancePayment_" +(index-1) ).style.display = "block";
	}	
	_numberOfBalanceCreditCards--;
	var paymentMode= getCheckedValue(document.getElementsByName("paymentMode"));
	if(paymentMode == 'BALANCE_PAYMENT') {
    	// Re populating the amount
    	for ( var count = 0; count < index-1; count++ ) {
    		creditCardAmount = document.getElementById( "creditCardAmount_balancePayment_"+count).value;
    		previousCardAmount = parseFloat( previousCardAmount + parseFloat( creditCardAmount ) );
    	}
    	document.getElementById( "creditCardAmount_balancePayment_" +(index-1) ).value = parseFloat( parseFloat( _balanceAmount - parseFloat( previousCardAmount ) ) ).toFixed(2);
	}
}

function loadBalancePayment() {
	var queryString = 'pm=0';
	makeAjaxCall( 'balancePayment.act', queryString, null, 'rightContent', 'callbackLoadBalancePayment');
}


function callbackLoadBalancePayment(message, errorCode) {
	showMessage( message, errorCode, 'dataContent' );
	return true;
}

function validateBalanceCreditCardAmount( ) {
	clearErrorElements();
	var totalCreditCardAmount = 0;
	var creditCardAmount;
	for ( var index = 0; index < _numberOfBalanceCreditCards; index++ ) {
		creditCardAmount = document.getElementById( "creditCardAmount_balancePayment_"+index).value;
		totalCreditCardAmount = parseFloat( totalCreditCardAmount + parseFloat( creditCardAmount ) );
	}
	var balanceAmount = parseFloat(_balanceAmount );
	totalCreditCardAmount = parseFloat ( parseFloat( totalCreditCardAmount ).toFixed(2) );	
	
	if( totalCreditCardAmount > balanceAmount ) {
		showErrorMessage( 'You have entered payments totaling $' + totalCreditCardAmount + ' which is greater than the balance amount owed on your booking.', 'dataContent', 'creditCardAmount_balancePayment_0', '1px solid #7f9db9');
		return false;
	}
	
	var paymentMode= getCheckedValue(document.getElementsByName("paymentMode"));
	if(paymentMode == 'BALANCE_PAYMENT') {
		if ( totalCreditCardAmount < balanceAmount ) {
			showErrorMessage( 'You have entered payments totaling $' + totalCreditCardAmount + ' which is less than the balance amount owed on your booking.', 'dataContent', 'creditCardAmount_balancePayment_0', '1px solid #7f9db9');
			return false;
		}
	} 
	return true;
}

function createBalancePayment() {
	clearErrorElements();
	var balancePaymentInfo = new BalancePaymentInfo();
	balancePaymentInfo.creditCardInfoArray = new Array();
	
	var currentDate = getCurrentDate();
	var currentMonth = currentDate.getMonth();
	var currentYear = currentDate.getFullYear();
	
	for ( var index = 0; index < _numberOfBalanceCreditCards; index++ ) {
		var creditCardInfo = new CreditCardInfo();
		
		if( !validateField( 'creditCardNumber_balancePayment_' + index , 'Please enter credit card number.' ) ) {
			return false;
		}
		
		if( !validateField( 'creditCardExpirationMonth_balancePayment_' + index , 'Please enter credit card expiration month.'  ) ) {
			return false;
		}
		
		if( !validateField( 'creditCardExpirationYear_balancePayment_' + index , 'Please enter credit card expiration year.'  ) ) {
			return false;
		}
		
		creditCardInfo.creditCardExpirationMonth = document.getElementById( "creditCardExpirationMonth_balancePayment_"+index).value;
		creditCardInfo.creditCardExpirationYear = document.getElementById( "creditCardExpirationYear_balancePayment_"+index).value;
		if( creditCardInfo.creditCardExpirationYear < currentYear || ( ( currentYear == creditCardInfo.creditCardExpirationYear ) && creditCardInfo.creditCardExpirationMonth <= currentMonth ) ) {
			showErrorMessage('Please enter valid expiration date.', 'dataContent', 'creditCardExpirationMonth_balancePayment_'+index, '1px solid #7f9db9');
			return false;
		}
		
		if( !validateField( 'creditCardAmount_balancePayment_' + index , 'Please enter valid amount.'  ) ) {
			return false;
		}
		
		creditCardInfo.creditCardAmount = document.getElementById( "creditCardAmount_balancePayment_"+index).value;
		if(!isFloat(creditCardInfo.creditCardAmount)) {
			showErrorMessage('Amount entered is not valid. Please enter a valid amount.', 'dataContent', 'creditCardAmount_balancePayment_'+index, '1px solid #7f9db9');
			return false;
		}
		
		if ( parseFloat(creditCardInfo.creditCardAmount) <= 0 ) {
			showErrorMessage('Amount cannot be zero. Please enter amount greater than zero.', 'dataContent', 'creditCardAmount_balancePayment_'+index, '1px solid #7f9db9');
			return false;
		}
		
		if( !validateField( 'creditCardSecurityCode_balancePayment_' + index , 'Please enter security number.'  ) ) {
			return false;
		}
		creditCardInfo.creditCardSecurityCode = document.getElementById( "creditCardSecurityCode_balancePayment_"+index).value;
		creditCardInfo.cardHolderName = document.getElementById( "creditCardHolderName_balancePayment_"+index).value;
		creditCardInfo.creditCardNumber = document.getElementById( "creditCardNumber_balancePayment_"+index).value;
		creditCardInfo.cardType = checkCreditCard( creditCardInfo.creditCardNumber );
		
		if(creditCardInfo.cardType == 'UNKNOWN') {
			showErrorMessage('The accepted forms of payment are Visa, MasterCard and American Express' + String.fromCharCode('174') +'.  Please try again using one of these credit cards.', 'dataContent', 'creditCardNumber_balancePayment_' + index, '1px solid #7f9db9');
			return false;
		}
		
		if ( creditCardInfo.creditCardSecurityCode.length < 3 || ( creditCardInfo.cardType == 'AmExCard' && creditCardInfo.creditCardSecurityCode.length < 4 )) {
			showErrorMessage('Please enter valid security number', 'dataContent', 'creditCardSecurityCode_balancePayment_'+index, '1px solid #7f9db9');
			return false;
		}
		
		if( !validateField( 'creditCardHolderName_balancePayment_' + index , 'Please enter Card holder name.'  ) ) {
			return false;
		}
		
		if( !validateField( 'street1_balancePayment_' + index , 'Please enter street.') ) {
			return false;
		}
		
		if( !validateField( 'city_balancePayment_' + index, 'Please enter city.') ) {
			return false;
		}
		
		if( !validateField( 'state_balancePayment_' + index, 'Please select a state.') ) {
			return false;
		}
		
		if( !validateField( 'zip_balancePayment_' + index, 'Please enter zip.') ) {
			return false;
		}
		
		if(!validateBalanceCreditCardAmount()) {
			return false;
		}	

		creditCardInfo.street1 = document.getElementById( "street1_balancePayment_"+index).value;
		creditCardInfo.street2 = document.getElementById( "street2_balancePayment_"+index).value;
		creditCardInfo.city = document.getElementById( "city_balancePayment_"+index).value;
		creditCardInfo.state = document.getElementById( "state_balancePayment_"+index).value;
		creditCardInfo.country = document.getElementById( "country_balancePayment_"+index).value;
		creditCardInfo.zip = document.getElementById( "zip_balancePayment_"+index).value;
		balancePaymentInfo.creditCardInfoArray[index] = creditCardInfo;		
		
		var paymentMode= getCheckedValue(document.getElementsByName("paymentMode"));
		if(paymentMode == 'BALANCE_PAYMENT') {
		  balancePaymentInfo.isBalancePayment = true;  
		  balancePaymentInfo.isAnotherPayment = false;    
		}else {
		  balancePaymentInfo.isBalancePayment = false;  
		  balancePaymentInfo.isAnotherPayment = true;    		    
		}		
	}
	
	var queryString = 'bpm=2';
	queryString += "&balancePaymentDetail=" + balancePaymentInfo.toJSONString();
	makeAjaxCall( 'balancePayment.act', queryString, null, 'rightContent', 'callbackMakeBalancePayment', '' );
}	

function callbackMakeBalancePayment( message, errorCode ) {
	showMessage( message, errorCode, 'dataContent' );
	return true;
}

function loadBalancePaymentConfirmation(balancePaymentDetail) {
	var queryString = 'bpm=3&balancePaymentDetail=' + balancePaymentDetail;
	makeAjaxCall( 'balancePayment.act', queryString, null, 'rightContent', 'callbackLoadBalancePaymentConfirmation', '' );	
}

function callbackLoadBalancePaymentConfirmation( message, errorCode ) {
	showMessage( message, errorCode, 'dataContent' );
	return true;
}

function onPaymentModeChange() {
  var paymentMode= getCheckedValue(document.getElementsByName("paymentMode"));
  if(paymentMode == 'BALANCE_PAYMENT' && _numberOfBalanceCreditCards == 1) {      
    document.getElementById( "creditCardAmount_balancePayment_0").value = _balanceAmount;      
  }     
}

function applyPayment(bookingId) {
	var queryString = 'cf=2';
	queryString += '&bookingId=' + bookingId;
	disableElement( 'dataContent', true );
	asynchronousRequest = new AsynchronousRequest();
	asynchronousRequest.url = _webLoc + '/paymentConfirm.act';
	asynchronousRequest.queryString = queryString;
	asynchronousRequest.useAjax = true;
	asynchronousRequest.target = 'rightContent';
	asynchronousRequest.callbackFunctionName = 'callbackApplyPayment';

	var splashScreenRequest = new SplashScreenRequest();
	splashScreenRequest.splashScreenText = "Please Wait...";
	asynchronousRequest.splashScreenRequest = splashScreenRequest;
	asynchronousRequest.splashScreenDisplayFunctionName = "displaySearchingPopup";
	asynchronousRequest.splashScreenHideFunctionName = "hideSearchingPopup";

	//making Ajax call with '/vp/booking/bookingConfirmation/<destinationCode>/<regionCode>/package/<packageId>' as the description to be passed into Google Analytics
	makeAjaxCallWithRequest( asynchronousRequest, '/vp/booking/bookingConfirmation/' + _destinationCode + '/' + _regionCode + '/package/' + _packageId );
	
}

function callbackApplyPayment( message, errorCode, paymentException ) {
	disableElement( 'dataContent', false );
	if( message != '' ) {
		showMessage( message, errorCode, 'dataContent' );
	} else {
		clearErrorElements();
		if( paymentException != null || paymentException != undefined ) { 
			showErrorMessage( paymentException, 'dataContent' );
			return false;
		}
	}
	return true;
}



function submitSpecialRequests(noOfProducts) {
// This is a vaidation that ensures that the Arrival and Departure Transfers when selected ,
// Should also have the information related to the fligthNumber, fligth Time and the
// realted.

	var specialRequestParams = new Array(
		new Array("sr", "1"));

	var specialReqParamsIndex = 1;

	for ( i = 0; i < parseInt( noOfProducts ); i++ ) {
		var selectedOption = "selected";
		no_flightinfo = "false";
		var a_airCode = "";
		var a_airport = "";
		var a_airlineNo = "";
		var a_transferDate = "";
		var a_transferTime = "";
		var d_airCode = "";
		var d_airport = "";
		var d_airlineNo = "";
		var d_transferDate = "";
		var d_transferTime = "";
		var no_flightinfo = "false";
		var hotelOptions = "";
		var railOptions = "";
		var hotelRemark = "";
		var railRemark = "";
		var ferryRemark = "";
		var hotelOptionName;
		var railOptionName1;
		var railOptionName2;
		var railOptionName3;
		var carOptionName;
		var carOptions = "";
		var jsonFormattedString = "";
		var pickupDate = "";
		var pickupTime = "";
		var dropoffDate = "";
		var dropoffTime = "";

		if( document.getElementById( selectedOption + "ArrivalOption_" + i + "_AirCode" )!= null ) {

	    	if( !validateArrivalAndDepartureTransfers( selectedOption + "ArrivalOption_" + i, i ) ) {
			  return false;
		  	}

		  	  //arrival transfer special requests
			 a_airCode = document.getElementById( selectedOption + "ArrivalOption_" + i + "_AirCode" ).value;

			 a_airport = document.getElementById( selectedOption + "ArrivalOption_" + i + "_Airport" ).value;
			 a_airlineNo = document.getElementById( selectedOption + "ArrivalOption_" + i + "_AirlineNumber" ).value;
			 a_transferDate = document.getElementById( selectedOption + "ArrivalOption_" + i + "_TransferDate" ).value;
			 a_transferTime = document.getElementById( selectedOption + "ArrivalOption_" + i + "_TransferTime" ).value;
			 if( document.getElementById( "noFlightInfo_" + i ).checked ) {
			 	no_flightinfo = "true";
			 }
		}

		if( document.getElementById( selectedOption + "DepartOption_" + i + "_AirCode" )!= null ) {
			if( !validateArrivalAndDepartureTransfers( selectedOption + "DepartOption_" + i, i ) ) {
				return false;
			}
			  //departure transfer special requests
			 d_airCode = document.getElementById( selectedOption + "DepartOption_" + i + "_AirCode" ).value;
			 d_airport = document.getElementById( selectedOption + "DepartOption_" + i + "_Airport" ).value;
			 d_airlineNo = document.getElementById( selectedOption + "DepartOption_" + i + "_AirlineNumber" ).value;
			 d_transferDate = document.getElementById( selectedOption + "DepartOption_" + i + "_TransferDate" ).value;
			 d_transferTime = document.getElementById( selectedOption + "DepartOption_" + i + "_TransferTime" ).value;
			 if( document.getElementById( "noFlightInfo_" + i ).checked ) {
			 	no_flightinfo = "true";
			 }
		}

		//hotel special requests
		 hotelOptionName = 	document.getElementsByName( selectedOption + "HotelOption_" + i );

		 if( hotelOptionName.length > 0 ) {
			for( len = 0; len< hotelOptionName.length; len++ ) {
				if( hotelOptionName[len].checked ) {
					if( hotelOptions == "" ) {
						hotelOptions = hotelOptionName[len].value;
					} else {
						hotelOptions = hotelOptions + "," + hotelOptionName[len].value;
					}
				}
			}
		}

		if( document.getElementById( selectedOption + "HotelRemark_" + i ) != null ) {
		 	hotelRemark = document.getElementById( selectedOption + "HotelRemark_" + i ).value;
		}
		//rail special requests
		railOptionName1 = document.getElementById( selectedOption + "RailOption_" + i + "_1" );
		railOptionName2 = document.getElementById( selectedOption + "RailOption_" + i + "_2" );
		railOptionName3 = document.getElementById( selectedOption + "RailOption_" + i + "_3" );

		if( ( railOptionName1 != null )&& ( railOptionName2 != null ) && ( railOptionName3 != null ) ) {
			if ( railOptionName1.value == railOptionName2.value || railOptionName1.value == railOptionName3.value ) {
				showErrorMessage( "Rail Preferred Times  should have different timings, Please select different timings.", "dataContent", "1px solid #7f9db9" );
	            document.getElementById( selectedOption + "RailOption_" + i + "_1" ).focus();
				return false;
			}
			if ( railOptionName2.value == railOptionName3.value ) {
				showErrorMessage( "Rail Preferred Times should have different timings, Please select different timings.", "dataContent", "1px solid #7f9db9" );
	            document.getElementById( selectedOption + "RailOption_" + i + "_2" ).focus();
				return false;
			}
			railOptions = railOptionName1.value + "," + railOptionName2.value + "," + railOptionName3.value;
		}
		if( document.getElementById( selectedOption + "RailRemark_" + i ) != null ) {
		 	railRemark = document.getElementById( selectedOption + "RailRemark_" + i ).value;
		}
		//ferry special requests
		if( document.getElementById( selectedOption + "FerryRemark_" + i )!= null ) {
		 	ferryRemark = document.getElementById( selectedOption + "FerryRemark_" + i ).value;
		}

		//car options:
		carOptionName = document.getElementsByName( selectedOption + "CarOption_" + i );
		 if( carOptionName.length > 0 )	{
			for( len = 0;len < carOptionName.length; len++ )	{
				if( carOptionName[len].checked ) {
					if( carOptions == "" ) {
						carOptions = carOptionName[len].value;
					} else {
						carOptions = carOptions + "," + carOptionName[len].value;
					}
				}
			}
		}
		if( document.getElementById( selectedOption + "CarOption_" + i + "_ArrivalAirCode" ) != null ) {
	    	  //car arrival options:
			 a_airCode = document.getElementById( selectedOption + "CarOption_" + i + "_ArrivalAirCode" ).value;
			 a_airport = document.getElementById( selectedOption + "CarOption_" + i + "_ArrivalAirport" ).value;
			 a_airlineNo = document.getElementById( selectedOption+ "CarOption_" + i + "_ArrivalAirlineNumber" ).value;
			 a_transferDate = document.getElementById( selectedOption + "CarOption_" + i + "_ArrivalTransferDate" ).value;
			 a_transferTime = document.getElementById( selectedOption + "CarOption_" + i + "_ArrivalTransferTime" ).value;
		}

		if( document.getElementById( selectedOption + "CarOption_" + i + "_DepartureAirCode" )!= null ) {
	    	  //car departure options:
			 d_airCode = document.getElementById( selectedOption + "CarOption_" + i + "_DepartureAirCode" ).value;
			 d_airport = document.getElementById( selectedOption + "CarOption_" + i + "_DepartureAirport" ).value;
			 d_airlineNo = document.getElementById( selectedOption+ "CarOption_" + i + "_DepartureAirlineNumber" ).value;
			 d_transferDate = document.getElementById( selectedOption + "CarOption_" + i + "_DepartureTransferDate" ).value;
			 d_transferTime = document.getElementById( selectedOption + "CarOption_" + i + "_DepartureTransferTime" ).value;
		}
		specialRequestParams[specialReqParamsIndex] = 	new Array( selectedOption+"HotelOption_" + i, hotelOptions );
		specialRequestParams[++specialReqParamsIndex] = new Array( selectedOption+"HotelRemark_" + i, escape( hotelRemark ) );
		specialRequestParams[++specialReqParamsIndex] = new Array( selectedOption+"RailOption_" + i, railOptions);
		specialRequestParams[++specialReqParamsIndex] = new Array( selectedOption+"RailRemark_" + i, escape( railRemark ) );
		specialRequestParams[++specialReqParamsIndex] = new Array( selectedOption+"FerryRemark_" + i, escape( ferryRemark ) );
		specialRequestParams[++specialReqParamsIndex] = new Array( selectedOption+"ArrivalOption_" + i + "_AirCode", a_airCode );
		specialRequestParams[++specialReqParamsIndex] = new Array( selectedOption+"ArrivalOption_" + i + "_Airport", a_airport );
		specialRequestParams[++specialReqParamsIndex] = new Array( selectedOption+"ArrivalOption_" + i + "_AirlineNumber", a_airlineNo );
		specialRequestParams[++specialReqParamsIndex] = new Array( selectedOption+"ArrivalOption_" + i + "_TransferDate", a_transferDate );
		specialRequestParams[++specialReqParamsIndex] = new Array( selectedOption+"ArrivalOption_" + i + "_TransferTime", a_transferTime );
		specialRequestParams[++specialReqParamsIndex] = new Array( selectedOption+"noFlightInfo_" + i , no_flightinfo );
		specialRequestParams[++specialReqParamsIndex] = new Array( selectedOption+"DepartOption_" + i + "_AirCode", d_airCode );
		specialRequestParams[++specialReqParamsIndex] = new Array( selectedOption+"DepartOption_" + i + "_Airport", d_airport );
		specialRequestParams[++specialReqParamsIndex] = new Array( selectedOption+"DepartOption_" + i + "_AirlineNumber", d_airlineNo );
		specialRequestParams[++specialReqParamsIndex] = new Array( selectedOption+"DepartOption_" + i + "_TransferDate", d_transferDate );
		specialRequestParams[++specialReqParamsIndex] = new Array( selectedOption+"DepartOption_" + i + "_TransferTime", d_transferTime );
		specialRequestParams[++specialReqParamsIndex] = new Array( selectedOption+"CarOption_" + i, carOptions );
		specialRequestParams[++specialReqParamsIndex] = new Array( selectedOption+"CarOption_" + i+ "_ArrivalAirCode", a_airCode );
		specialRequestParams[++specialReqParamsIndex] = new Array( selectedOption+"CarOption_" + i+ "_ArrivalAirlineNumber", a_airlineNo );
		specialRequestParams[++specialReqParamsIndex] = new Array( selectedOption+"CarOption_" + i+ "_ArrivalAirport", a_airport );
		specialRequestParams[++specialReqParamsIndex] = new Array( selectedOption+"CarOption_" + i+ "_ArrivalTransferDate", a_transferDate );
		specialRequestParams[++specialReqParamsIndex] = new Array( selectedOption+"CarOption_" + i+ "_ArrivalTransferTime", a_transferTime );
		specialRequestParams[++specialReqParamsIndex] = new Array( selectedOption+"CarOption_" + i+ "_DepartureAirCode", d_airCode );
		specialRequestParams[++specialReqParamsIndex] = new Array( selectedOption+"CarOption_" + i+ "_DepartureAirlineNumber", d_airlineNo );
		specialRequestParams[++specialReqParamsIndex] = new Array( selectedOption+"CarOption_" + i+ "_DepartureAirport", d_airport );
		specialRequestParams[++specialReqParamsIndex] = new Array( selectedOption+"CarOption_" + i+ "_DepartureTransferDate", d_transferDate );
		specialRequestParams[++specialReqParamsIndex] = new Array( selectedOption+"CarOption_" + i+ "_DepartureTransferTime", d_transferTime );

		specialReqParamsIndex = specialReqParamsIndex + 1;
	}
	
	//Make Ajax call with '/vp/booking/paymentDetails/<destinationCode>/<regionCode>/<packageId>' as the description to be passed into Google Analytics'
	var trackingText = '/vp/booking/paymentDetails/' + _destinationCode + '/' + _regionCode + '/package/' + _packageId;
	makeAjaxCall( 'specialRequests.act', "", specialRequestParams, 'rightContent', 'callbackCreateSpecialRequests', trackingText );
}

function callbackCreateSpecialRequests( message, errorCode ) {
	showMessage( message, errorCode, 'dataContent' );
	return true;
}

 // The fieldName indicates whether it is an Arrival Transfer or Departure Transfer.
 // Based on this we validate the fields.
function validateArrivalAndDepartureTransfers( fieldName,indexNo ){
	// fieldName will have value as selectedDepartOption_i or selectedArrivalOption_i

	clearErrorElements();
   	if( !document.getElementById( "noFlightInfo_" + indexNo ).checked ) {
    	document.getElementById( "noFlightInfo_" + i ).value = "true";
	    if( trim( document.getElementById( ( fieldName + "_" + "AirCode" ) ).value )== "" ) {
			showErrorMessage( "Please select the Airline", "dataContent", fieldName + "_" + "AirCode", "1px solid #7f9db9" );
            document.getElementById((fieldName+"_" +"AirCode" )).focus();
			return false;
		}
		if( document.getElementById( ( fieldName + "_" + "AirlineNumber" ) ).value=="" ) {
			showErrorMessage( "Please enter the Flight Number", "dataContent", fieldName + "_" + "AirlineNumber", "1px solid #7f9db9");
            document.getElementById( ( fieldName + "_" + "AirlineNumber" ) ).focus();
			return false;
		}
		if( trim( document.getElementById( ( fieldName + "_" + "TransferDate" ) ).value ) == "" || document.getElementById( ( fieldName + "_" + "TransferDate" ) ).value == "mm/dd/yyyy" ) {
			showErrorMessage( "Please select the Flight Date", "dataContent", fieldName + "_" + "TransferDate", "1px solid #7f9db9" );
            document.getElementById( ( fieldName + "_" + "TransferDate" ) ).focus();
			return false;
		}
		if( trim( document.getElementById( ( fieldName + "_" + "TransferTime" ) ).value ) == "" ) {
			showErrorMessage( "Please enter the Flight Time", "dataContent", fieldName + "_" + "TransferTime", "1px solid #7f9db9" );
            document.getElementById( ( fieldName + "_" + "TransferTime" ) ).focus();
			return false;
		}
	} else {
		document.getElementById( "noFlightInfo_" + i ).value = "false";
	}
	return true;
}

function loadSpecialRequests() {
	var queryString = 'sr=0';

	//Make Ajax call with '/vp/booking/specialRequests/<destinationCode>/<regionCode>/<packageId>' as the description to be passed into Google Analytics'
	trackingText = '/vp/booking/specialRequests/' + _destinationCode + '/' + _regionCode + '/package/' + _packageId;
	makeAjaxCall('specialRequests.act', queryString, null, 'rightContent', 'callbackLoadSpecialRequests', trackingText);
}

function callbackLoadSpecialRequests() {
	document.title = "Costco Travel";
}

function hideFlightInfo( indexNo ) {
	if( document.getElementById( "noFlightInfo_" + indexNo ).checked ) {
		document.getElementById( "flightInformation_" + indexNo ).style.display = 'none';
		document.getElementById( "noFlightInfo_" + indexNo ).value = "true";
	} else {
		document.getElementById( "flightInformation_" + indexNo ).style.display = 'block';
		document.getElementById( "noFlightInfo_" + indexNo ).value = "false";
	}
}

function storePickupTime( pickupTime ) {
	var i = 0;
	selectedTime = pickupTime + '_selectedPickupTime';
	pickupTime = pickupTime + '_pickupTime';
	var pickupTimeInCity = document.getElementById( pickupTime );
	i = pickupTimeInCity.selectedIndex;
	document.getElementById( selectedTime ).value = pickupTimeInCity.value == "-1" ? "": pickupTimeInCity.options[i].text;
}

function storeDropoffTime( returnTime ) {
	var i = 0;
	selectedTime = returnTime + '_selectedDropoffTime';
	returnTime = returnTime + '_dropoffTime';
	var returnTimeInCity = document.getElementById( returnTime );
	i = returnTimeInCity.selectedIndex;
	document.getElementById( selectedTime ).value = returnTimeInCity.value == "-1" ? "": returnTimeInCity.options[i].text;
}var _totalCruiseTripProtectionAmount = 0;
function showCruiseInformationDiv( cruiseSailingItemUid, selectedTab ) {
	if( document.getElementById ( "cruiseInfoPopupDivContainer" ) ){
		removeElement( 'cruiseInfoPopupDivContainer' );
	}
	createPopupDiv ( "cruiseInfoPopupDivContainer" , -1 , -1, -1, 200, false , true , "" );
	disableElement( "dataContent", true );

	var queryString = "cb=10";
	queryString += "&itemUid=" + cruiseSailingItemUid;
	queryString += "&selectedTab=" + selectedTab;

	makeAjaxCallWithWaitingDiv( "cruiseBooking.act" , queryString , null , "cruiseInfoPopupDivContainer" , "callbackShowCruiseInformationDiv", '' );
}

function callbackShowCruiseInformationDiv( ) {
	if ( !( showMessage( this.errorMessage, this.errorCode , 'dataContent' ) ) ) {
		showBlock( "cruiseInfoPopupDivContainer" );
		positionBlockCentrally( "cruiseInfoPopupDivContainer" );
		disableElement( "dataContent" , true );
	}
}

function loadPaymentInfo() {
	var queryString = 'pm=0';
	
	//Load the payment details screen with '/cr/booking/bookingWidget/paymentDetails/<destination>/<cruiseLine>/<ship>/<date>' as the description to be passed into Google Analytics
	var trackingText = '/cr/booking/bookingWidget/paymentDetails/' + _destinationName + '/' + _cruiseLineName + '/' + _shipName + '/' + _departureDate;
	
	makeAjaxCall( 'payment.act', queryString, null, 'rightContent', 'callbackLoadPaymentInfo', trackingText );
}

function callbackLoadPaymentInfo() {
	if ( !( showMessage( this.errorMessage, this.errorCode , 'dataContent' ) ) ) {
		disableElement ( "dataContent" , false );
	}
}

function toggleCruiseTripProtection() {
}

function callbackToggleCruiseTripProtection( message, errorCode, packagePrice ) {
	
}

function loadCruiseTripProtectionPopup() {	
	var cruiseTripProtectionPopupDivContainer = createPopupDiv ( "cruiseTripProtectionPopupDivContainer" , - 1 , - 1 , - 1 , 200 , false , true , "" );
	cruiseTripProtectionPopupDivContainer.onkeypress = function( event ) { onKeyDownOnTripProtectionPopup(event) };
	disableElement( 'dataContent', true );
	var queryString = 'cb=11';
	
	//Load the trip protection screen with '/cr/booking/bookingWidget/searchIns/<destination>/<cruiseLine>/<ship>/<date>' as the description to be passed into Google Analytics
	var trackingText = '/cr/booking/bookingWidget/searchIns/' + _destinationName + '/' + _cruiseLineName + '/' + _shipName + '/' + _departureDate;

	makeAjaxCallWithWaitingDiv( 'cruiseBooking.act', queryString, null, 'cruiseTripProtectionPopupDivContainer', 'callbackLoadCruiseTripProtectionPopup', null, trackingText );	
}

function callbackLoadCruiseTripProtectionPopup() {
	if ( !( showMessage( this.errorMessage, this.errorCode , 'dataContent' ) ) ) {
		showBlock( 'cruiseTripProtectionPopupDivContainer' );
		positionBlockCentrally( 'cruiseTripProtectionPopupDivContainer' );	
	}
}

function PassengerTripProtection( passengerName, grossInsuranceAmount, netInsuranceAmount ) {
	this.passengerName = passengerName;
	this.grossInsuranceAmount = grossInsuranceAmount;
	this.netInsuranceAmount = netInsuranceAmount;
}

function applyTripProtection() {
	var passengerDetails = new Array();
	var numberOfPax = parseInt( document.getElementById( "numberOfPax" ).value, 10 );
	var isPaxSelected = false;
	var isDeclined = document.getElementById( "declineCruiseTripProtection" ).checked;
	if( !isDeclined ) {
		for( var index = 0 ; index < numberOfPax; index++ ) {
			if( document.getElementById( "insuranceCheckbox_" + index ).checked ) {
				isPaxSelected = true;
				var passengerName = document.getElementById( "passengerName_" + index ).value;
				var grossInsuranceAmount = document.getElementById( "grossInsuranceAmount_" + index ).value;
				var netInsuranceAmount = document.getElementById( "netInsuranceAmount_" + index ).value;
				var passengerTripProtection = new PassengerTripProtection( passengerName, grossInsuranceAmount, netInsuranceAmount );
				passengerDetails.push( passengerTripProtection );
			}
		}
		if( !isPaxSelected ) {
			showErrorMessage ( 'Please select at least one passenger or decline all' , 'cruiseTripProtectionPopupDivContainer' );
			return false;
		}
	}
	var queryString = "cb=12"; 
	queryString += "&selectedPassengers=" + passengerDetails.toJSONString();
	disableElement( 'cruiseTripProtectionPopupDivContainer', true );
	
	//Load the booking recap screen with '/cr/booking/bookingWidget/BookingRecap/<destination>/<cruiseLine>/<ship>/<date>' as the description to be passed into Google Analytics
	var trackingText = '/cr/booking/bookingWidget/BookingRecap/' + _destinationName + '/' + _cruiseLineName + '/' + _shipName + '/' + _departureDate;
	
	makeAjaxCallWithWaitingDiv( 'cruiseBooking.act', queryString, null, 'rightContent', 'callbackApplyTripProtection', null, trackingText );
}

function callbackApplyTripProtection() {
	if ( !( showMessage( this.errorMessage, this.errorCode , 'cruiseTripProtectionPopupDivContainer' ) ) ) {
		disableElement( 'cruiseTripProtectionPopupDivContainer', false );
		removeElement('cruiseTripProtectionPopupDivContainer')
		disableElement( 'dataContent', false );
	}
}

function toggelCruiseTripProtection( isDeclineTripProtection ) {
	var numberOfPax = parseInt( document.getElementById( "numberOfPax" ).value, 10 );
	if( isDeclineTripProtection ) {
		var totalInsuranceAmount = 0;
		for( var index = 0 ; index < numberOfPax ; index++ ) {
			var checkbox = document.getElementById( "insuranceCheckbox_" + index );
			if( checkbox.checked ) {
				checkbox.checked = false;
			}
			checkbox.disabled = true;
		}
		var packagePrice = parseFloat( document.getElementById( "totalCruisePackagePrice" ).value );
		packagePrice = packagePrice - _totalCruiseTripProtectionAmount;
		//updatePackagePrice( parseFloat( packagePrice ).toFixed( 2 ), 'totalCruisePackagePriceDisplay', 'totalCruisePackagePrice');
		document.getElementById( "totalCruisePackagePriceDisplay" ).innerHTML = "$"+parseFloat( packagePrice ).toFixed( 2 );
		document.getElementById( "totalCruisePackagePrice" ).value = parseFloat( packagePrice ).toFixed( 2 );
	} else {
		for( var index = 0 ; index < numberOfPax ; index++ ) {
			var checkbox = document.getElementById( "insuranceCheckbox_" + index );
			checkbox.disabled = false;
		}
	}
}

function updateCruisePackagePrice( paxIndex ) {
	var isChecked = document.getElementById( "insuranceCheckbox_" + paxIndex ).checked;
	var insuranceAmount = document.getElementById( "grossInsuranceAmount_" + paxIndex ).value;
	var packagePrice = parseFloat( document.getElementById( "totalCruisePackagePrice" ).value );
	if( isChecked ) {
		packagePrice = packagePrice + parseFloat( insuranceAmount );
		_totalCruiseTripProtectionAmount = _totalCruiseTripProtectionAmount  + parseFloat( insuranceAmount );
	} else {
		packagePrice = packagePrice - parseFloat( insuranceAmount );
		_totalCruiseTripProtectionAmount = _totalCruiseTripProtectionAmount - parseFloat( insuranceAmount );
	}
	//updatePackagePrice( parseFloat( packagePrice ).toFixed( 2 ), 'totalCruisePackagePriceDisplay', 'totalCruisePackagePrice');
	document.getElementById( "totalCruisePackagePriceDisplay" ).innerHTML = "$"+parseFloat( packagePrice ).toFixed( 2 );
	document.getElementById( "totalCruisePackagePrice" ).value = parseFloat( packagePrice ).toFixed( 2 );
}

function loadCruiseTaxesAndFeesPopup() {
	var cruiseTaxesAndFeesPopupDiv = document.getElementById('cruiseTaxesAndFeesPopupDiv');
	if(!cruiseTaxesAndFeesPopupDiv){
		cruiseTaxesAndFeesPopupDiv = createPopupDiv('cruiseTaxesAndFeesPopupDiv', 0, 0, 700, 300, false, true,  "tal popupDivBig");
	}
	disableElement('dataContent', true);
	makeAjaxCall('booking/cruise/cruiseTaxesAndFeesPopup.jsp', 'cruiseTaxesAndFeesPopup=true', null, 'cruiseTaxesAndFeesPopupDiv', 'callbackLoadCruiseTaxesAndFeesPopup', '');	
}

function callbackLoadCruiseTaxesAndFeesPopup() {
	document.title = "Costco Travel";	
	showBlock('cruiseTaxesAndFeesPopupDiv'); 
	positionBlockCentrally('cruiseTaxesAndFeesPopupDiv'); 
}
function updateCruiseSpecialRequest (isDiningSeatingMandatory) {
	var queryString = "crsr=1";
	var paxNumber = document.getElementById("paxNumber").value;
	var specialRequestsNumber = document.getElementById("specialRequestsNumber").value;
	
	var diningSeating = document.getElementById("diningSeating").value;
	
	if (isDiningSeatingMandatory){
		if( !( validateField( 'diningSeating', 'Please select dining seating.' ) ) ) {
			return false;
		}
	}
	
	var jsonSpecialOccasionFormattedString = "";
	var jsonSpecialRequestsFormattedString = "";
	var jsonMedicalRequestsFormattedString = "";

	for (var paxIndex = 1; paxIndex <= paxNumber; paxIndex++){
		if (document.getElementById("birthdayDate_" + paxIndex) && document.getElementById("anniversaryDate_" + paxIndex)){
			var birthdayDate = document.getElementById("birthdayDate_" + paxIndex).value;
			var anniversaryDate = document.getElementById("anniversaryDate_" + paxIndex).value;
			var isHoneymoonSelected = document.getElementById("honeymoon_" + paxIndex).checked;
			var paxName = document.getElementById("paxName_" + paxIndex).innerHTML;
			
			if (birthdayDate != "" && document.getElementById("birthdayCodeType")){
				var birthdayCodeType = document.getElementById("birthdayCodeType").value;
				var birthdayYears = document.getElementById("birthdayYears_" + paxIndex).value;
				
				if (trim(birthdayYears) == '' || birthdayYears == '0'){
					message = 'Please enter years celebrating birthday for passenger ' + paxName;
					showErrorMessage( message, 'dataContent', "birthdayYears_" + paxIndex, '1px solid #7f9db9' );
					return false;
				}

				jsonSpecialOccasionFormattedString += "{'requestCodeType':'" + birthdayCodeType + "',";
				jsonSpecialOccasionFormattedString += "'yearsToCelebrate':'" + birthdayYears + "',";
				jsonSpecialOccasionFormattedString += "'paxIndex':'" + paxIndex + "',";
				jsonSpecialOccasionFormattedString += "'occasionDate':" + "'" + birthdayDate + "'},";
			}	
	
			if (anniversaryDate != "" && document.getElementById("anniversaryCodeType")){
				var anniversaryCodeType = document.getElementById("anniversaryCodeType").value;
				var anniversaryYears = document.getElementById("anniversaryYears_" + paxIndex).value;

				if (trim(anniversaryYears) == '' || anniversaryYears == '0'){
					message = 'Please enter years celebrating anniversary for passenger ' + paxName;
					showErrorMessage( message, 'dataContent', "anniversaryYears_" + paxIndex, '1px solid #7f9db9' );
					return false;
				}
				
				jsonSpecialOccasionFormattedString += "{'requestCodeType':'" + anniversaryCodeType + "',";
				jsonSpecialOccasionFormattedString += "'yearsToCelebrate':'" + anniversaryYears + "',";
				jsonSpecialOccasionFormattedString += "'paxIndex':'" + paxIndex + "',";
				jsonSpecialOccasionFormattedString += "'occasionDate':" + "'" + anniversaryDate + "'},";
			}	
			
			if (isHoneymoonSelected && document.getElementById("honeymoonCodeType")){
				var honeymoonCodeType = document.getElementById("honeymoonCodeType").value;
				
				jsonSpecialOccasionFormattedString += "{'requestCodeType':'" + honeymoonCodeType + "',";
				jsonSpecialOccasionFormattedString += "'paxIndex':'" + paxIndex + "'},";
			}	
		}
	}	
	
	for (var specialRequestIndex = 0; specialRequestIndex < specialRequestsNumber; specialRequestIndex++ ){
		var specialRequestCheckbox = document.getElementById("specialRequest_" + specialRequestIndex);
		if (specialRequestCheckbox && specialRequestCheckbox.checked){
			jsonSpecialRequestsFormattedString += "{'requestCodeType':'" + specialRequestCheckbox.value + "',";
			jsonSpecialRequestsFormattedString += "'paxIndex':'0'},";
		}	
	}

	for (var paxIndex = 1; paxIndex <= paxNumber; paxIndex++){
		for (var specialRequestIndex = 0; specialRequestIndex < specialRequestsNumber; specialRequestIndex++ ){
			var medicalRequestCheckbox = document.getElementById("medicalRequest_" + specialRequestIndex + "_" + paxIndex);
			if (medicalRequestCheckbox && medicalRequestCheckbox.checked){
				jsonMedicalRequestsFormattedString += "{'requestCodeType':'" + medicalRequestCheckbox.value + "',";
				jsonMedicalRequestsFormattedString += "'paxIndex':'" + paxIndex + "'},";
			}	
		}	
	}
	
	jsonSpecialOccasionFormattedString = "{'SPECIAL_OCCASION_INFO':[" + jsonSpecialOccasionFormattedString.substring( 0, jsonSpecialOccasionFormattedString.lastIndexOf( "," ) ) + "]}";	
	jsonSpecialRequestsFormattedString = "{'SPECIAL_REQUESTS_INFO':[" + jsonSpecialRequestsFormattedString.substring( 0, jsonSpecialRequestsFormattedString.lastIndexOf( "," ) ) + "]}";	
	jsonMedicalRequestsFormattedString = "{'MEDICAL_REQUESTS_INFO':[" + jsonMedicalRequestsFormattedString.substring( 0, jsonMedicalRequestsFormattedString.lastIndexOf( "," ) ) + "]}";	
	
	var tableSizeElement = document.getElementById("tableSize");
	if(tableSizeElement) {		
		queryString += "&diningTableSize=" + tableSizeElement.value;
	}
	
	queryString += "&diningSeatingCode=" + diningSeating;
	queryString += "&specialOccasion=" + jsonSpecialOccasionFormattedString; 
	queryString += "&specialRequest=" + jsonSpecialRequestsFormattedString; 
	queryString += "&medicalRequest=" + jsonMedicalRequestsFormattedString;
	
	var cruiseTripProtectionPopupDivContainer = createPopupDiv('cruiseTripProtectionPopupDivContainer', -1, -1, -1, 200, false, true,  "");
	disableElement ( 'dataContent' , true );
	
	//Load the trip protection screen with '/cr/booking/bookingWidget/searchIns/<destination>/<cruiseLine>/<ship>/<date>' as the description to be passed into Google Analytics
	var trackingText = '/cr/booking/bookingWidget/searchIns/' + _destinationName + '/' + _cruiseLineName + '/' + _shipName + '/' + _departureDate;
	
	makeAjaxCallWithWaitingDiv ( 'cruiseSpecialRequests.act' , queryString , null , 'cruiseTripProtectionPopupDivContainer' , 'callbackUpdateCruiseSpecialRequest', null, trackingText );
}

function callbackUpdateCruiseSpecialRequest () {
	if ( ! ( showMessage ( this.errorMessage , this.errorCode , 'dataContent' ) ) ) {
		//loadCruiseTripSummary ();
		showBlock( 'cruiseTripProtectionPopupDivContainer' );
		positionBlockCentrally( 'cruiseTripProtectionPopupDivContainer' );
	}
}

function reLoadCruiseSpecialRequests () {
	var queryString = "crsr=0";

	disableElement ( 'dataContent' , true );
	makeAjaxCallWithWaitingDiv ( 'cruiseSpecialRequests.act' , queryString , null , 'rightContent' , 'callbackReLoadCruiseSpecialRequests' );
}

function callbackReLoadCruiseSpecialRequests () {
	if ( ! ( showMessage ( this.errorMessage , this.errorCode , 'dataContent' ) ) ) {
		loadCruiseTripSummary ();
		disableElement ( "dataContent" , false );
	}
}

function diningSeatingOnChange() {
	var diningSeatingList = document.getElementById("diningSeating");
	if (diningSeatingList.selectedIndex != ''){
		var gratuityRequired = document.getElementById("gratuityRequired_" + diningSeatingList.selectedIndex).value;
		if (gratuityRequired == "true"){
			modifyClassName(document.getElementById("diningGratuityNote"), "+displayBlock -displayNone");
		}
		else{
			modifyClassName(document.getElementById("diningGratuityNote"), "-displayBlock +displayNone");
		}	
	}
	
	for(var i=1; i< diningSeatingList.options.length; i++) {
		var sittingTypeTable = document.getElementById("sittingTypeTable_" + i);
		if(i == diningSeatingList.selectedIndex) {			
			modifyClassName(sittingTypeTable, "+displayBlock -displayNone");
		}else {
			modifyClassName(sittingTypeTable, "-displayBlock +displayNone");
		}
	}
}

function displayRequestGratuityNote(requestCheckbox, gratuityCode){
	var requestCodeType = requestCheckbox.value;
	
	if (requestCheckbox.checked && requestCodeType.substring(0,requestCodeType.indexOf('_') ) == gratuityCode){
		modifyClassName(document.getElementById("requestGratuityNote"), "+displayBlock -displayNone");
	}	
	if (!requestCheckbox.checked && requestCodeType.substring(0,requestCodeType.indexOf('_') ) == gratuityCode){
		modifyClassName(document.getElementById("requestGratuityNote"), "-displayBlock +displayNone");		
	}	
}

	Menu1=new Array("Home","javascript:loadHomePage();","",0,22,42);
        	
	Menu2=new Array("| What's New","javascript:loadGeneralInfo('whatsNew')","",0,22,90);
					
	Menu3=new Array("| Cruises","javascript:loadCruise();","",15,22,72);
	
				Menu3_1 = new Array("Azamara Club Cruises","javascript:loadCruiseLine('azamara');","",0,20,130);
			
				Menu3_2 = new Array("Carnival","javascript:loadCruiseLine('carnival');","",0,20,130);
			
				Menu3_3 = new Array("Celebrity","javascript:loadCruiseLine('celebrity');","",0,20,130);
			
				Menu3_4 = new Array("Crystal","javascript:loadCruiseLine('crystal');","",0,20,130);
			
				Menu3_5 = new Array("Cunard","javascript:loadCruiseLine('cunard');","",0,20,130);
			
				Menu3_6 = new Array("Disney Cruise Line®","javascript:loadCruiseLine('disneyCruiseLine');","",0,20,130);
			
				Menu3_7 = new Array("Holland America","javascript:loadCruiseLine('hollandAmerica');","",0,20,130);
			
				Menu3_8 = new Array("Norwegian Cruise Line","javascript:loadCruiseLine('norwegianCruiseLine');","",0,20,130);
			
				Menu3_9 = new Array("Paul Gauguin Cruises","javascript:loadCruiseLine('paulGauguinCruises');","",0,20,130);
			
				Menu3_10 = new Array("Princess","javascript:loadCruiseLine('princess');","",0,20,130);
			
				Menu3_11 = new Array("Regent","javascript:loadCruiseLine('regent');","",0,20,130);
			
				Menu3_12 = new Array("Royal Caribbean","javascript:loadCruiseLine('royalCaribbean');","",0,20,130);
			
				Menu3_13 = new Array("Seabourn","javascript:loadCruiseLine('seabourn');","",0,20,130);
			
				Menu3_14 = new Array("Uniworld","javascript:loadCruiseLine('uniworld');","",0,20,130);
			
				Menu3_15 = new Array("Windstar","javascript:loadCruiseLine('windstarCruiseLine');","",0,20,130);
			
	if(Menu3[3] > 0) {	
		if(Menu3_1) {
			Menu3_1[5] = (21 * 9);
		}
	}

	Menu4=new Array("| Destinations","javascript:loadDestinationHome();","",13,22,103);	
	
				Menu4_1 = new Array("Australia","javascript:loadDestination('australia');","",6,20,130);
			
					Menu4_1_1 = new Array("Adelaide & South Australia","javascript:loadRegion('australia', 'adelaideAndSouthAustralia');","",1,20,170);		
				
				Menu4_1_1_1 = new Array("Adelaide","javascript:loadArea('australia', 'adelaideAndSouthAustralia', 'adelaide');","",0,20,130);		
			
			if(Menu4_1_1[3] > 0) {
				if(Menu4_1_1_1) {
					Menu4_1_1_1[5] = (10 * 9);
				}
			}
		
					Menu4_1_2 = new Array("Ayers Rock & Northern Territory","javascript:loadRegion('australia', 'ayersRockAndNorthernTerritory');","",3,20,170);		
				
				Menu4_1_2_1 = new Array("Alice Springs","javascript:loadArea('australia', 'ayersRockAndNorthernTerritory', 'aliceSprings');","",0,20,130);		
			
				Menu4_1_2_2 = new Array("Ayers Rock","javascript:loadArea('australia', 'ayersRockAndNorthernTerritory', 'ayersRock');","",0,20,130);		
			
				Menu4_1_2_3 = new Array("Darwin","javascript:loadArea('australia', 'ayersRockAndNorthernTerritory', 'darwin');","",0,20,130);		
			
			if(Menu4_1_2[3] > 0) {
				if(Menu4_1_2_1) {
					Menu4_1_2_1[5] = (13 * 9);
				}
			}
		
					Menu4_1_3 = new Array("Great Barrier Reef & Queensland","javascript:loadRegion('australia', 'greatBarrierReefAndQueensland');","",4,20,170);		
				
				Menu4_1_3_1 = new Array("Brisbane","javascript:loadArea('australia', 'greatBarrierReefAndQueensland', 'brisbane');","",0,20,130);		
			
				Menu4_1_3_2 = new Array("Cairns","javascript:loadArea('australia', 'greatBarrierReefAndQueensland', 'cairns');","",0,20,130);		
			
				Menu4_1_3_3 = new Array("Palm Cove","javascript:loadArea('australia', 'greatBarrierReefAndQueensland', 'palmCove');","",0,20,130);		
			
				Menu4_1_3_4 = new Array("Port Douglas","javascript:loadArea('australia', 'greatBarrierReefAndQueensland', 'portDouglas');","",0,20,130);		
			
			if(Menu4_1_3[3] > 0) {
				if(Menu4_1_3_1) {
					Menu4_1_3_1[5] = (12 * 9);
				}
			}
		
					Menu4_1_4 = new Array("Melbourne","javascript:loadRegion('australia', 'melbourne');","",0,20,170);		
				
			if(Menu4_1_4[3] > 0) {
				if(Menu4_1_4_1) {
					Menu4_1_4_1[5] = (10 * 9);
				}
			}
		
					Menu4_1_5 = new Array("Perth","javascript:loadRegion('australia', 'perth');","",0,20,170);		
				
			if(Menu4_1_5[3] > 0) {
				if(Menu4_1_5_1) {
					Menu4_1_5_1[5] = (10 * 9);
				}
			}
		
					Menu4_1_6 = new Array("Sydney & New South Wales","javascript:loadRegion('australia', 'sydneyAndNewSouthWales');","",1,20,170);		
				
				Menu4_1_6_1 = new Array("Sydney","javascript:loadArea('australia', 'sydneyAndNewSouthWales', 'sydney');","",0,20,130);		
			
			if(Menu4_1_6[3] > 0) {
				if(Menu4_1_6_1) {
					Menu4_1_6_1[5] = (10 * 9);
				}
			}
		
		if(Menu4_1[3] > 0) {
			if(Menu4_1_1) {
				Menu4_1_1[5] = (31 * 9);
			}
		}
	
				Menu4_2 = new Array("Caribbean","javascript:loadDestination('caribbean');","",11,20,130);
			
					Menu4_2_1 = new Array("Antigua","javascript:loadRegion('caribbean', 'antigua');","",0,20,170);		
				
			if(Menu4_2_1[3] > 0) {
				if(Menu4_2_1_1) {
					Menu4_2_1_1[5] = (10 * 9);
				}
			}
		
					Menu4_2_2 = new Array("Aruba","javascript:loadRegion('caribbean', 'aruba');","",0,20,170);		
				
			if(Menu4_2_2[3] > 0) {
				if(Menu4_2_2_1) {
					Menu4_2_2_1[5] = (10 * 9);
				}
			}
		
					Menu4_2_3 = new Array("Bahamas","javascript:loadRegion('caribbean', 'bahamas');","",0,20,170);		
				
			if(Menu4_2_3[3] > 0) {
				if(Menu4_2_3_1) {
					Menu4_2_3_1[5] = (10 * 9);
				}
			}
		
					Menu4_2_4 = new Array("Dominican Republic","javascript:loadRegion('caribbean', 'dominicanRepublic');","",0,20,170);		
				
			if(Menu4_2_4[3] > 0) {
				if(Menu4_2_4_1) {
					Menu4_2_4_1[5] = (10 * 9);
				}
			}
		
					Menu4_2_5 = new Array("Grand Cayman","javascript:loadRegion('caribbean', 'grandCayman');","",0,20,170);		
				
			if(Menu4_2_5[3] > 0) {
				if(Menu4_2_5_1) {
					Menu4_2_5_1[5] = (10 * 9);
				}
			}
		
					Menu4_2_6 = new Array("Jamaica","javascript:loadRegion('caribbean', 'jamaica');","",0,20,170);		
				
			if(Menu4_2_6[3] > 0) {
				if(Menu4_2_6_1) {
					Menu4_2_6_1[5] = (10 * 9);
				}
			}
		
					Menu4_2_7 = new Array("Puerto Rico","javascript:loadRegion('caribbean', 'puertoRico');","",0,20,170);		
				
			if(Menu4_2_7[3] > 0) {
				if(Menu4_2_7_1) {
					Menu4_2_7_1[5] = (10 * 9);
				}
			}
		
					Menu4_2_8 = new Array("St. Lucia","javascript:loadRegion('caribbean', 'stLucia');","",0,20,170);		
				
			if(Menu4_2_8[3] > 0) {
				if(Menu4_2_8_1) {
					Menu4_2_8_1[5] = (10 * 9);
				}
			}
		
					Menu4_2_9 = new Array("St. Maarten/St. Martin","javascript:loadRegion('caribbean', 'stMaarten');","",0,20,170);		
				
			if(Menu4_2_9[3] > 0) {
				if(Menu4_2_9_1) {
					Menu4_2_9_1[5] = (10 * 9);
				}
			}
		
					Menu4_2_10 = new Array("Turks & Caicos","javascript:loadRegion('caribbean', 'turksAndCaicos');","",0,20,170);		
				
			if(Menu4_2_10[3] > 0) {
				if(Menu4_2_10_1) {
					Menu4_2_10_1[5] = (10 * 9);
				}
			}
		
					Menu4_2_11 = new Array("U.S. Virgin Islands","javascript:loadRegion('caribbean', 'usVirginIslands');","",0,20,170);		
				
			if(Menu4_2_11[3] > 0) {
				if(Menu4_2_11_1) {
					Menu4_2_11_1[5] = (10 * 9);
				}
			}
		
		if(Menu4_2[3] > 0) {
			if(Menu4_2_1) {
				Menu4_2_1[5] = (22 * 9);
			}
		}
	
				Menu4_3 = new Array("Cook Islands","javascript:loadDestination('cookIslands');","",2,20,130);
			
					Menu4_3_1 = new Array("Aitutaki","javascript:loadRegion('cookIslands', 'aitutaki');","",0,20,170);		
				
			if(Menu4_3_1[3] > 0) {
				if(Menu4_3_1_1) {
					Menu4_3_1_1[5] = (10 * 9);
				}
			}
		
					Menu4_3_2 = new Array("Rarotonga","javascript:loadRegion('cookIslands', 'rarotonga');","",0,20,170);		
				
			if(Menu4_3_2[3] > 0) {
				if(Menu4_3_2_1) {
					Menu4_3_2_1[5] = (10 * 9);
				}
			}
		
		if(Menu4_3[3] > 0) {
			if(Menu4_3_1) {
				Menu4_3_1[5] = (10 * 9);
			}
		}
	
				Menu4_4 = new Array("Escorted Vacations","javascript:loadAncillary('escortedVacations', 'VacationPackage');","",3,20,130);
								
					Menu4_4_1 = new Array("Adventures by Disney","javascript:loadAncillaryCategory('disney', 'adventuresByDisney', 'vacationPackage' );","",0,20,170);		
				
			if(Menu4_4_1[3] > 0) {
				if(Menu4_4_1_1) {
					Menu4_4_1_1[5] = (10 * 9);
				}
			}
							
					Menu4_4_2 = new Array("Australian Pacific Touring","javascript:loadAncillaryCategory('escortedVacations', 'australianPacificTouring', 'vacationPackage' );","",0,20,170);		
				
			if(Menu4_4_2[3] > 0) {
				if(Menu4_4_2_1) {
					Menu4_4_2_1[5] = (10 * 9);
				}
			}
							
					Menu4_4_3 = new Array("Trafalgar Tours","javascript:loadAncillaryCategory('escortedVacations', 'trafalgarTours', 'vacationPackage' );","",0,20,170);		
				
			if(Menu4_4_3[3] > 0) {
				if(Menu4_4_3_1) {
					Menu4_4_3_1[5] = (10 * 9);
				}
			}
		
		if(Menu4_4[3] > 0) {
			if(Menu4_4_1) {
				Menu4_4_1[5] = (26 * 9);
			}
		}
	
				Menu4_5 = new Array("Europe","javascript:loadDestination('europe');","",7,20,130);
			
					Menu4_5_1 = new Array("England","javascript:loadRegion('europe', 'england');","",1,20,170);		
				
				Menu4_5_1_1 = new Array("London","javascript:loadArea('europe', 'england', 'london');","",0,20,130);		
			
			if(Menu4_5_1[3] > 0) {
				if(Menu4_5_1_1) {
					Menu4_5_1_1[5] = (10 * 9);
				}
			}
		
					Menu4_5_2 = new Array("France","javascript:loadRegion('europe', 'france');","",1,20,170);		
				
				Menu4_5_2_1 = new Array("Paris","javascript:loadArea('europe', 'france', 'paris');","",0,20,130);		
			
			if(Menu4_5_2[3] > 0) {
				if(Menu4_5_2_1) {
					Menu4_5_2_1[5] = (10 * 9);
				}
			}
		
					Menu4_5_3 = new Array("Greece","javascript:loadRegion('europe', 'greece');","",3,20,170);		
				
				Menu4_5_3_1 = new Array("Athens","javascript:loadArea('europe', 'greece', 'athens');","",0,20,130);		
			
				Menu4_5_3_2 = new Array("Mykonos","javascript:loadArea('europe', 'greece', 'mykonos');","",0,20,130);		
			
				Menu4_5_3_3 = new Array("Santorini","javascript:loadArea('europe', 'greece', 'santorini');","",0,20,130);		
			
			if(Menu4_5_3[3] > 0) {
				if(Menu4_5_3_1) {
					Menu4_5_3_1[5] = (10 * 9);
				}
			}
		
					Menu4_5_4 = new Array("Ireland","javascript:loadRegion('europe', 'ireland');","",1,20,170);		
				
				Menu4_5_4_1 = new Array("Dublin","javascript:loadArea('europe', 'ireland', 'dublin');","",0,20,130);		
			
			if(Menu4_5_4[3] > 0) {
				if(Menu4_5_4_1) {
					Menu4_5_4_1[5] = (10 * 9);
				}
			}
		
					Menu4_5_5 = new Array("Italy","javascript:loadRegion('europe', 'italy');","",3,20,170);		
				
				Menu4_5_5_1 = new Array("Florence","javascript:loadArea('europe', 'italy', 'florence');","",0,20,130);		
			
				Menu4_5_5_2 = new Array("Rome","javascript:loadArea('europe', 'italy', 'rome');","",0,20,130);		
			
				Menu4_5_5_3 = new Array("Venice","javascript:loadArea('europe', 'italy', 'venice');","",0,20,130);		
			
			if(Menu4_5_5[3] > 0) {
				if(Menu4_5_5_1) {
					Menu4_5_5_1[5] = (10 * 9);
				}
			}
		
					Menu4_5_6 = new Array("Scotland","javascript:loadRegion('europe', 'scotland');","",1,20,170);		
				
				Menu4_5_6_1 = new Array("Edinburgh","javascript:loadArea('europe', 'scotland', 'edinburgh');","",0,20,130);		
			
			if(Menu4_5_6[3] > 0) {
				if(Menu4_5_6_1) {
					Menu4_5_6_1[5] = (10 * 9);
				}
			}
		
					Menu4_5_7 = new Array("Spain","javascript:loadRegion('europe', 'spain');","",2,20,170);		
				
				Menu4_5_7_1 = new Array("Barcelona","javascript:loadArea('europe', 'spain', 'barcelona');","",0,20,130);		
			
				Menu4_5_7_2 = new Array("Madrid","javascript:loadArea('europe', 'spain', 'madrid');","",0,20,130);		
			
			if(Menu4_5_7[3] > 0) {
				if(Menu4_5_7_1) {
					Menu4_5_7_1[5] = (10 * 9);
				}
			}
		
		if(Menu4_5[3] > 0) {
			if(Menu4_5_1) {
				Menu4_5_1[5] = (10 * 9);
			}
		}
	
				Menu4_6 = new Array("Fiji","javascript:loadDestination('fiji');","",0,20,130);
			
		if(Menu4_6[3] > 0) {
			if(Menu4_6_1) {
				Menu4_6_1[5] = (10 * 9);
			}
		}
	
				Menu4_7 = new Array("Florida","javascript:loadDestination('florida');","",1,20,130);
			
					Menu4_7_1 = new Array("Orlando","javascript:loadRegion('florida', 'orlando');","",0,20,170);		
				
			if(Menu4_7_1[3] > 0) {
				if(Menu4_7_1_1) {
					Menu4_7_1_1[5] = (10 * 9);
				}
			}
		
		if(Menu4_7[3] > 0) {
			if(Menu4_7_1) {
				Menu4_7_1[5] = (10 * 9);
			}
		}
	
				Menu4_8 = new Array("Hawaii","javascript:loadDestination('hawaii');","",4,20,130);
			
					Menu4_8_1 = new Array("Big Island","javascript:loadRegion('hawaii', 'bigIsland');","",2,20,170);		
				
				Menu4_8_1_1 = new Array("Kohala Coast","javascript:loadArea('hawaii', 'bigIsland', 'kohala');","",0,20,130);		
			
				Menu4_8_1_2 = new Array("Kona Coast","javascript:loadArea('hawaii', 'bigIsland', 'kailuaKona');","",0,20,130);		
			
			if(Menu4_8_1[3] > 0) {
				if(Menu4_8_1_1) {
					Menu4_8_1_1[5] = (12 * 9);
				}
			}
		
					Menu4_8_2 = new Array("Kauai","javascript:loadRegion('hawaii', 'kauai');","",2,20,170);		
				
				Menu4_8_2_1 = new Array("Poipu","javascript:loadArea('hawaii', 'kauai', 'poipu');","",0,20,130);		
			
				Menu4_8_2_2 = new Array("Wailua Kapaa","javascript:loadArea('hawaii', 'kauai', 'wailuaKapaa');","",0,20,130);		
			
			if(Menu4_8_2[3] > 0) {
				if(Menu4_8_2_1) {
					Menu4_8_2_1[5] = (12 * 9);
				}
			}
		
					Menu4_8_3 = new Array("Maui","javascript:loadRegion('hawaii', 'maui');","",2,20,170);		
				
				Menu4_8_3_1 = new Array("Kaanapali","javascript:loadArea('hawaii', 'maui', 'kaanapali');","",0,20,130);		
			
				Menu4_8_3_2 = new Array("Wailea","javascript:loadArea('hawaii', 'maui', 'wailea');","",0,20,130);		
			
			if(Menu4_8_3[3] > 0) {
				if(Menu4_8_3_1) {
					Menu4_8_3_1[5] = (10 * 9);
				}
			}
		
					Menu4_8_4 = new Array("Oahu","javascript:loadRegion('hawaii', 'oahu');","",1,20,170);		
				
				Menu4_8_4_1 = new Array("Waikiki","javascript:loadArea('hawaii', 'oahu', 'waikiki');","",0,20,130);		
			
			if(Menu4_8_4[3] > 0) {
				if(Menu4_8_4_1) {
					Menu4_8_4_1[5] = (10 * 9);
				}
			}
		
		if(Menu4_8[3] > 0) {
			if(Menu4_8_1) {
				Menu4_8_1[5] = (10 * 9);
			}
		}
	
				Menu4_9 = new Array("Las Vegas & Desert","javascript:loadAncillary('lasVegasAndDesert', 'VacationPackage');","",0,20,130);
			
		if(Menu4_9[3] > 0) {
			if(Menu4_9_1) {
				Menu4_9_1[5] = (10 * 9);
			}
		}
	
				Menu4_10 = new Array("Mexico","javascript:loadDestination('mexico');","",7,20,130);
			
					Menu4_10_1 = new Array("Cancun","javascript:loadRegion('mexico', 'cancun');","",0,20,170);		
				
			if(Menu4_10_1[3] > 0) {
				if(Menu4_10_1_1) {
					Menu4_10_1_1[5] = (10 * 9);
				}
			}
		
					Menu4_10_2 = new Array("Cozumel","javascript:loadRegion('mexico', 'cozumel');","",0,20,170);		
				
			if(Menu4_10_2[3] > 0) {
				if(Menu4_10_2_1) {
					Menu4_10_2_1[5] = (10 * 9);
				}
			}
		
					Menu4_10_3 = new Array("Ixtapa/Zihuatanejo","javascript:loadRegion('mexico', 'ixtapaZihuatanejo');","",0,20,170);		
				
			if(Menu4_10_3[3] > 0) {
				if(Menu4_10_3_1) {
					Menu4_10_3_1[5] = (10 * 9);
				}
			}
		
					Menu4_10_4 = new Array("Los Cabos","javascript:loadRegion('mexico', 'losCabos');","",0,20,170);		
				
			if(Menu4_10_4[3] > 0) {
				if(Menu4_10_4_1) {
					Menu4_10_4_1[5] = (10 * 9);
				}
			}
		
					Menu4_10_5 = new Array("Mazatlan","javascript:loadRegion('mexico', 'mazatlan');","",0,20,170);		
				
			if(Menu4_10_5[3] > 0) {
				if(Menu4_10_5_1) {
					Menu4_10_5_1[5] = (10 * 9);
				}
			}
		
					Menu4_10_6 = new Array("Puerto Vallarta/Riviera Nayarit","javascript:loadRegion('mexico', 'puertoVallartaAndRivieraNayarit');","",2,20,170);		
				
				Menu4_10_6_1 = new Array("Puerto Vallarta","javascript:loadArea('mexico', 'puertoVallartaAndRivieraNayarit', 'puertoVallarta');","",0,20,130);		
			
				Menu4_10_6_2 = new Array("Riviera Nayarit","javascript:loadArea('mexico', 'puertoVallartaAndRivieraNayarit', 'rivieraNayarit');","",0,20,130);		
			
			if(Menu4_10_6[3] > 0) {
				if(Menu4_10_6_1) {
					Menu4_10_6_1[5] = (15 * 9);
				}
			}
		
					Menu4_10_7 = new Array("Riviera Maya","javascript:loadRegion('mexico', 'rivieraMaya');","",0,20,170);		
				
			if(Menu4_10_7[3] > 0) {
				if(Menu4_10_7_1) {
					Menu4_10_7_1[5] = (10 * 9);
				}
			}
		
		if(Menu4_10[3] > 0) {
			if(Menu4_10_1) {
				Menu4_10_1[5] = (31 * 9);
			}
		}
	
				Menu4_11 = new Array("New Zealand","javascript:loadDestination('newZealand');","",2,20,130);
			
					Menu4_11_1 = new Array("North Island","javascript:loadRegion('newZealand', 'northIsland');","",5,20,170);		
				
				Menu4_11_1_1 = new Array("Auckland","javascript:loadArea('newZealand', 'northIsland', 'auckland');","",0,20,130);		
			
				Menu4_11_1_2 = new Array("Kerikeri (Bay of Islands)","javascript:loadArea('newZealand', 'northIsland', 'bayOfIslands');","",0,20,130);		
			
				Menu4_11_1_3 = new Array("Napier","javascript:loadArea('newZealand', 'northIsland', 'napier');","",0,20,130);		
			
				Menu4_11_1_4 = new Array("Rotorua","javascript:loadArea('newZealand', 'northIsland', 'rotorua');","",0,20,130);		
			
				Menu4_11_1_5 = new Array("Wellington","javascript:loadArea('newZealand', 'northIsland', 'wellington');","",0,20,130);		
			
			if(Menu4_11_1[3] > 0) {
				if(Menu4_11_1_1) {
					Menu4_11_1_1[5] = (25 * 9);
				}
			}
		
					Menu4_11_2 = new Array("South Island","javascript:loadRegion('newZealand', 'southIsland');","",6,20,170);		
				
				Menu4_11_2_1 = new Array("Blenheim","javascript:loadArea('newZealand', 'southIsland', 'blenheim');","",0,20,130);		
			
				Menu4_11_2_2 = new Array("Christchurch","javascript:loadArea('newZealand', 'southIsland', 'christchurch');","",0,20,130);		
			
				Menu4_11_2_3 = new Array("Dunedin","javascript:loadArea('newZealand', 'southIsland', 'dunedin');","",0,20,130);		
			
				Menu4_11_2_4 = new Array("Franz Josef","javascript:loadArea('newZealand', 'southIsland', 'franzJosef');","",0,20,130);		
			
				Menu4_11_2_5 = new Array("Nelson","javascript:loadArea('newZealand', 'southIsland', 'nelson');","",0,20,130);		
			
				Menu4_11_2_6 = new Array("Queenstown","javascript:loadArea('newZealand', 'southIsland', 'queenstown');","",0,20,130);		
			
			if(Menu4_11_2[3] > 0) {
				if(Menu4_11_2_1) {
					Menu4_11_2_1[5] = (12 * 9);
				}
			}
		
		if(Menu4_11[3] > 0) {
			if(Menu4_11_1) {
				Menu4_11_1[5] = (12 * 9);
			}
		}
	
				Menu4_12 = new Array("Tahiti","javascript:loadDestination('tahitianIslands');","",5,20,130);
			
					Menu4_12_1 = new Array("Bora Bora","javascript:loadRegion('tahitianIslands', 'boraBora');","",0,20,170);		
				
			if(Menu4_12_1[3] > 0) {
				if(Menu4_12_1_1) {
					Menu4_12_1_1[5] = (10 * 9);
				}
			}
		
					Menu4_12_2 = new Array("Moorea","javascript:loadRegion('tahitianIslands', 'moorea');","",0,20,170);		
				
			if(Menu4_12_2[3] > 0) {
				if(Menu4_12_2_1) {
					Menu4_12_2_1[5] = (10 * 9);
				}
			}
		
					Menu4_12_3 = new Array("Taha'a, Huahine","javascript:loadRegion('tahitianIslands', 'tahaaHuahine');","",0,20,170);		
				
			if(Menu4_12_3[3] > 0) {
				if(Menu4_12_3_1) {
					Menu4_12_3_1[5] = (10 * 9);
				}
			}
		
					Menu4_12_4 = new Array("Tahiti","javascript:loadRegion('tahitianIslands', 'tahiti');","",0,20,170);		
				
			if(Menu4_12_4[3] > 0) {
				if(Menu4_12_4_1) {
					Menu4_12_4_1[5] = (10 * 9);
				}
			}
		
					Menu4_12_5 = new Array("Tikehau, Manihi","javascript:loadRegion('tahitianIslands', 'tikehauRangiroaManihi');","",0,20,170);		
				
			if(Menu4_12_5[3] > 0) {
				if(Menu4_12_5_1) {
					Menu4_12_5_1[5] = (10 * 9);
				}
			}
		
		if(Menu4_12[3] > 0) {
			if(Menu4_12_1) {
				Menu4_12_1[5] = (15 * 9);
			}
		}
	

	Menu4_13 = new Array("Theme Parks","javascript:loadAncillaryHome()","",2,20,145);
		Menu4_13_1=new Array("Houseboat Vacations","javascript:loadAncillary('houseboatVacations', 'VacationPackage')","",0,20,170);
		Menu4_13_2=new Array("Theme Park Vacations","javascript:loadAncillary('themeParkVacations', 'VacationPackage')","",2);
			Menu4_13_2_1=new Array("Disneyland® Resort","javascript:loadAncillaryCategory('disney', 'disneylandResort')","",0,20,150);
			Menu4_13_2_2=new Array("Orlando","javascript:loadAncillaryCategory('themeParkVacations', 'orlando')","",0);
	
	//The menu item "Theme Parks & Vacations" has width of 23 characters. 
	//So, if destinationMenuWidth is less than 23, then set its value to 23

	
	
	if(Menu4[3] > 0) {	
		if(Menu4_1) {
			Menu4_1[5] = (23 * 9);
		}
	}
    
    Menu5=new Array("| Rental Cars","javascript:loadAncillary('rentalCars')","",4,22,99);
    	Menu5_1=new Array("Alamo","javascript:loadAncillaryCategory('rentalCars', 'alamo')","",0,20,145);
        Menu5_2=new Array("Avis","javascript:loadAncillaryCategory('rentalCars', 'avis')","",0);
		Menu5_3=new Array("Budget","javascript:loadAncillaryCategory('rentalCars', 'budget')","",0);
		Menu5_4=new Array("Enterprise","javascript:loadAncillaryCategory('rentalCars', 'enterprise')","",0);
	
	Menu6=new Array("| Theme Parks & Specialty","javascript:loadAncillaryHome()","",4,22,185);
		Menu6_1=new Array("Disney","javascript:loadAncillary('disney')","",4,20,205);
			Menu6_1_1=new Array("Adventures by Disney","javascript:loadAncillaryCategory('disney', 'adventuresByDisney')","",0,20,175);
			Menu6_1_2=new Array("Disney Cruise Line®","javascript:loadCruiseLine('disneyCruiseLine')","",0);
			Menu6_1_3=new Array("Disneyland® Resort","javascript:loadAncillaryCategory('disney', 'disneylandResort')","",0);
			Menu6_1_4=new Array("Orlando","javascript:loadAncillaryCategory('themeParkVacations', 'orlando')","",0);
		
		Menu6_2=new Array("Escorted Vacations","javascript:loadAncillary('escortedVacations')","",3);
			Menu6_2_1=new Array("Adventures by Disney","javascript:loadAncillaryCategory('disney', 'adventuresByDisney')","",0,20,175);
			Menu6_2_2=new Array("Australian Pacific Touring","javascript:loadAncillaryCategory('escortedVacations', 'australianPacificTouring')","",0);
			Menu6_2_3=new Array("Trafalgar Tours","javascript:loadAncillaryCategory('escortedVacations', 'trafalgarTours')","",0);
		
		Menu6_3=new Array("Houseboat Vacations","javascript:loadAncillary('houseboatVacations')","",0);
		
		Menu6_4=new Array("Pacific Northwest Vacations","javascript:loadCruiseLine('pacificNorthwestVacations')","",0);
		
	Menu7=new Array("| Hotels","javascript:loadAncillary('hotels')","",2,22,65);
		Menu7_1=new Array("Best Western® Hotels","javascript:loadAncillary('bestWesternHotels')","",0,20,180);
		Menu7_2=new Array("Hyatt Hotels & Resorts®","javascript:loadAncillary('hyattHotelsAndResorts')","",0);
	
	Menu8=new Array("| In the Warehouse","javascript:loadAncillary('inTheWarehouse')","",0,22,130);
		
   function createMenu() {
   	
   }
