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, dependentDateFieldName ) {
	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 );
		
		//if selected field date before dependent field date, then assigning the dependent date to start date which helps to display start month of the calendar. 
		//E.g. : Departure date( dependent Date ) and Return Date ( selected date ).
		//User enters departure date after return date, now user clicks on the return date picker and calendar will display start month as departure date month.
		var dependentDateField = document.getElementById( dependentDateFieldName );
		if( !isNull( dependentDateField ) && !isEmpty( dependentDateField.value ) && ( dependentDateField.value != 'mm/dd/yyyy' ) ) {
			var dependentDate = new Date( dependentDateField.value );
			if( dependentDate > selectedDate ) {
				startDate = new Date( dependentDate );
			}
		}
	} else if( !( isNull( specialDates ) ) ) { //specialDates is an associative array, which contains date as a key as well as value. 
		//specialDates used for highlighting the days. 
		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 = null;
		document.onmouseover = null;
	}
	calendar = new Calendar( startDate, selectedDate, disabledDateRanges, fieldName, specialDates, activatePastDatesNavigation );
	var calendarPopup = createCalendarPopup();
	if( isIE7Under() ) {
		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, -1, -1, 300, true, false, "box-shadow" );		
		calendarPopup.onmouseover = function( event ) { setDragEvent( divId, event, 15 ); };		
	}
	return calendarPopup;
}

function setCalendarDefaultCoordinates( fieldName, divId ) {
	var referenceElement = document.getElementById( fieldName );
	var referenceElementHeight = referenceElement.offsetHeight;
	var referenceElementPos = getPosRelativeToContainer(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 = toPixels(referenceElementTop);
	calendarPopup.style.left = toPixels(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.className = 'calendarBorder';
	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 = 'calendarBgc00';
	var spacerImageLeftBorder = document.createElement( "IMG" );
	spacerImageLeftBorder.src = _webLoc + '/shared/images/core/spacer.gif';
	spacerImageLeftBorder.alt = "";
	spacerImageLeftBorder.border = '0';
	spacerImageLeftBorder.width = '10';
	spacerImageLeftBorder.height = '10';
	column1Row1.appendChild( spacerImageLeftBorder );

	var column2Row1 = document.createElement( "TD" );
	column2Row1.colSpan = '2';
	column2Row1.className = '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 ) );
	}
	

	
	row1.appendChild( column1Row1 );
	row1.appendChild( column2Row1 );	

	//Row 2
	var row2 = document.createElement( "TR" );

	var column1Row2 = document.createElement( "TD" );
	column1Row2.className = '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 );
	


	row2.appendChild( column1Row2 );
	row2.appendChild( column2Row2 );
	row2.appendChild( column3Row2 );
	
	// Row 3	
	var row3 = document.createElement( "TR" );
	var column1Row3 = document.createElement( "TD" );
	column1Row3.className = '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 );
	

	calendarTBody.appendChild( row1 );
	calendarTBody.appendChild( row2 );
	calendarTBody.appendChild( row3 );

	calendarMainTable.appendChild( calendarTBody );
	
	document.getElementById( divId ).innerHTML = "";
	document.getElementById( divId ).appendChild( calendarMainTable );
	document.getElementById( divId ).style.display = "block";
	if( isIE7Under() ) {
		document.getElementById( divId ).appendChild(createHiddenIFrame());
	}
}

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 ) ) {
		if(isAndroid()) {
			column1Row1.ontouchstart = function() { moveCalendarByMonth( -1 ); };
		}
		else {
			previousImage.onclick = function() { moveCalendarByMonth( -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 ) ) {
		if(isAndroid()) {
			column3Row1.ontouchstart = function() { moveCalendarByMonth( 1 ); };
		}
		else {
			nextImage.onclick = function() { moveCalendarByMonth( 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.activatePastDatesNavigation );
	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(isIE7Under()) {
			showElementsHiddenByCalendar( divId );
		}
		removeElement( divId );
		document.onmousedown = null;
		document.onmouseover = null;
	}
}
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, activatePastDatesNavigation ) {
	var presentDate = getCurrentDate();
	var isDisabled = true;
	if( !( isEmpty( disabledDateRanges ) ) ) {
		if( !activatePastDatesNavigation && ( 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( ( !( activatePastDatesNavigation ) && ( compareDates( date, presentDate ) >= 0 ) ) || ( ( 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 = getPosRelativeToContainer(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 = getPosRelativeToContainer(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, disableSearch ) {
	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" : ( !( disableSearch )? "calendarTd calendarHand calendarTdAvl" : "calendarTd calendarTdAvl" ),
						  "N" : "calendarTd calendarTdSold"
						}
	this.numberOfNights = numberOfNights;
	this.productUid = productUid;
	this.disabledDateRanges = disabledDateRanges;
	this.specialDates = specialDates;
	this.dataContainer = 'dataContent';
	this.fieldName = "calendarCheckinDate";
	this.disableSearch  = disableSearch ;
}

function DayAllotment( date, status ) {
	this.date = date;
	this.status = status;
}

function createAllotmentCalendar( anchorName, title, subTitle, startDate, cutoffMonths, dayAllotments, numberOfNights, productUid, disabledDateRanges, specialDates, disableSearch  ) {
	var divId = "allotmentCalendarDivPopup";
	allotmentCalendarDivId = divId;
	
	var dayAllotments = getDayAllotmentHashMap( dayAllotments );
	allotmentCalendar = new AllotmentCalendar( anchorName, title, subTitle, startDate, cutoffMonths, dayAllotments, numberOfNights, productUid, disabledDateRanges, specialDates, disableSearch );
	
	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, -1, 250, true, false, "" );
		calendarPopup.onmouseover = function( event ) { setDragEvent( divId, event, 15 ) };
		calendarPopup.style.height = toPixels(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.className = 'calendarBorder box-shadow';
	calendarMainTable.border = "0";
	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 = 'calendarBgc00'
	var spacerImageLeftBorder = document.createElement( "IMG" );
	spacerImageLeftBorder.src = _webLoc + '/shared/images/core/spacer.gif';
	spacerImageLeftBorder.alt = "";
	spacerImageLeftBorder.border = '0';
	spacerImageLeftBorder.width = '10';
	spacerImageLeftBorder.height = '10';
	column1Row1.appendChild( spacerImageLeftBorder );

	var column2Row1 = document.createElement( "TD" );
	column2Row1.colSpan = '2';
	column2Row1.className = '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 );

	row1.appendChild( column1Row1 );
	row1.appendChild( column2Row1 );	

	//Row 2
	var row2 = document.createElement( "TR" );

	var column1Row2 = document.createElement( "TD" );
	column1Row2.className = '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 );
	
	row2.appendChild( column1Row2 );
	row2.appendChild( column2Row2 );
	row2.appendChild( column3Row2 );
	
	calendarTBody.appendChild( row1 );
	calendarTBody.appendChild( row2 );
	
	if( !allotmentCalendar.disableSearch ) {
		//Row 3
		var row3 = document.createElement( "TR" );
		
		var column1Row3 = document.createElement( "TD" );
		column1Row3.className = '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.onkeypress = function( event ) { return checkDate( event ); }
		inputTextForCheckinDate.onblur = function( event ) { showPlaceHolder( inputTextForCheckinDate, 'mm/dd/yyyy' ); }
		inputTextForCheckinDate.onchange = function( event ) { updateCheckoutDate( inputTextForCheckinDate.id, "calendarNoOfNights", "calendarCheckoutDate" ); }
		showPlaceHolder( inputTextForCheckinDate, 'mm/dd/yyyy' );
		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 );
			
		row3.appendChild( column1Row3 );
		row3.appendChild( column2Row3 );
		row3.appendChild( column3Row3 );
		
		//Row 5
		var row4 = document.createElement( "TR" );
		
		//Two colspan.	
		var column1Row4 = document.createElement( "TD" );
		column1Row4.className = '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.onkeypress = function( event ) { return checkDate( event ); } 
		inputTextForCheckoutDate.onblur = function( event ) {  showPlaceHolder( inputTextForCheckoutDate, 'mm/dd/yyyy' ); }
		inputTextForCheckoutDate.onchange = function( event ) { updateNights( inputTextForCheckinDate.id, "calendarNoOfNights", "calendarCheckoutDate" ); };
		showPlaceHolder( inputTextForCheckoutDate, 'mm/dd/yyyy' );
		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 ) { 	clearPlaceHolder( inputTextForCheckinDate );
															  	selectTextField( inputTextForCheckinDate, borderColor ); 
															  	changeBorderColor( inputTextForCheckoutDate, "1px solid #7f9db9" ); 
															 }
		inputTextForCheckoutDate.onfocus = function( event ) { 	clearPlaceHolder( inputTextForCheckoutDate );
																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 );
		
		row4.appendChild( column1Row4 );
		row4.appendChild( column2Row4 );
		row4.appendChild( column3Row4 );
	
		calendarTBody.appendChild( row3 );
		calendarTBody.appendChild( row4 );
	} else {
		var row3 = document.createElement( "TR" );
		
		var column1Row3 = document.createElement( "TD" );
		column1Row3.className = '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 = "calendarTac calendarFs11 calendarBgc00 calendarBold";
		column2Row3.colSpan = '2';
		var link = document.createElement('A');
		link.href = "javascript:;";
		link.onclick = function() { closeCalendar( allotmentCalendarDivId ); disableElement( allotmentCalendar.dataContainer, false ); }	
		var closeText = document.createTextNode( "close" );	
		link.appendChild(closeText);
		column2Row3.appendChild( link );
			
		row3.appendChild( column1Row3 );
		row3.appendChild( column2Row3 );
		
		calendarTBody.appendChild( row3 );
	}
	
	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( isIE7Under() ) {
		document.getElementById( allotmentCalendarDivId ).appendChild(createHiddenIFrame());
	}
}

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 && !( allotmentCalendar.disableSearch ) ) {
			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;
}

/* 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 Browser ()
{   // 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.ie3Mac = (this.mac && agt.indexOf("MSIE")!=-1);
    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.ns = (agt.indexOf("netscape6/") != -1 || agt.indexOf("gecko") != -1);
    this.ns61 = agt.indexOf("gecko") != -1;
    
    this.firefox = (agt.indexOf("firefox") != -1);

    this.safari = (agt.indexOf("safari") != -1);

    this.chrome = (agt.indexOf("chrome") != -1);
    
    this.android = (agt.indexOf("android") != -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));
    this.iPhone = (agt.indexOf("iphone")!=-1);
    this.iPad = (agt.indexOf("ipad")!=-1);
}
var browser = new Browser();

/* End of code from Ultimate client-side Javascript client sniff, version 3.03 */


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;
}

/*
 * phoneNumberFieldOnKeyUp() method is used for any phone fields for on key up event with passing next field id for focus and number of digits allowed in the current field.
 *  
 */
function phoneNumberFieldOnKeyUp( event, currentFieldName, nextFieldName, maxAllowed ) {
	var currentPhoneField = document.getElementById(currentFieldName).value;
	if( ( currentPhoneField.length == maxAllowed ) && !isShiftTabOrDeleteKey(event)){
		var nextPhoneField = document.getElementById(nextFieldName);
		nextPhoneField.focus();
		nextPhoneField.select();
	}
}

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 browser.ie;
}

function isIE7Under() {
	return browser.ie7under;
}

function isFireFox() {
	return browser.firefox;
}

function isSafari() {
	return browser.safari;
}

function isOpera() {
	return browser.opera;
}

function isNetscape() {
	return browser.ns;
}

function isAndroid() {
	return browser.android;
}

function isIpad() {
	return browser.iPad;
}

/*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++ ) {
		var 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, cruiseSearch  ) {
	var futureDateMessage = "Date of birth cannot be future date";
	if ( paxType == 2 && ( !isNull(cruiseSearch) && cruiseSearch )) {
		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);
}

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;
}

function validateTextAreaLength(field, length) {
	if(field.value.length >length)
	{
		field.value = field.value.substring(0,length);
	}
	//return (field.value.length <= length);
}


var errorElements = new Array();

var _disabledFormElements = [];
var _hiddenElements = [];

var numberOfAdImages = 8;
var adImages = new Array(numberOfAdImages);
var isDragEventRegistered = false;

var mouseX;
var mouseY;
var _eventListener = null;
var isScrollWindowDown ;

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;
	this.callbackFunctionName="hideMessageBox";
	this.callbackFunctionParams=null;
}

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 $(element) {
	if(typeof element == "string") {
		element = document.getElementById(element);
	}
	return element;
}

function makeMultiAjaxCall(requestItems, showSplashScreen, splashScreenText, callbackFunction) {
	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 = "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.parseResponse = false;
			asynchronousRequest.callbackFunctionName = 'callbackMakeMultiAjaxCall';
			asynchronousRequest.callbackFunctionParams = new Array(asynchronousMultiRequestItems, callbackFunction);
			
			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, callbackFunction) {
	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);
		
		var callbackObject = new CallbackObject(response, asynchronousMultiRequestItem.callbackFunctionName, asynchronousMultiRequestItem.callbackFunctionParams, true);
		if(callbackObject.isPageContent()) {
			if(asynchronousMultiRequestItem.target && asynchronousMultiRequestItem.target != '') {
				_populateDiv(response, asynchronousMultiRequestItem.target, callbackObject);
			}
		}
		callbackObject.applyCallback();
		
					
		var postCallbackScript = asynchronousMultiRequestItem.postCallbackScript;
		if(postCallbackScript && (postCallbackScript != '')) {
			eval(postCallbackScript);
		}
	}
	if(callbackFunction) {
		callbackFunction();
	}
}

function showErrorMessage(message, fadingElementName, errorElementNames, originalBorders,callbackFunctionName, callbackFunctionParams) {
	var messageBoxRequest = new MessageBoxRequest();
	messageBoxRequest.message = message;
	messageBoxRequest.fadingElementName = fadingElementName;
	messageBoxRequest.errorElementNames = errorElementNames;
	messageBoxRequest.errorElementOriginalBorders = originalBorders;
	if(callbackFunctionName!=null)
	{
		messageBoxRequest.callbackFunctionName=callbackFunctionName;
	}
	messageBoxRequest.callbackFunctionParams = callbackFunctionParams;
	displayMessageBox(messageBoxRequest);
}

function showWarningMessage(message, fadingElementName,callbackFunctionName, callbackFunctionParams) {
	var messageBoxRequest = new MessageBoxRequest();
	messageBoxRequest.message = message;
	messageBoxRequest.messageType = messageBoxRequest.MESSAGE_TYPE_WARNING;
	messageBoxRequest.fadingElementName = fadingElementName;
	if(callbackFunctionName!=null)
	{
		messageBoxRequest.callbackFunctionName=callbackFunctionName;
	}
	messageBoxRequest.callbackFunctionParams = callbackFunctionParams;
	displayMessageBox(messageBoxRequest);
}

function showGeneralMessage(message, fadingElementName, callbackFunctionName, callbackFunctionParams) {
	var messageBoxRequest = new MessageBoxRequest();
	messageBoxRequest.message = message;
	messageBoxRequest.messageType = messageBoxRequest.MESSAGE_TYPE_MESSAGE;
	messageBoxRequest.fadingElementName = fadingElementName;
	if(callbackFunctionName!=null)
	{
		messageBoxRequest.callbackFunctionName=callbackFunctionName;
	}
	messageBoxRequest.callbackFunctionParams = callbackFunctionParams;
	displayMessageBox(messageBoxRequest);
}

function hasError(callbackObject) {
	if(callbackObject.message && callbackObject.messageType == 0) {
		return true;
	}
	return false;
}

function hasWarning(callbackObject) {
	if(callbackObject.message && callbackObject.messageType == 1) {
		return true;
	}
	return false;
}

function hasInfo(callbackObject) {
	if(callbackObject.message && ((callbackObject.messageType != 0 && callbackObject.messageType != 1) || !callbackObject.messageCode)) {
		return true;
	}
	return false;
}

function hasMessage(callbackObject) {
	if(hasError(callbackObject) || hasWarning(callbackObject) || hasInfo(callbackObject)){
		return true;
	}
	return false;
}

function showMessage(messageType, messageCode, message, fadingBlock, callbackFunctionName, callbackFunctionParams) {
	if(message) {
		if(messageCode) {
			if(messageType == 0) {
				showErrorMessage(message, fadingBlock, null, null, callbackFunctionName, callbackFunctionParams);
				return true;
			}else if(messageType == 1){
				showWarningMessage(message, fadingBlock, callbackFunctionName, callbackFunctionParams);
				return true;
			}else {
				showGeneralMessage(message, fadingBlock,callbackFunctionName, callbackFunctionParams);
				return true;
			}
		}
		else {
			showGeneralMessage(message, fadingBlock,callbackFunctionName, callbackFunctionParams);
			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, -1, 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 = toPixels(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);
			var callbackFunction = _getMethod(messageBoxRequest.callbackFunctionName);
			var arguments = messageBoxRequest.callbackFunctionParams;
			if(arguments==null)
			{
				arguments= new Array(messageBoxRequest.uid, messageBoxRequest.fadingElementName);
			}
			if (callbackFunction != null)
			{
				var params = "";
				
				for (var i=0; i<arguments.length; i++)
				{
					if (i > 0) params += ", ";
					params += "arguments[" + i + "]";
				}
				//Invoke the callback function with parameters returned from the server
				eval("callbackFunction(" + params + ");");
			}
		};
		
		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(browser.ie7under) {
			var tagsToHide = new Array("select");
			hideElements(true, tagsToHide, '_messageBoxDiv');
		}
	}
}

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) {
			disableElement(fadingElementName, false);
		}
	} 

	//If the browser version is IE 6 or below, we have to show the hidden select boxes
	if(browser.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 getElementsByAttribute(rootNode, attributeName, attibuteValue, recurse, result) {
	if(!result) {
		result = [];
	}
	rootNode = $(rootNode);
	if(rootNode) {
		var childNodes = rootNode.childNodes;
		for(var i=0; i< childNodes.length; i++) {
			var childNode = childNodes[i];
			if((childNode[attributeName] == attibuteValue) ||
					(childNode.attributes && childNode.attributes[attributeName] && childNode.attributes[attributeName].value == attibuteValue)) {
				result.push(childNode);
			}
			
			if(recurse) {
				getElementsByAttribute(childNode, attributeName, attributeValue, recurse, result);
			}
		}
	}	
	return result;
}

function fireEvent(element, event, interval){
	var fireEventFunction = function() { 
	    if (document.createEventObject){
	        // dispatch for IE
	        var evt = document.createEventObject();
	        return element.fireEvent('on'+event,evt);
	    }
	    else{
	        // dispatch for firefox + others
	        var evt = document.createEvent("HTMLEvents");
	        evt.initEvent(event, true, true ); // event type,bubbling,cancelable
	        return !element.dispatchEvent(evt);
	    }
	};
	
	if(interval) {
		setTimeout(fireEventFunction, interval);
	}else {
		fireEventFunction();
	}
}

function SplashScreenRequest() {
	this.splashScreenText = 'Loading...Please Wait...';
	this.showStopButton = false;
	this.formActionAfterCancel = '';
}

function changeAdImage(image) {
	if(image) {
		var randomNumber = Math.ceil((numberOfAdImages - 1) * Math.random());
		image.src = adImages[randomNumber].src;
	}
}

function displaySearchingPopup(splashScreenRequest) {
	var searchingPopupDiv = document.getElementById('_searchingPopupDiv');
	if(!searchingPopupDiv) {
		searchingPopupDiv = createPopupDiv('_searchingPopupDiv', 0, 0, -1, -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 = toPixels(208);
		innerAdImage.style.height= toPixels(91);
		innerAdImage.alt = 'Banner';
		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 = toPixels(168);
		innerSearchingImage.style.height= toPixels(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);
	}
	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';
			
		changeAdImage(document.getElementById('_adImage'));

		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(browser.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";		

		//If the browser version is IE 6 or below, we have to show the hidden select boxes
		if(browser.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 - element.scrollLeft, y:element.offsetTop - element.scrollTop};
	element = element.offsetParent;
	while(element){
		pos.x+=element.offsetLeft - element.scrollLeft;
		pos.y+=element.offsetTop - element.scrollTop;
		element = element.offsetParent;
	}
	return pos;
}

function getPosRelativeToContainer(element, containerElement) {
	var pos1 = getAbsolutePos(element);
	containerElement = $(containerElement);
	if(!containerElement) {
		containerElement = document.getElementById("popupDivContainer");
	}
	
	if(containerElement) {
		var pos2 = getAbsolutePos(containerElement);
		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;
	}

	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(isIE7Under() && 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(browser.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(browser.ie7under) {
			var tagsToShow = new Array("select");
			hideElements(false, tagsToShow, elementName);
		}
	}
}

function getElementValue(element, defaultValue) {
	element = $(element);
	if(element) {
		return element.value;
	}
	return defaultValue;
}

function getCSSProperty(el, cssproperty){
	el = $(el);
	if (el.currentStyle) {
		return el.currentStyle[cssproperty];
	}
	else if (window.getComputedStyle){
		var elstyle=window.getComputedStyle(el, "")
		return elstyle.getPropertyValue(cssproperty)
	}
}

function positionBlockCentrally(elementName) {
	var element = document.getElementById(elementName);
	if(element) {
		
		var clientHeight = browser.iPad ? window.innerHeight : document.body.clientHeight;

		var scrollLeft = browser.iPad ? 0 : document.body.scrollLeft;
		var clientWidth =  browser.iPad ? window.innerWidth :  document.body.clientWidth;
	
		//alert("ch: " + clientHeight + " cw: " + clientWidth + " sl: " + scrollLeft + " st: " + document.body.scrollTop + "ww: " + window.innerWidth + " wh: " +  window.innerHeight);
		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 = (clientHeight - elementHeight) / 2;
		var renderingX = scrollLeft + (clientWidth - elementWidth) / 2;

		var popupDivContainer = document.getElementById("popupDivContainer");
		var popupDivContainerPos = getAbsolutePos(popupDivContainer);
		
		element.style.left = toPixels(renderingX - popupDivContainerPos.x);
		
		if(renderingY - popupDivContainerPos.y < 0) {
			element.style.top = toPixels(150);
		} else {
			element.style.top = toPixels(renderingY - popupDivContainerPos.y);
		}
	}	
}
function toPixels(value) {
	return value ? parseInt(value) + "px" : "0px"
}

function randomString(length) {
	var chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz";
	var result = '';
	for (var i=0; i<length; i++) {
		var rnum = Math.floor(Math.random() * chars.length);
		result += chars.substring(rnum,rnum+1);
	}
	return result;
}

function createPopupDiv(divName, left, top, width, height, zIndex, isVisible, isDraggable,  className, parentDiv, retainContent, popupContainer) {
	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";

	parentDiv = $(parentDiv);
	if(parentDiv) {
		popupDiv.parentDiv = parentDiv;
	}
	
	if(left >=0) {
		popupDiv.style.left = toPixels(left);
	}
	
	if(top>=0) {
		popupDiv.style.top = toPixels(top);
	}
	
	if(width>=0) {
		popupDiv.style.width = toPixels(width);
	}
	
	if(height>=0) {
		popupDiv.style.height = toPixels(height);
	} 		

	if(zIndex){
		popupDiv.style.zIndex = zIndex;
	}else {
		popupDiv.style.zIndex = "300";
	}	
	if(className || className=="") {
		popupDiv.className = className;
	}else {
		popupDiv.className="tal popupDivBig";
	}	
	
	if(!retainContent) {
		popupDiv.innerHTML = '';
	}
	if(isDraggable) {
		popupDiv.onmouseover = function( event ) { setDragEvent(divName, event ); };
	}

	popupDiv.isPopup = true;
	
	popupContainer = $(popupContainer);
	if(!popupContainer) {
		popupContainer = document.getElementById("popupDivContainer");
	}
	
	if( popupContainer && popupDiv.parentNode != popupContainer) {
		popupContainer.appendChild(popupDiv);
	}	
	return popupDiv;
}

function getPopupParent(popupDiv) {
	popupDiv = $(popupDiv);
	if(popupDiv) {
		return popupDiv.parentDiv;
	}
	return null;
}

function getContainerDiv(element){	
	element = $(element);	
	if(element) {
		var element = element.parentNode;
		while(element) {
			if(element.isPopup || element.id == "dataContent") {
				return element
			}
			element = element.parentNode;
		}
	}
	return null;
}

function getScrollableContainer(element) {
	element = $(element);	
	if(element) {
		var element = element.parentNode;
		while(element) {
			var isScrollable = getCSSProperty(element, "overflow") == "auto";
			if(isScrollable) {
				return element;
			}
			element = element.parentNode;
		}
	}
	return null;
}

function getPopupContainer(element) {
	element = $(element);	
	if(element) {
		var element = element.parentNode;
		while(element) {			
			if(element.id == "popupDivContainer" || hasClassName(element, "popup-container")) {
				return element;
			}
			element = element.parentNode;
		}
	}
	return null;
}

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(element, disable) {
	if(disable == null) {
		disable = true;
	}
	var popupContainer = getPopupContainer(element);
	
	var elementName = null;
	var baseElement = null;
	if(typeof element == 'string') {
		elementName = element;
		baseElement = document.getElementById(elementName);
	}else {
		elementName = element.id || randomString(5);
		element.id = elementName;
		baseElement = element;
	}
	
	var coveringDiv = document.getElementById('_' + elementName + '_coveringDiv');
	if(disable) { 
		if(!coveringDiv) {
			coveringDiv = createPopupDiv('_' + elementName + '_coveringDiv', 0, 0, 0, 0, -1, false, false, "", null, false, popupContainer);
		}
	}
		
	if(coveringDiv) {
		var baseElement = document.getElementById(elementName); 
		if(baseElement) {
			if(disable) {
				var baseElementHeight = baseElement.offsetHeight;
				try {
					var baseElementStyleHeight = parseInt(baseElement.style.height);
					if(isNaN(baseElementStyleHeight)) {
						baseElementStyleHeight = 0;
					}
					baseElementHeight = (baseElementHeight == 0) ? baseElementStyleHeight : baseElementHeight;
				}
				catch(e) {
				}
				
				var baseElementWidth = baseElement.offsetWidth;
				try {
					var baseElementStyleWidth = parseInt(baseElement.style.width);
					if(isNaN(baseElementStyleWidth)) {
						baseElementStyleWidth = 0;
					}
					baseElementWidth = (baseElementWidth == 0) ? baseElementStyleWidth : baseElementWidth;
				}
				catch(e) {
				}								

				coveringDiv.style.width = toPixels(baseElementWidth);
				coveringDiv.style.height = toPixels(baseElementHeight);
				var baseElementPos = getPosRelativeToContainer(baseElement, popupContainer);
				coveringDiv.style.background = "#000000";
				coveringDiv.style.left = toPixels(baseElementPos.x);
				coveringDiv.style.top = toPixels(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 = '';
		removeElement(fadingElement);
	}
}

function removeElement( element ) {
	var element = $( element );
	if( element ) {
		element.parentNode.removeChild(element);
	}
}

function elementSupportsAttribute(element, attribute) {
  var test = document.createElement(element);
  if (attribute in test) {
    return true;
  } else {
    return false;
  }
};

function isAjaxRequest() {
	return document.callbackObject != undefined;
}

function defer(func, executeImmediate) {   
	if(isAjaxRequest()) {
		  setTimeout(func, 10);
	  }else if(executeImmediate) {
		  func();
	  }else {
		  var oldonload = window.onload;   
		  if (typeof window.onload != 'function') {   
		     window.onload = func;   
		  } else {   
			  window.onload = function() {   
			  if (oldonload) {   
				oldonload();   
			  }   
			  func();   
		     };   
		  }
	  }   
} 

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;
		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;
		}
	}
}

function initializeDragEvent( divId, event ) {
	var element = document.getElementById( divId );
	var elementRelLoc = getPosRelativeToContainer(element);
	var elementAbsLoc = getAbsolutePos(element);
	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 = toPixels(xpos);
		document.getElementById( divId ).style.top = toPixels(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 = toPixels(( 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 = toPixels(-( 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( !browser.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 = getPosRelativeToContainer(element);
		var suggestionBox = document.getElementById("_suggestionBox");
		if(!suggestionBox) {
			suggestionBox = createPopupDiv('_suggestionBox', 0, 0, 0, -1, 300, false, false, "");		
		}
		if(suggestionBox) {
			suggestionBox.style.position = "absolute";
			suggestionBox.style.left = toPixels(elementPos.x);
			suggestionBox.style.top = toPixels(elementPos.y + element.offsetHeight);
			suggestionBox.style.width = toPixels(element.offsetWidth);			
			suggestionBox.style.visibility = "visible";
			suggestionBox.style.display = "block";
			suggestionBox.style.zIndex = "300";		
			suggestionBox.innerHTML = "";
			var isSuggestions = false;
			if(suggestions) {
				
				var selectString;
				if(isAndroid()) {					
					selectString = "<select id='_suggestionBoxSelect' size='10' " + 
														"onkeydown='_suggestionBoxOnKeyDown(event, \"" + elementName + "\")' " + 
														"onchange='_suggestionBoxOnChange(\"" + elementName + "\"); hideSuggestionBox();' >";
				}
				else if(isIpad()) {
					selectString = "<select id='_suggestionBoxSelect' " + 
																		"onKeyDown='_suggestionBoxOnKeyDown(event, \"" + elementName + "\")' " + 
														"onblur='_suggestionBoxOnChange(\"" + elementName + "\"); hideSuggestionBox();' onchange='_suggestionBoxOnChange(\"" + elementName + "\"); hideSuggestionBox();' >";
				}
				else {
					selectString = "<select id='_suggestionBoxSelect' size='10' " + 
													"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 showPlaceHolder(element, text) {
	element = $(element);
	element.placeholder = text;
	if(!elementSupportsAttribute("input", "placeholder")) {
		if(element.value == "") {
			element.value = text;	
		}
	}
}

function clearPlaceHolder(element) {
	element = $(element);
	if(!elementSupportsAttribute("input", "placeholder")) {
		if(element.value == element.placeholder) {
			element.value = "";	
		}
	}
}

window.nativeScrollTo = window.scrollTo;
window.scroll = window.scrollTo = function() {
	if( isScrollWindowDown != undefined && !isScrollWindowDown ){
		scrollWindowTop();
	}
};

function scrollWindowTop(divName) {
	var scrollableDiv = null;
	if(divName && (document.getElementById(divName))) {
		scrollableDiv = document.getElementById(divName);
	} else {
		scrollableDiv = document.getElementById("scrollablePageContent");		
	}
		
	if(scrollableDiv) {
		var currentStyle = (window.getComputedStyle ? window.getComputedStyle(scrollableDiv, "") : scrollableDiv.currentStyle)
		if(currentStyle.overflow == "auto") {
			scrollableDiv.scrollTop = 0;
		}
		else {
			window.nativeScrollTo(0,0);	
		}
	}else {
		window.nativeScrollTo(0,0);
	}
}

function scrollTopLink(topLink) {
	topLink = $(topLink);
	if(topLink) {
		var div = getScrollableContainer(topLink);
		if(div) {
			div.scrollTop = 0;
		} else {
			window.scroll(0,0);
		}
	}
}

function setFocus(element){
	if (element.value != ''){
		element.select();
	}
}

function getRadioWithValue(radioObj, value) {
	if(typeof radioObj == "string") {
		radioObj = document.getElementsByName(radioObj); 
	}
	if(radioObj) {
		var radioLength = radioObj.length;
		if(radioLength == undefined)
			if(radioObj.value == value)
				return radioObj;
			else
				return null;
		for(var i = 0; i < radioLength; i++) {
			if(radioObj[i].value == value) {
				return radioObj[i];
			}
		}
	}
	return null;
}

function getCheckedRadio(radioObj) {
	if(typeof radioObj == "string") {
		radioObj = document.getElementsByName(radioObj); 
	}
	if(radioObj) {
	var radioLength = radioObj.length;
	if(radioLength == undefined)
		if(radioObj.checked)
				return radioObj;
		else
				return null;
	for(var i = 0; i < radioLength; i++) {
		if(radioObj[i].checked) {
				return radioObj[i];
			}
		}
	}
	return null;
}
function getCheckedValue(radioObj, defaultValue) {
	var checkedRadio = getCheckedRadio(radioObj);
	if(checkedRadio) {
		return checkedRadio.value;
	}
	if(defaultValue != undefined) {
		return defaultValue;
	}
	return "";
}

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(isIE7Under()) {
		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 srcElement = document.getElementById(srcElementId);
	var popupContainer = getPopupContainer(srcElement);
	
	var toolTipPopupDiv = createPopupDiv("toolTipPopup", 0, 0, 0, -1, 300, false, false, "", null, false, popupContainer);
	toolTipPopupDiv.innerHTML = document.getElementById(toolTipId).innerHTML;
	if(event.type == "mouseout" || event.type == "blur") {
	      hideBlock("toolTipPopup");
	}else {
		showBlock("toolTipPopup");		
		var relPos = getPosRelativeToContainer(srcElement, popupContainer);
		toolTipPopupDiv.style.left = toPixels(relPos.x);
		toolTipPopupDiv.style.top = toPixels(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) {
	objElement = $(objElement);
	
	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 encodeHTML( decodedString ) {
	while( decodedString.indexOf( "'" ) != -1 ) {
		decodedString = decodedString.replace( "'", "##39##" );
	}
	while( decodedString.indexOf( '"' ) != -1 ) {
		decodedString = decodedString.replace( '"', "##34##" );
	}
	while( decodedString.indexOf( '?' ) != -1 ) {
		decodedString = decodedString.replace( '?', "##63##" );
	}
	while( decodedString.indexOf( '}' ) != -1 ) {
		decodedString = decodedString.replace( '}', "##125##" );
	}
	while( decodedString.indexOf( '{' ) != -1 ) {
		decodedString = decodedString.replace( '{', "##123##" );
	}
	while( decodedString.indexOf( '[' ) != -1 ) {
		decodedString = decodedString.replace( '[', "##91##" );
	}
	while( decodedString.indexOf( ']' ) != -1 ) {
		decodedString = decodedString.replace( ']', "##93##" );
	}
	while( decodedString.indexOf( '(' ) != -1 ) {
		decodedString = decodedString.replace( '(', "##40##" );
	}
	while( decodedString.indexOf( ')' ) != -1 ) {
		decodedString = decodedString.replace( ')', "##41##" );
	}
	while( decodedString.indexOf( '\n' ) != -1 ) {
		decodedString = decodedString.replace( '\n', "##38##" );
	}
	while( decodedString.indexOf( '\r' ) != -1 ) {
		decodedString = decodedString.replace( '\r', "##42##" );
	}
	while( decodedString.indexOf( '\\' ) != -1 ) {
		decodedString = decodedString.replace( '\\', "##92##" );
	}
	while( decodedString.indexOf( '$' ) != -1 ) {
		decodedString = decodedString.replace( '$', "##36##" );
	}
    decodedString = decodedString.replace( /</g, "##60##" );
    decodedString = decodedString.replace( />/g, "##62##" );
    decodedString = decodedString.replace( /!/g, "##33##" );    
    decodedString = decodedString.replace( /%/g, "##37##" );
    decodedString = decodedString.replace( /&/g, "##35##" );
    decodedString = decodedString.replace( /:/g, "##58##" );
    decodedString = decodedString.replace( /=/g, "##61##" );
    decodedString = decodedString.replace( /`/g, "##145##" );
	return decodedString;
}

function decodeHTML( encodedString ) {
	if (!encodedString){
		return "";
	}
	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 \&
    encodedString = encodedString.replace( /&#174;/g, '\u00AE' ); //converting reg code to ®
	return encodedString;
}

/*
 * set preservationType to 0 to discard previous selection
 * set preservationType to 1 to preserve only the first selection (for single select boxes)
 * set preservationType to 2 to preserve all selections (for multi select boxes)
 */
function replaceOptions ( list, optionsJSON, preservationType, useTextAsTitle ) {
	var options = optionsJSON.parseJSON ();
	list = $(list);
	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 optionText = decodeHTML ( trim( options [ i ].text ) );
			var newOpt = new Option ( optionText , options [ i ].value );
			if( !isEmpty( options [ i ].title ) ) {
				newOpt.title = decodeHTML ( options [ i ].title );
			} else if(useTextAsTitle) {
				newOpt.title = optionText;
			}
			if ( ( options [ i ].selected == true ) || ( preservationType > 0 && selectedOptions [ "_" + options [ i ].value ] ) ) {
				newOpt.selected = true;
			}
			if ( options [ i ].disabled == true ) {
				newOpt.disabled = true;
			}
			list.options [ i ] = newOpt;
		}
	}	
}

function loadImage(imageId, imageUrl) {
	var image = document.getElementById(imageId);
	
	if(image) {
		image.src = imageUrl;
	}
}

function preloadImage(image, imageSrc) {
	image.src = imageSrc;
}

function dynamicallyLoadImage(imageElementId, imageSrc, errorImg) {
	defer(function() { 
			var image = new Image();
			image.onload = function(){
							loadImage(imageElementId, imageSrc);
						   };
						   
						   
		    if (errorImg){				   
				image.onerror = function(){
								loadImage(imageElementId, errorImg);
								};
		    }				
			preloadImage(image, imageSrc);
	}, true);
}

function scrollToChild( childNodeName, parentNodeName ) {
	if( !isNull( document.getElementById( childNodeName ) ) ) {
		var childNode = document.getElementById( childNodeName );
		var offsetTop = getAbsolutePos( childNode ).y;
		if( !isNull( parentNodeName ) && !isNull( document.getElementById( parentNodeName ) ) ) {
			offsetTop -= getAbsolutePos( document.getElementById( parentNodeName ) ).y;
			document.getElementById( parentNodeName ).scrollTop = offsetTop;
		} else {
			window.scroll( 0, offsetTop );
		}
	}
}

function registerListener(element, event, listener) {
	element = $(element);
	if(element) {
		if(isIE()) {
			element.attachEvent("on" + event, listener);
		}else {		
			element.addEventListener(event, listener, true);
		}
	}
}

function unregisterListener(element, event, listener) {
	element = $(element);
	if(element) {
		if(isIE()) {
			element.detachEvent("on" + event, listener);
		}else {		
			element.removeEventListener(event, listener, true);
		}
	}
}

function trackEvent(category, action, label, value){
	try {
		pageTracker._trackEvent(category,action, label, value);
	}catch(e) {
		
	}
}

function trackPageView(trackingText){
	try {
		pageTracker._trackPageview(trackingText);
	}catch(e) {
		
	}
}

function setCruiseGlobalParams(destinationName, cruiseLineName, shipName, departureDate, cruisePackageId){
	_destinationName = destinationName;
	_cruiseLineName = cruiseLineName;
	_shipName = shipName;
	_departureDate = departureDate;
	_cruisePackageId = cruisePackageId;
}

function getSelectedOptionsAsQueryString(listName, paramName, startIndex, endIndex, selectAllIndex) {
	var queryString = "";
	var list = document.getElementById(listName);
	if(list) {
		var options = list.options;
		if(endIndex <=0) {
			endIndex = options.length;
		}		
		var selectAll = selectAllIndex>=0 && options[selectAllIndex].selected;
		for(var i=startIndex; i<endIndex; i++) {
			if(selectAll || options[i].selected) {
				if(queryString.length > 0) {
					queryString += "&";
				}
				queryString+= paramName +"=" + options[i].value;				
			}
		}
	}
	return queryString;
}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  +  ( sign ? '' : ')' );
}

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);
}var globalParameters =  {
	parameters: new Array(),
	
	addParameter: function(key, value) {
		this.parameters[key] = value;
	},
	
	getParameter: function(key) {
		return this.parameters[key];
	},
	
	setParameters: function(params) {
		this.parameters = params;
	},
	
	getParameters: function() {
		return this.parameters;
	},
	
	getQueryString: function() {
		var queryString = "";
   		if(this.parameters) {
	 		for (var key in this.parameters)
			{		
	 			if(this.parameters.hasOwnProperty(key)) {
	 				if(queryString != "") {
						queryString += "&";
					}
					queryString += key + "=" + this.parameters[key];
	 			}
			}
		}
   		
   		return queryString;
	}
};

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;
	
	/*set this variable to false, if the response needn't be parsed. Callback function will be invoked and it is the responsibility of the callback function to parse and interpret the response. Default value is true*/
	this.parseResponse = true;
	
	/*set this variable to true, if the request has to be cancelled by the client (browser). In this case, the response will not be interpreted. Default value is false*/
	this.requestCancelled = false;
}

function CallbackObject(responseText, callbackFunctionName, callbackFunctionAdditionalParams, parseResponse) {
	this.responseText = responseText;
	this.callbackFunctionParams = [];
	this.serverCallbackObject = null;
	this.pageContent = true;
	
	if(callbackFunctionName) {
		eval("this.callbackFunction = " + callbackFunctionName );
	}

	if(parseResponse) {
		if(responseText) {
			var callbackObjectPrefix = "<!-- callbackObject:";
			var currentPos = 0;
			var serverCallbackObjectLengthStartPos = responseText.indexOf(callbackObjectPrefix, currentPos) + callbackObjectPrefix.length;			
			while(serverCallbackObjectLengthStartPos >=callbackObjectPrefix.length) {
				currentPos = serverCallbackObjectLengthStartPos;				
				var serverCallbackObjectLengthEndPos = responseText.indexOf(":", serverCallbackObjectLengthStartPos);
				if(serverCallbackObjectLengthEndPos > 0) {					
					var serverCallbackObjectLength = parseInt(responseText.substring(serverCallbackObjectLengthStartPos, serverCallbackObjectLengthEndPos));		
					if(serverCallbackObjectLength > 0 ) {
						var serverCallbackObjectJson = responseText.substring(serverCallbackObjectLengthEndPos + 1, serverCallbackObjectLengthEndPos + serverCallbackObjectLength + 1);
						
						try {
							eval("this.serverCallbackObject = " + serverCallbackObjectJson);
						}catch(exception) {						
						}
						
						if(this.serverCallbackObject) {
							if(this.serverCallbackObject.activityMessages) {
								this.activityMessages = this.serverCallbackObject.activityMessages;
								if(this.activityMessages.length > 0) {
									this.messageCode = this.serverCallbackObject.activityMessages[0].code;
									this.messageType = this.serverCallbackObject.activityMessages[0].type;
									this.message = this.serverCallbackObject.activityMessages[0].message;
								}
							}
							
							if(this.serverCallbackObject.callbackFunctionParmeters) {
								this.callbackFunctionParams = this.serverCallbackObject.callbackFunctionParmeters;
							}
							this.pageContent = false;
							break;
						}
					}					
				}
				serverCallbackObjectLengthStartPos = responseText.indexOf(callbackObjectPrefix, currentPos);
			}
		}
	}
	else {
		this.pageContent = false;
	}
	
	if(callbackFunctionAdditionalParams && callbackFunctionAdditionalParams.length > 0) {
		for(var i =0; i< callbackFunctionAdditionalParams.length; i++) {
			this.callbackFunctionParams.push(callbackFunctionAdditionalParams[i]);
		}
	}	
}

CallbackObject.prototype.isPageContent = function() {
	return this.pageContent;
};

CallbackObject.prototype.applyCallback = function() {
	try {
		if(this.callbackFunction) {
			this.callbackFunction.apply(this, this.callbackFunctionParams);
		}
	}
	catch(exception) {
	}	
};

function submitWithoutReload(asynchronousRequest) {	
	_showSplashScreen(asynchronousRequest);

	if(asynchronousRequest.useAjax) {
       	var httpRequest = _getHttpRequest();
       	if (httpRequest) {
       		var queryString = _getQueryString(asynchronousRequest);
       		httpRequest.onreadystatechange = function() { _callbackAjax(httpRequest, asynchronousRequest); };
    	   	httpRequest.open('POST', asynchronousRequest.url, true);
    	   	httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8');
       		httpRequest.send(queryString);
       	}
	}
	else {
		if(asynchronousRequest.form) {
			_submitAsynchronousForm(asynchronousRequest);
		}
	}
		
	if(asynchronousRequest.splashScreenRequest != null) {
		if(!asynchronousRequest.splashScreenDisplayFunctionName) {
			disableFormElements(true);
		}
	}	
}

function openUrlWithoutReload(asynchronousRequest) {
	_showSplashScreen(asynchronousRequest);

   	var httpRequest = _getHttpRequest();
   	if (httpRequest) {
	   	httpRequest.onreadystatechange = function() { _showUrlContents(httpRequest, asynchronousRequest ); };
	   	httpRequest.open('POST', asynchronousRequest.url, true);
    	httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8');

    	var queryString = _getQueryString(asynchronousRequest);	   	
	   	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 _showSplashScreen(asynchronousRequest) {
	if(asynchronousRequest.splashScreenRequest != null) {
		if(asynchronousRequest.splashScreenDisplayFunctionName) {
			eval(asynchronousRequest.splashScreenDisplayFunctionName + "(asynchronousRequest.splashScreenRequest)");
		}
		else {
			displayWaitingDiv(asynchronousRequest.splashScreenRequest);
		}
	}
	else {
		_showWaitCursor();
	}	
}

function _hideSplashScreen(asynchronousRequest) {
	if(asynchronousRequest.splashScreenRequest != null) {			
		if(asynchronousRequest.splashScreenHideFunctionName) {
			eval(asynchronousRequest.splashScreenHideFunctionName + "(asynchronousRequest.splashScreenRequest)");
		}
		else {
			hideWaitingDiv();
			disableFormElements(false);
		}
		
		asynchronousRequest.splashScreenRequest = null;
	}
	_hideWaitCursor();	
}

function _getQueryString(asynchronousRequest) {
	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];
		}
	}
	     
	var globalQueryString = globalParameters.getQueryString();
	if(globalQueryString != "") {
		if(queryString && queryString != "") {
			queryString += "&";
		}
		
		queryString += globalQueryString;
	}
	
	return queryString;
}

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;
	}
	
	var parameters = globalParameters.getParameters();
	if(parameters.length > 0){
	for(var key in parameters) {	
		if(asynchronousRequest.form.elements[key]) {
			asynchronousRequest.form.elements[key] = parameters[key];
		}
		else {
			var hiddenField = document.createElement("input");
			hiddenField.type = "hidden";			
			hiddenField.id = key;
			hiddenField.value = parameters[key];
			
			var form = document.forms[asynchronousRequest.form.name];
			form.appendChild(hiddenField);
		}
	}
	 }	
	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 _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) {
   		var isRequestCancelled = asynchronousRequest.requestCancelled;
   		_hideSplashScreen(asynchronousRequest);
       	if (httpRequest.status == 200 && !isRequestCancelled) {
       		var callbackObject = new CallbackObject(httpRequest.responseText, asynchronousRequest.callbackFunctionName, asynchronousRequest.callbackFunctionParams, asynchronousRequest.parseResponse);
       		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) {
   		_hideSplashScreen(asynchronousRequest);
       	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, true);
			
			if(callbackObject.isPageContent()) {
				//Target Frame or Div is populated with the page content only if there were no callback errors
				if(asynchronousRequest.isTargetFrame) {
					_populateFrame(responseText, asynchronousRequest.target);
				}
				else if(asynchronousRequest.target && asynchronousRequest.target != '') {
					//Is Div				
					_populateDiv(responseText, asynchronousRequest.target, callbackObject);
				}
			}
			
			//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 _populateFrame(responseText, frameName) {
	var frameDocument = document.frames(frameName).document;
	frameDocument.open();
	frameDocument.write(responseText);
	frameDocument.close();	
}

function _populateDiv(responseText, divName, callbackObject) {
	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;
		
		document.callbackObject = callbackObject;
		try {
			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);
			}
			
			fireContentChanged(divElement);
		}finally {
			document.callbackObject = undefined;
		}
	}
}

function fireContentChanged(element) {
	element = $(element)
	while(element) {
		if(element.onContentChange && typeof element.onContentChange == "function") {
			element.onContentChange();
		}
		element = element.parentNode;
	}
}

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 newLineChar = String.fromCharCode(10);
	var carriageReturnChar = String.fromCharCode(13);
	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 ||
			string.charAt(iTemp) == newLineChar ||
			string.charAt(iTemp) == carriageReturnChar) {
		}
		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 newLineChar = String.fromCharCode(10);
	var carriageReturnChar = String.fromCharCode(13);
	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 ||
				string.charAt(iTemp) == newLineChar ||
				string.charAt(iTemp) == carriageReturnChar) {
		}
		else {
			strTemp = string.substring(iTemp, length);
			break;
		}
		iTemp = iTemp + 1;
	}
	
	return strTemp;
}
ErrorTypes = {
	ERROR_TYPE_ERROR	: 0,
	ERROR_TYPE_WARNING	: 1,
	ERROR_TYPE_GENERAL	: 2
};

ErrorCodes = {
	MEMBER_NOT_LOGGED_IN_ERROR: 4055	
};

PageHistoryConstants = {
	HISTORY_LANDING_URL										:0,
	HISTORY_HOME											:1,
	HISTORY_DESTINATION_HOME								:2,
	HISTORY_CRUISE_HOME										:3,
	HISTORY_ANCILLARY_HOME									:4,
	HISTORY_DESTINATION_LANDING								:5,
	HISTORY_REGION_LANDING									:6,
	HISTORY_AREA_LANDING									:7,
	HISTORY_CRUISE_DESTINATION_LANDING						:8,
	HISTORY_CRUISE_LINE_LANDING								:9,
	HISTORY_CRUISE_SHIP_LANDING								:10,
	HISTORY_ANCILLARY_LANDING								:11,
	HISTORY_ANCILLARY_CATEGORY_LANDING						:12,
	HISTORY_LAND_PACKAGE									:13,
	HISTORY_CRUISE_PACKAGE									:14,
	HISTORY_ANCILLARY_PACKAGE								:15,
	HISTORY_HOTEL											:16,
	HISTORY_RIGHT_CONTENT_HOTEL								:17,
	HISTORY_GENERAL_INFO									:18,
	HISTORY_SITE_MAP										:19,
	HISTORY_BLAST_OFFER_LANDING								:20,
	HISTORY_SWEEPSTAKES_LANDING								:21,
	HISTORY_RIGHT_CONTENT_THEME_PARK						:22,
	
	/* Search Pages */
	/* Codes 1001 through 2000 */
	HISTORY_SEARCH_RESULT_ALL_PACKAGES						:1001,
	HISTORY_SEARCH_RESULT_PACKAGE_FLIGHT_HOTEL				:1002,
	HISTORY_SEARCH_RESULT_PACKAGE_TRANSPORTATION			:1003,
	
	/* Cruise Search */
	HISTORY_CRUISE_SAILING_SEARCH_RESULTS					:1501,
	HISTORY_CRUISE_PASSENGER_INFO							:1502,
	HISTORY_CRUISE_CATEGORY_RESULTS							:1503,
	HISTORY_CRUISE_CABIN_RESULTS							:1504,
	
	/* Booking Pages */
	/* Codes 2001 through 3000 */
	HISTORY_BOOKING_RECAP									:2001,
	HISTORY_BOOKING_MEMBER_LOGIN							:2002,
	HISTORY_PASSENGER_DETAILS								:2003,
	HISTORY_SPECIAL_REQUESTS								:2004,
	HISTORY_SEAT_MAP_SELECTION								:2005,
	HISTORY_PAYMENT											:2006,
	HISTORY_PAYMENT_SUMMARY									:2007,
	HISTORY_ORDER_CONFIRMATION								:2008,
	HISTORY_ITINERARY_MEMBER_LOGIN							:2009,
	HISTORY_MEMBER_BOOKING_DETAILS							:2010,
	HISTORY_BOOKING_DETAILS									:2011,
	HISTORY_BALANCE_PAYMENT_SUMMARY							:2012,
	HISTORY_BALANCE_PAYMENT									:2013,
	
	/* Cruise Booking */
	HISTORY_CRUISE_PASSENGER_DETAILS						:2501,
	HISTORY_CRUISE_SPECIAL_REQUESTS							:2502,
	HISTORY_CRUISE_BOOKING_RECAP							:2503,
	HISTORY_CRUISE_BOOKING_CONFIRMATION						:2504,
	
	HISTORY_CRUISE_PRE_POST_SEARCH							:2601,
	HISTORY_CRUISE_PRE_POST_FLIGHT_RESULTS					:2602,
	HISTORY_CRUISE_PRE_HOTEL_RESULTS						:2603,
	HISTORY_CRUISE_POST_HOTEL_RESULTS						:2604,
	HISTORY_CRUISE_PRE_POST_TRANSFER_RESULTS				:2605,
	
	/* Car Module */
	/* Codes 3001 through 4000 */
	HISTORY_SEARCH_RESULT_CAR_AGENCY  						:3001,
	HISTORY_SEARCH_RESULT_CAR_AGENCY_MATRIX					:3002,
	HISTORY_SEARCH_RESULT_CAR_EQUIPMENT						:3003,
	HISTORY_CAR_BOOKING_RECAP								:3004,
	HISTORY_FINALIZE_CAR_BOOKING							:3005
};

CarTripSummaryDisplayConstants = {
	DISPLAY_CAR_TRIP_SUMMARY_UPTO_AGENCY_LOCATION		:0,
	DISPLAY_CAR_TRIP_SUMMARY_UPTO_CATEGORY				:1,
	DISPLAY_CAR_TRIP_SUMMARY_UPTO_OPTIONAL_REQUESTS 	:2
};window.pageHistory  = {
	currentHistoryCode: null,
	listener: null,
	storage: new Array(),
	hiddenIFrame: null,
	
	initialize: function() {
		//Create a hidden IFrame for IE
		if(browser.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(browser.ie && this.hiddenIFrame) {
				this.hiddenIFrame.src = _webLoc + "/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 = _webLoc + "/blank.html";
		iFrame.frameborder = "0";
		iFrame.style.position = "absolute";
		iFrame.style.width = toPixels(1);
		iFrame.style.height = toPixels(1);
		iFrame.style.left = toPixels(-100);
		iFrame.style.top = toPixels(-100);
		
		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;
			}
		}
	}
};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, dockContainer){
	this.source=document.all? document.all[el] : document.getElementById(el);
	this.source.height=this.source.offsetHeight;
	this.duration=duration;
	this.pagetop=0;
	if(typeof dockContainer == "string") {
		dockContainer = document.getElementById(dockContainer);
	}
	if(dockContainer) {
		this.dockContainer = dockContainer;
	}else {
		this.dockContainer= truebody();
	}
	this.docheight=dockContainer.clientHeight;
	this.elementoffset=this.getOffsetY();
	dockarray[dockarray.length]=this;
	
	var dockfunc = function() {
		dockornot(dockarray[dockarray.length-1])
	  };
	  
	dockContainer.onContentChange = dockfunc;
	registerListener(dockContainer, "scroll", dockfunc);
	//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(){
	return getPosRelativeToContainer(this.source, this.dockContainer).y;
}

function dockornot(obj){
	obj.pagetop=obj.dockContainer.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;
				}
			} 
		}
	};
}();

function SlideShow(imageId, pics, slideshowSpeed, transitionSpeed, transitionSteps) {	
	this.imageId = imageId ? imageId: "SlideShow";
	this.slideShowSpeed = slideshowSpeed ? slideshowSpeed: 4000;
	this.transitionSpeed = transitionSpeed ? transitionSpeed: 1000;
	this.transitionCount = 1;	
	this.transitionSteps = transitionSteps ? transitionSteps: 8;	
	this.preLoad = [];
	
	pics = pics ? pics : Pic;
	for (i = 0; i < pics.length; i++){
		this.preLoad[i] = pics[i];
	}
	
	this.initialize = function() {
		var slideShow = this;		
		var image = document.getElementById(slideShow.imageId);
		
		if(image && !slideShow.initialized) {
			image.slideShow = this;
			
			if(typeof image.style.opacity != 'undefined') {
				slideShow.type = 'w3c';
			}
			else if(typeof image.style.MozOpacity != 'undefined') {
				slideShow.type = 'moz';
			}
			else if(typeof image.style.KhtmlOpacity != 'undefined') {
				slideShow.type = 'khtml';
			}
			else if(typeof image.filters == 'object') {
				slideShow.type = 'ie';
			}
			else {
				slideShow.type = 'none';
			}
			
			slideShow.beginImageIndex = 0;
			slideShow.endImageIndex = 1 % slideShow.preLoad.length;
			image.src = slideShow.preLoad[slideShow.beginImageIndex];
			
			slideShow.initialized = true;
			if(slideShow.preLoad.length > 1) {
		    	slideShow.timerId = setTimeout(function(){slideShow.stay();}, slideShow.slideShowSpeed);
		    }
		}			
	}
	
	this.transition = function() {
		var slideShow = this;
		
		var timerId = slideShow.timerId;
		var image = document.getElementById(slideShow.imageId);
		if(image && image.slideShow == this) {
			if(slideShow.initialized) {
				if(!slideShow.transitioned) {
					var image = document.getElementById(slideShow.imageId);
					if(slideShow.type == 'ie') {
						slideShow.transitioned = false;
						image.style.filter="blendTrans(duration=" + (slideShow.transitionSpeed /1000) + ")";
						image.filters.blendTrans.Apply();			  
						image.src = slideShow.preLoad[slideShow.endImageIndex];
						image.filters.blendTrans.Play();
						slideShow.transitioned = true;
					}else if(slideShow.type != 'none') {
						image.src = slideShow.preLoad[slideShow.endImageIndex];
						
						slideShow.nextImage = image.parentNode.appendChild(document.createElement('img'));
						
						slideShow.nextImage.style.position = "absolute";
						slideShow.nextImage.style.visibility = "hidden";
						slideShow.nextImage.style.left = "0px";
						slideShow.nextImage.style.top = "0px";
						slideShow.nextImage.src = slideShow.preLoad[slideShow.beginImageIndex];

						slideShow.timerId = setInterval(function(){slideShow.fade();}, slideShow.transitionSpeed / slideShow.transitionSteps);
					}else {
						image.src = slideShow.preLoad[slideShow.beginImageIndex];
					}
				}
				
				if(slideShow.transitioned) {
				    if(slideShow.preLoad.length > 1) {
				    	slideShow.timerId = setTimeout(function(){slideShow.stay();}, slideShow.slideShowSpeed);
				    }
				}
			}
		}else {
			clearTimeout(timerId);
		}
	}
	
	
	this.fade = function() {
		var slideShow = this;
		
		var timerId = slideShow.timerId;
		var image = document.getElementById(slideShow.imageId);
		
		if(image && image.slideShow == this) {
			slideShow.transitionCount -= (1 / slideShow.transitionSteps);
			if(slideShow.transitionCount < 1 / slideShow.transitionSteps) {
				clearInterval(slideShow.timerId);
				slideShow.timerId = null;
				slideShow.transitionCount = 1;
							
				image.src = slideShow.nextImage.src;
				
				slideShow.transitioned = true;
			}
			
			switch(slideShow.type) {
				case 'khtml' :
					image.style.KhtmlOpacity = ixf.count;
					slideShow.nextImage.style.KhtmlOpacity = (1 - slideShow.transitionCount);
					break;
					
				case 'moz' : 
					image.style.MozOpacity = (slideShow.transitionCount == 1 ? 0.9999999 : slideShow.transitionCount);
					slideShow.nextImage.style.MozOpacity = (1 - slideShow.transitionCount);
					break;
					
				default : 
					image.style.opacity = (slideShow.transitionCount == 1 ? 0.9999999 : slideShow.transitionCount);
					slideShow.nextImage.style.opacity = (1 - slideShow.transitionCount);
			}
			
			slideShow.nextImage.style.visibility = 'visible';
			
			slideShow.nextImage.style.left = '0px';
			slideShow.nextImage.style.top ='0px';
			
			if(slideShow.transitionCount == 1) {
				slideShow.nextImage.parentNode.removeChild(slideShow.nextImage);
				if(slideShow.preLoad.length > 1) {
			    	slideShow.timerId = setTimeout(function(){slideShow.stay();}, slideShow.slideShowSpeed);
			    }
			}
		}else {
			clearTimeout(timerId);
		}
	}
	
	this.stay = function() {
		var slideShow = this;
		
		var timerId = slideShow.timerId;
		var image = document.getElementById(slideShow.imageId);
		if(image && image.slideShow == this) {
			slideShow.transitioned = false;			
			slideShow.endImageIndex = slideShow.beginImageIndex;
			slideShow.beginImageIndex = (slideShow.beginImageIndex + 1) % slideShow.preLoad.length;
			slideShow.transition();
		}else {
			clearTimeout(timerId);
		}
	}
	
	this.run = function() {
		var slideShow = this;
		var timerId = this.timerId;
		try {
			this.initialize();
		}catch(e) {
			if(timerId) {
				clearTimeout(timerId);
			}
		}
	}
}

function runSlideShow(imageId, pics, slideshowSpeed, transitionSpeed, transitionSteps){
   new SlideShow(imageId, pics, slideshowSpeed, transitionSpeed, transitionSteps).run();
}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 varLastActiveCruiseHomeTab = 'CruiseOnly' ;
var varLastActiveCruiseShipTab = 'ShipOverview' ;
var varLastActiveCruiseShipOnboardTab = 'ShipActivitiesAndEntertainment' ;
var varLastActiveCityTab = 'City2'; 
var varLastActiveThemeParkTab = 'ThemeParkOverview' ;
var varLastActiveThemeParkInnerTab = 'ThemeParkTicketsOptions';
var varLastActiveCruiseOfferTab = 'CruiseOffers' ;
var varLastActiveCruiseCategoryGroupTab = 'InsideStateroom' ;
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 _parentDivId;
var _region;
var _trackingText;
var _destinationCode = '';
var _regionCode = '';
var _packageId = '';
var _destinationName = '';
var _cruiseLineName = '';
var _shipName = '';
var _departureDate = '';
var varSearchMode = '';
var _cruiseCategoryGroupInsideDivName;
var _cruiseCategoryGroupOceanViewDivName;
var _cruiseCategoryGroupBalconyDivName;
var _cruiseCategoryGroupSuiteDivName;
var _carCompanyName = '';

// _cruisePackageId is used for reporting page tracking to Google Analytics
var _cruisePackageId = null;

/* 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 initializeCruiseHomeTab() {
	varLastActiveCruiseHomeTab = 'CruiseOnly';
}

function initializeCruiseShipTab() {
	varLastActiveCruiseShipTab = 'ShipOverview';
}

function initializeThemeParkTab() {
	varLastActiveThemeParkTab = 'ThemeParkOverview';
}

function initializeThemeParkInnerTab() {
	varLastActiveThemeParkInnerTab = 'ThemeParkTicketsOptions';
}

function activateTab(tabName, tabGroup, activeTabCssClass, inactiveTabCssClass) {
	var activeTab = document.getElementById('div' + tabName);
	var allTabs = getElementsByAttribute(activeTab.parentNode, "tabGroup", tabGroup);

	for(var i=0; i< allTabs.length; i++) {
		var currentTab = allTabs[i];
		currentTab.className = inactiveTabCssClass;
	}	
	
	var lastActiveTab = document.getElementById('div' + tabGroup);
	if(lastActiveTab) {
		lastActiveTab.className = inactiveTabCssClass;
	}
	activeTab.className = activeTabCssClass;
}

function activateHotelTab(tabName) {		
	activateTab(tabName, varLastActiveHotelTab, "tab-sel01", "tab01");

	if(varLastActiveHotelTab != tabName) {
		varLastActiveHotelTab = tabName ;
	}
}

function activateHotelPopupTab(tabName) {
	activateTab(tabName, "hotelPropertyTab", "tab-sel01", "tab01");
}

function activateHotelInnerTab(tabName) {	
	activateTab(tabName, varLastActiveHotelInnerTab, "tab-sel02", "tab02");

	if(varLastActiveHotelInnerTab != tabName) {
		varLastActiveHotelInnerTab = tabName ;
	}
}

function activateCityTab(tabName) {	
	activateTab(tabName, "packageCityTabGroup", "tab-sel01", "tab01");
}

function activateDestinationHomeTab(tabName) {	
	activateTab(tabName, "destinationHomeTabGroup", "tab-sel01", "tab01");	
	varSearchMode = "VacationPackage";
}

function activateDestinationTab(tabName) {	
	activateTab(tabName, varLastActiveDestinationTab, "tab-sel01", "tab01");

	if(varLastActiveDestinationTab != tabName) {
		varLastActiveDestinationTab = tabName ;
	}
	
	varSearchMode = "VacationPackage";
}

function activateRegionTab(tabName) {	
	activateTab(tabName, varLastActiveRegionTab, "tab-sel01", "tab01");

	if(varLastActiveRegionTab != tabName) {
		varLastActiveRegionTab = tabName ;
	}

	varSearchMode = "VacationPackage";
}

function activateAreaTab(tabName) {	
	activateTab(tabName, varLastActiveAreaTab, "tab-sel01", "tab01");

	if(varLastActiveAreaTab != tabName) {
		varLastActiveAreaTab = tabName ;
	}

	varSearchMode = "VacationPackage";
}

function activateCruiseTab(tabName) {
	activateTab(tabName, "cruiseTabGroup", "tab-sel01", "tab01");
	varSearchMode = "Cruise";
}

function activateCruiseHomeTab(tabName) {
	if( isNull( document.getElementById( 'div'+tabName ) ))
		return false;
	activateTab(tabName, "cruiseHomeTabGroup", "tab-sel01", "tab01");
	varSearchMode = "Cruise";
}

function activateCruiseShipTab(tabName) {	
	activateTab(tabName, varLastActiveCruiseShipTab, "tab-sel01", "tab01");

	if(varLastActiveCruiseShipTab != tabName) {
		varLastActiveCruiseShipTab = tabName ;
	}

	varSearchMode = "Cruise";
}

function activateCruiseShipOnboardTab(tabName) {	
	activateTab(tabName, "cruiseOnboardTabGroup", "tab-sel02", "tab02");
	varSearchMode = "Cruise";
}

function activateThemeParkTab(tabName) {		
	activateTab(tabName, varLastActiveThemeParkTab, "tab-sel01", "tab01");

	if(varLastActiveThemeParkTab != tabName) {
		varLastActiveThemeParkTab = tabName ;
	}
}

function activateThemeParkInnerTab(tabName) {	
	activateTab(tabName, varLastActiveThemeParkInnerTab, "tab-sel02", "tab02");

	if(varLastActiveThemeParkInnerTab != tabName) {
		varLastActiveThemeParkInnerTab = tabName ;
	}
}

function activateCruiseOfferTab(tabName) {	
	activateTab(tabName, "cruiseOfferTabGroup", "tab-sel01", "tab01");
	varSearchMode = "Cruise";
}

function activateCruiseCategoryGroupTab(tabName) {	
	activateTab(tabName, "cruiseCategoriesTabGroup", "tab-sel02", "tab02");
	varSearchMode = "Cruise";
}

function showCruiseCategoryGroup(cruiseCategoryGroupDivName) {
	hideBlock(_cruiseCategoryGroupInsideDivName);
	hideBlock(_cruiseCategoryGroupOceanViewDivName);
	hideBlock(_cruiseCategoryGroupBalconyDivName);
	hideBlock(_cruiseCategoryGroupSuiteDivName);
	
	showBlock(cruiseCategoryGroupDivName);
}

function loadHomePage()
{
	//Load the main content block with '/home' as the description to be passed into Google Analytics
	loadMainContent('mainContent.act', 'mac=2', '/home');
	loadDestinationTopBandImage();
	
	//Add the pseudo code "1" to browser history
	addHistory(PageHistoryConstants.HISTORY_HOME);
	
	//Scroll to the top of the page
	window.scrollTo(0,0);
	setSupportPhoneNumber(bookingPhoneNumber);
	varSearchMode = "VacationPackage";
}

function loadDestinationHome(trackingText) {
	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, (trackingText ? trackingText : '/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(PageHistoryConstants.HISTORY_DESTINATION_HOME);

	//Scroll to the top of the page
	window.scrollTo(0,0);
	setSupportPhoneNumber(bookingPhoneNumber);
	varSearchMode = "VacationPackage";
}

function loadDestination(destination, trackingText) {
	//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=4&rc=1&rbc=1', (trackingText ? trackingText : '/vp/browse/destination/' + destination));
	loadDestinationTopBandImage(destination);

	//Add the pseudo code "5_<destinationCode>" to browser history
	addHistory(PageHistoryConstants.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/<destinationCode>' as the description to be passed into Google Analytics
	loadVacationTabContent('vacationTabContent.act', 'destination=' + destination + '&vtc=17', '/vp/browse/destinatonSightseeings/' +  destination);
}

function loadDestinationThemeParks(destination) {
	//Load the vacation content block with '/vp/browse/destinatonThemeParks/<destinationCode>' as the description to be passed into Google Analytics
	loadVacationTabContent('vacationTabContent.act', 'destination=' + destination + '&vtc=20', '/vp/browse/destinatonThemeParks/' +  destination);
}

function loadRegion(destination, region, trackingText) {
	//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=4&rc=1&rcc=1&rbc=2', (trackingText ? trackingText : '/vp/browse/regional/' +  destination + '/' + region));
	loadDestinationTopBandImage(destination);

	//Add the pseudo code "6_<destinationCode>_<regionCode>" to browser history
	addHistory(PageHistoryConstants.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 loadRegionThemeParks(destination, region) {
	//Load the vacation tab content block with '/vp/browse/destinationThemeParks/<destination>/<region>' as the description to be passed into Google Analytics
	loadVacationTabContent('vacationTabContent.act', 'destination=' + destination + '&region=' + region + '&vtc=21', '/vp/browse/destinationThemeParks/' +  destination + '/' + region);
}

function loadArea(destination, region, area, trackingText) {
	//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=4&rc=1&rcc=2&rbc=3', (trackingText ? trackingText : '/vp/browse/area/' +  destination + '/' + region + '/' + area));
	loadDestinationTopBandImage(destination);

	//Add the pseudo code "7_<destinationCode>_<regionCode>_<areaCode>" to browser history
	addHistory(PageHistoryConstants.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/<destinationCode>/<regionCode>/<areaCode>' 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/<destinationCode>/<regionCode>/<areaCode>' 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 loadAreaThemeParks(destination, region, area) {
	//Load the vacation tab content block with '/vp/browse/destinationThemeParks/<destinationCode>/<regionCode>/<areaCode>' as the description to be passed into Google Analytics
	loadVacationTabContent('vacationTabContent.act', 'destination=' + destination + '&region=' + region + '&area=' + area  + '&vtc=22', '/vp/browse/destinationThemeParks/' +  destination + '/' + region + '/' + area);
}

function loadHotel(destination, cityCode, hotelId, region, area, displayOffer, packageId, packageName, trackingText) {
	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, (trackingText ? trackingText : '/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, (trackingText ? trackingText : '/an/browse/hotel/hotel/' +  destination + '/' + cityCode + '/' + hotelId));
	}

	//Add the pseudo code "16_<destinationCode>_<cityCode>_<hotelId>_<regionCode>_<areaCode>_<displayOffer>_<packageId>_<packageName>" to browser history
	addHistory(PageHistoryConstants.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, trackingText) {
	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, (trackingText ? trackingText : '/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, (trackingText ? trackingText : '/an/browse/hotel/hotel/' +  destination + '/' + cityCode + '/' + hotelId));
	}

	//Add the pseudo code "17_<destinationCode>_<cityCode>_<hotelId>_<regionCode>_<areaCode>_<displayOffer>_<packageId>_<packageName>" to browser history
	addHistory(PageHistoryConstants.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 loadRightContentThemePark(venueId, destination, region, area, trackingText) {
	var queryString = 'rc=31';
	if(venueId) {
		queryString += '&venueId=' + venueId;
	}
	if(destination) {
		queryString += '&destination=' + destination;
	}
	if(region) {
		queryString += '&region=' + region;
	}
	if(area) {
		queryString += '&area=' + area;
	}

	//Load the right content block with '/an/browse/themeParks/themeParks/<destinationCode>/<regionCode>/<areaCode><venueId>' as the description to be passed into Google Analytics
	loadRightContent('rightContent.act', queryString, (trackingText ? trackingText : '/an/browse/themeParks/themeParks/' +  destination + '/' + region + '/' + area + '/' + venueId));

	//Add the pseudo code "17_<destinationCode>_<cityCode>_<hotelId>_<regionCode>_<areaCode>_<displayOffer>_<packageId>_<packageName>" to browser history
	addHistory(PageHistoryConstants.HISTORY_RIGHT_CONTENT_THEME_PARK, venueId, destination, region, area);

	//Initialize the tab structure within theme parks tab content div to display the first tab
	initializeThemeParkTab();

	//Initialize the tab structure within theme parks inner tab content div to display the first tab
	initializeThemeParkInnerTab();

	//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, trackingText ) {
	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, (trackingText ? trackingText : '/vp/browse/package/' + packageId));
	//loadDestinationTopBandImage();
	//Add the pseudo code "13_<destinationCode>_<regionCode>_<areaCode>_<hotelId>_<packageId>_<cityCode>_<ancillaryCode>_<ancillaryCategoryCode>" to browser history
	addHistory(PageHistoryConstants.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(PageHistoryConstants.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(PageHistoryConstants.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 loadParkAndTheaterVendorPopup(vendorId, destination, region, area){
	loadParkAndTheaterVendorPopupDiv('parkAndTheaterContent.act', '&vendorId=' + vendorId + '&ptc=2' + '&destination=' + destination + '&region=' + region + '&area=' + area);
}

function loadParkAndTheaterVenuePopup(venueId, destination, region, area, parentDivId, parkName){
	//Load the park and theater content block with '/an/browse/themeParks/themeParks/<destinationCode>/<regionCode>/<areaCode>/<venueId>' as the description to be passed into Google Analytics
	loadParkAndTheaterVenuePopupDiv('parkAndTheaterContent.act', '&venueId=' + venueId + '&ptc=3' + '&destination=' + destination + '&region=' + region + '&area=' + area + '&parkName=' + parkName, '/an/browse/themeParks/themeParks/' +  destination + '/' + region + '/' + area + '/' + venueId, parentDivId);
}

function loadThemeParkOverview(venueId, destination, region, area) {	
	//Load the theme park tab content block with '/an/browse/themeParkOverview/themePark/<destinationCode>/<regionCode>/<areaCode>/<venueId>' as the description to be passed into Google Analytics
	loadThemeParkTabContent('parkAndTheaterContent.act', 'destination=' + destination + '&region=' + region + '&area=' + area + '&venueId=' + venueId + '&ptc=4', '/an/browse/themeParkOverview/themePark/' +  destination + '/' + region + '/' + area + '/' + venueId);
}

function loadThemeParkAttractions(venueId, destination, region, area) {	
	//Load the theme park tab content block with '/an/browse/themeParkAttractions/themePark/<destinationCode>/<regionCode>/<areaCode>/<venueId>' as the description to be passed into Google Analytics
	loadThemeParkTabContent('parkAndTheaterContent.act', 'destination=' + destination + '&region=' + region + '&area=' + area + '&venueId=' + venueId + '&ptc=5', '/an/browse/themeParkAttractions/themePark/' +  destination + '/' + region + '/' + area + '/' + venueId);
}

function loadThemeParkDining(venueId, destination, region, area) {	
	//Load the theme park tab content block with '/an/browse/themeParkDining/themePark/<destinationCode>/<regionCode>/<areaCode>/<venueId>' as the description to be passed into Google Analytics
	loadThemeParkTabContent('parkAndTheaterContent.act', 'destination=' + destination + '&region=' + region + '&area=' + area + '&venueId=' + venueId + '&ptc=6', '/an/browse/themeParkDining/themePark/' +  destination + '/' + region + '/' + area + '/' + venueId);
}

function loadThemeParkMaps(venueId, destination, region, area) {	
	//Load the theme park tab content block with '/an/browse/themeParkMaps/themePark/<destinationCode>/<regionCode>/<areaCode>/<venueId>' as the description to be passed into Google Analytics
	loadThemeParkTabContent('parkAndTheaterContent.act', 'destination=' + destination + '&region=' + region + '&area=' + area + '&venueId=' + venueId + '&ptc=7', '/an/browse/themeParkMaps/themePark/' +  destination + '/' + region + '/' + area + '/' + venueId);
}

function loadThemeParkTickets(venueId, destination, region, area) {	
	//Load the theme park tab content block with '/an/browse/themeParkTickets/themePark/<destinationCode>/<regionCode>/<areaCode>/<venueId>' as the description to be passed into Google Analytics
	loadThemeParkTabContent('parkAndTheaterContent.act', 'destination=' + destination + '&region=' + region + '&area=' + area + '&venueId=' + venueId + '&ptc=8', '/an/browse/themeParkTickets/themePark/' +  destination + '/' + region + '/' + area + '/' + venueId);
}

function loadThemeParkTicketsOptions(venueId, destination, region, area) {	
	//Load the theme park tab content block with '/an/browse/themeParkTicketsOptions/themePark/<destinationCode>/<regionCode>/<areaCode>/<venueId>' as the description to be passed into Google Analytics
	loadThemeParkInnerTabContent('parkAndTheaterContent.act', 'destination=' + destination + '&region=' + region + '&area=' + area + '&venueId=' + venueId + '&ptc=9', '/an/browse/themeParkTicketsOptions/themePark/' +  destination + '/' + region + '/' + area + '/' + venueId);
}

function loadThemeParkTicketsFAQ(venueId, destination, region, area) {	
	//Load the theme park tab content block with '/an/browse/themeParkTicketsFAQ/themePark/<destinationCode>/<regionCode>/<areaCode>/<venueId>' as the description to be passed into Google Analytics
	loadThemeParkInnerTabContent('parkAndTheaterContent.act', 'destination=' + destination + '&region=' + region + '&area=' + area + '&venueId=' + venueId + '&ptc=10', '/an/browse/themeParkTicketsFAQ/themePark/' +  destination + '/' + region + '/' + area + '/' + venueId);
}

function loadCruise(trackingText) {
	loadCruiseWidgetHome(false, trackingText);
}

function loadCruiseWidgetHome(isCruiseTour, trackingText) {
	if(isNull(isCruiseTour)) {
		isCruiseTour = false;
	}
	
	var queryString = 'lbc=2&rc=1&rcc=5&rruc=2';
	if(isCruiseTour) {
		queryString += '&lc=12&rbc=8&ctc=14&cruiseOnlySearch=false';
		trackingText = (trackingText ? trackingText : '/cr/browse/cruiseTourPackages/');
		varLastActiveCruiseTab = 'CruiseWhyCruiseTour';
	}
	else {
		queryString += '&lc=7&rbc=4&ctc=13&cruiseOnlySearch=true'
		trackingText = (trackingText ? trackingText : '/cr/browse/cruiseHome/');
		varLastActiveCruiseTab = 'CruiseWhyCruise';
	}

	//Load the main content block with '/cr/browse/cruiseHome/' or '/cr/browse/cruiseTourPackages/'as the description to be passed into Google Analytics
	loadMainContentWithWaitingDiv('mainContent.act', queryString, trackingText);
	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(PageHistoryConstants.HISTORY_CRUISE_HOME);

	//Scroll to the top of the page
	window.scrollTo(0,0);
	setSupportPhoneNumber(bookingPhoneNumber);
	varSearchMode = "Cruise";
}

function loadCruiseDestination(cruiseDestination, trackingText) {
	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, (trackingText ? trackingText : '/cr/browse/cruiseDest///' + cruiseDestination));
	loadDestinationTopBandImage();

	//Add the pseudo code "8" to browser history
	addHistory(PageHistoryConstants.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 loadCruiseWhyCruiseTour() {
	//Load the cruise tab content block with '/cr/browse/cruiseWhyCruiseTour/' as the description to be passed into Google Analytics
	loadCruiseTabContent('cruiseTabContent.act', 'ctc=15', '/cr/browse/cruiseWhyCruiseTour/');
}

function loadCruiseSelectingACruiseTour() {
	//Load the cruise tab content block with '/cr/browse/cruiseSelectingACruiseTour/' as the description to be passed into Google Analytics
	loadCruiseTabContent('cruiseTabContent.act', 'ctc=16', '/cr/browse/cruiseSelectingACruiseTour/');
}

function loadCruiseTourCruiseLines() {
	//Load the cruise tab content block with '/cr/browse/cruiseTourLines/' as the description to be passed into Google Analytics
	loadCruiseTabContent('cruiseTabContent.act', 'ctc=17', '/cr/browse/cruiseTourLines/');
}

function loadCruiseTourKnowBeforeYouGo() {
	//Load the cruise tab content block with '/cr/browse/cruiseTourBeforeYouGo/' as the description to be passed into Google Analytics
	loadCruiseTabContent('cruiseTabContent.act', 'ctc=18', '/cr/browse/cruiseTourBeforeYouGo/');
}

function loadCruiseLine(cruiseLine, ancillary, ancillaryCategory, trackingText) {
	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, (trackingText ? trackingText : '/cr/browse/cruiseLines/' + cruiseLine));
	loadDestinationTopBandImage();

	//Add the pseudo code "9_<cruiseLineCode>_<ancillaryCode>_<ancillaryCategoryCode>" to browser history
	addHistory(PageHistoryConstants.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, trackingText) {
	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, (trackingText ? trackingText : '/cr/browse/cruiseShip/' + cruiseLine + '/' + ship));
	loadDestinationTopBandImage();

	//Add the pseudo code "10_<cruiseLineCode>_<shipCode>_<ancillaryCode>_<ancillaryCategoryCode>" to browser history
	addHistory(PageHistoryConstants.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 loadCruiseTourHighlights( cruiseSailingItemUid, itineraryName ) {
	var trackingText = '/cr/browse/cruiseTourHighlights/';
	trackingText += (itineraryName) ? ('/' + itineraryName) : '';
	loadCruiseTabContent('cruiseSailingResults.act', 'csr=19&cruiseSailingItemUid=' + cruiseSailingItemUid, trackingText, true );
}

function loadCruiseItinerary( cruiseSailingItemUid, disableBackground, packageId, destination, cruiseLine, ship, departureDate ) {
	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);
	}	

	var trackingText = '/cr/browse/cruiseItinerary';
	trackingText += (destination) ? ('/' + destination) : '';
	trackingText += (cruiseLine) ? ('/' + cruiseLine) : '';
	trackingText += (ship) ? ('/' + ship) : '';
	trackingText += (departureDate) ? ('/' + year + month + day) : '';
	
	loadCruiseTabContent('cruiseSailingResults.act', 'csr=9&cruiseSailingItemUid=' + cruiseSailingItemUid + "&fromPackageLandingPage=true&packageId=" + packageId, trackingText, isNull(disableBackground) ? true : disableBackground );
}

function loadCruiseShipOverview(cruiseLine, ship, displayShipImage) {
	//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 + '&displayShipImage=' + displayShipImage, '/cr/browse/cruiseShipOverview/' + cruiseLine + '/' + ship, true);
}

function loadCruiseShipOnboard(cruiseLine, ship) {
	//Load the cruise tab content block with '/cr/browse/cruiseShipOnboard/<cruiseLineCode>/<cruiseShipCode>' as the description to be passed into Google Analytics
	loadCruiseTabContent('cruiseTabContent.act', 'ctc=11&cruiseLine=' + cruiseLine + '&ship=' + ship, '/cr/browse/cruiseShipOnboard/' + cruiseLine + '/' + ship, true);
}

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
	loadCruiseShipOnboardTabContent('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
	loadCruiseShipOnboardTabContent('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
	loadCruiseShipOnboardTabContent('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
	loadCruiseShipOnboardTabContent('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
	loadCruiseShipOnboardTabContent('cruiseTabContent.act', 'ctc=10&cruiseLine=' + cruiseLine + '&ship=' + ship, '/cr/browse/cruiseStateroom/' + cruiseLine + '/' + ship);
}

function loadCruiseOffers(packageId) {
	//Load the cruise tab content block with '/cr/browse/cruisePackage////<packageId>' as the description to be passed into Google Analytics
	loadCruiseTabContent('cruiseTabContent.act', 'ctc=12&packageId=' + packageId, '/cr/browse/cruisePackage////' + packageId, true);
}

function loadCruiseOnlyPackages() {
	//Load the cruise tab content block with '/cr/browse/cruiseHome/' as the description to be passed into Google Analytics
	//loadCruisePackageTabContent('cruiseTabContent.act', 'ctc=13', '/cr/browse/cruiseHome/');
	loadCruiseWidgetHome(false);
}

function loadCruiseTourPackages() {
	//Load the cruise tab content block with '/cr/browse/cruiseTourPackages/' as the description to be passed into Google Analytics
	//loadCruisePackageTabContent('cruiseTabContent.act', 'ctc=14', '/cr/browse/cruiseTourPackages/');
	loadCruiseWidgetHome(true);
}

function loadRightContentCruisePackage(cruiseLine, ship, packageId, ancillary, ancillaryCategory, cruiseDestination, trackingText) {
	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, (trackingText ? trackingText : '/cr/browse/cruisePackage////' + packageId));
	//Add the pseudo code "14_<cruiseLineCode>_<shipCode>_<packageId>_<ancillaryCode>_<ancillaryCategoryCode>" to browser history
	addHistory(PageHistoryConstants.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&lc=11&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(PageHistoryConstants.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&lc=11&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(PageHistoryConstants.HISTORY_CRUISE_PACKAGE, cruiseLine, null, nextPackageId);
	//Scroll to the top of the page
	window.scrollTo(0,0);
}

function loadAncillaryHome(trackingText) {
	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, (trackingText ? trackingText : '/an/browse/ancillaryHome/'));
	loadDestinationTopBandImage();

	//Add the pseudo code "4" to browser history
	addHistory(PageHistoryConstants.HISTORY_ANCILLARY_HOME);

	//Scroll to the top of the page
	window.scrollTo(0,0);
	setSupportPhoneNumber(bookingPhoneNumber);
}

function loadAncillary(ancillary, searchMode, trackingText) {
	var queryString = ''; 
	
	if (searchMode){
		varSearchMode = searchMode;
	}	

	if( ancillary == 'rentalCars' )  {
		queryString = 'lc=19&lbc=5';
	}
	else if (varSearchMode == "Cruise"){
		queryString = 'lc=7&lbc=2';
	}
	else {
		queryString = 'lbc=0';
	}

	queryString += '&rc=6&ancillary=' + ancillary;
	
	if(!trackingText) {
		if (ancillary == 'rentalCars'){
			//Load the main content block with '/rc/browse/rentalCarsHome/' as the description to be passed into Google Analytics
			trackingText = '/rc/browse/carsHome';
		}	
		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(PageHistoryConstants.HISTORY_ANCILLARY_LANDING, ancillary);

	//Scroll to the top of the page
	window.scrollTo(0,0);
	setSupportPhoneNumber(bookingPhoneNumber);
}

function loadAncillaryCategory(ancillary, ancillaryCategory, searchMode, trackingText) {
	var queryString = '';

	if (searchMode){
		varSearchMode = searchMode; 
	}	
	
	if( ancillary == 'rentalCars' )  {
		queryString = 'lc=19&lbc=5';
	}
	else if (varSearchMode == "Cruise"){
		queryString = 'lc=7&lbc=2';
	}
	else {
		queryString = 'lbc=0';
	}
	
	queryString += '&rc=7&ancillary=' + ancillary + '&ancillaryCategory=' + ancillaryCategory;
	
	if(!trackingText) {
		if (ancillary == 'rentalCars'){
			//Load the main content block with '/rc/browse/rentalCarsBrand/' as the description to be passed into Google Analytics
			trackingText = '/rc/browse/brandHome/' + 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(PageHistoryConstants.HISTORY_ANCILLARY_CATEGORY_LANDING, ancillary, ancillaryCategory);

	//Scroll to the top of the page
	window.scrollTo(0,0);
	setSupportPhoneNumber(bookingPhoneNumber);
}

function loadRightContentAncillaryPackage(ancillary, ancillaryCategory, packageId, trackingText) {
	var queryString = 'h=0';
	
	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(!trackingText) {
		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(PageHistoryConstants.HISTORY_ANCILLARY_PACKAGE, ancillary, ancillaryCategory, packageId);

	//Scroll to the top of the page
	window.scrollTo(0,0);
}

function loadBlastOffer(blastId, trackingText) {
	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, (trackingText ? trackingText : '/em/email/blastOffer/' + blastId));
	loadDestinationTopBandImage();

	//Add the pseudo code "20_<blastId>" to browser history
	addHistory(PageHistoryConstants.HISTORY_BLAST_OFFER_LANDING, blastId);

	//Scroll to the top of the page
	window.scrollTo(0,0);
}

function loadCruiseBlastOffer(blastId, trackingText) {
	var queryString = 'lbc=2&lc=7&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, (trackingText ? trackingText : '/em/email/cruiseBlastOffer/' + blastId));
	loadDestinationTopBandImage();

	//Add the pseudo code "20_<blastId>" to browser history
	addHistory(PageHistoryConstants.HISTORY_BLAST_OFFER_LANDING, blastId);

	//Scroll to the top of the page
	window.scrollTo(0,0);
}

function loadSweepstakes(sweepstakesCode, trackingText) {
	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, (trackingText ? trackingText : '/gi/generalInfo/sweepstakes/' + sweepstakesCode));
	loadDestinationTopBandImage();
	
	//Add the pseudo code "21_<sweepstakesCode>" to browser history
	addHistory(PageHistoryConstants.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(PageHistoryConstants.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(PageHistoryConstants.HISTORY_SITE_MAP);

	//Scroll to the top of the page
	window.scrollTo(0,0);
	setSupportPhoneNumber(bookingPhoneNumber);
}

function loadExternalUrl(url, trackingText) {
	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.")) {
		trackPageView((trackingText ? trackingText : 'home/externalUrl/' + url));
		window.open(url);
		return true;
	}
	else {
		return false;
	}
}

function loadInternalUrl(url, trackingText) {
	trackPageView((trackingText ? trackingText : 'home/internalUrl/' + url));
	window.location = url;
	return true;
}

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 loadLeftAndRightContent(leftContentUrl, leftContentUrlQueryString, rightContentUrl, rightContentUrlQueryString, trackingText) {
	makeMultiAjaxCall(new Array(
			new AsynchronousMultiRequestItem(leftContentUrl, leftContentUrlQueryString, null, "leftContent", "callbackLoadLeftContent", null, trackingText),
			new AsynchronousMultiRequestItem(rightContentUrl, rightContentUrlQueryString, null, "rightContent", "callbackLoadRightContent", null, trackingText)
		   )
	);	
}


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, -1, 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, -1, 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 loadParkAndTheaterVendorPopupDiv(parkAndTheaterVendorContentUrl, parkAndTheaterVendorContentUrlQueryString, trackingText) {
	var parkAndTheaterVendorPopupDiv = document.getElementById('parkAndTheaterVendorPopupDiv');
	if(parkAndTheaterVendorPopupDiv == null){
		parkAndTheaterVendorPopupDiv = createPopupDiv('parkAndTheaterVendorPopupDiv', 0, 0, 700, -1, 200, false, true,  "tal popupDivBig");
	}
	makeAjaxCall(parkAndTheaterVendorContentUrl, parkAndTheaterVendorContentUrlQueryString, null, 'parkAndTheaterVendorPopupDiv', 'callbackLoadParkAndTheaterVendorPopupDiv', trackingText);
}

function callbackLoadParkAndTheaterVendorPopupDiv() {
	document.title = "Costco Travel";	
	showBlock('parkAndTheaterVendorPopupDiv'); 
	positionBlockCentrally('parkAndTheaterVendorPopupDiv'); 
	document.getElementById('parkAndTheaterPopupVendorContentDiv').scrollTop = 0;
	disableElement( 'dataContent', true );
}

function loadParkAndTheaterVenuePopupDiv(parkAndTheaterVenueContentUrl, parkAndTheaterVenueContentUrlQueryString, trackingText, parentDivId) {
	_parentDivId = parentDivId;
	var parkAndTheaterVenuePopupDiv = document.getElementById('parkAndTheaterVenuePopupDiv');
	if(parkAndTheaterVenuePopupDiv == null){
		var zIndex = 200;
		if(parentDivId) {
			zIndex = 202;
		}
		parkAndTheaterVenuePopupDiv = createPopupDiv('parkAndTheaterVenuePopupDiv', 0, 0, 700, -1, zIndex, false, true,  "tal popupDivBig");
	}
	makeAjaxCall(parkAndTheaterVenueContentUrl, parkAndTheaterVenueContentUrlQueryString, null, 'parkAndTheaterVenuePopupDiv', 'callbackLoadParkAndTheaterVenuePopupDiv', trackingText);
}

function callbackLoadParkAndTheaterVenuePopupDiv() {
	document.title = "Costco Travel";	
	showBlock('parkAndTheaterVenuePopupDiv'); 
	positionBlockCentrally('parkAndTheaterVenuePopupDiv'); 
	document.getElementById('themeParkTabContent').scrollTop = 0;
	if(!_parentDivId) {
		_parentDivId = 'dataContent';
	}
	disableElement( _parentDivId, 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, disableBackground) {
	if( disableBackground ) {
		disableElement( 'dataContent', true );
	}
	if( disableBackground ) {
		makeAjaxCallWithWaitingDiv( cruiseTabContentUrl, cruiseTabContentUrlQueryString, null, 'cruiseTabContent', 'callbackLoadCruiseTabContent', null, trackingText);
	} else {
		makeAjaxCall(cruiseTabContentUrl, cruiseTabContentUrlQueryString, null, 'cruiseTabContent', 'callbackLoadCruiseTabContent', trackingText);
	}
}

function callbackLoadCruiseTabContent() {
	disableElement( 'dataContent', false );
	document.title = "Costco Travel";
}

function loadCruisePackageTabContent(cruiseTabContentUrl, cruiseTabContentUrlQueryString, trackingText) {
	makeAjaxCall(cruiseTabContentUrl, cruiseTabContentUrlQueryString, null, 'cruisePackageTabContent', 'callbackLoadCruisePackageTabContent', trackingText);
}

function callbackLoadCruisePackageTabContent() {
	document.title = "Costco Travel";
}

function loadCruiseShipOnboardTabContent(cruiseShipOnboardTabContentUrl, cruiseShipOnboardTabContentUrlQueryString, trackingText) {
	makeAjaxCall(cruiseShipOnboardTabContentUrl, cruiseShipOnboardTabContentUrlQueryString, null, 'cruiseShipOnboardTabContent', 'callbackLoadCruiseShipOnboardTabContent', trackingText);
}

function callbackLoadCruiseShipOnboardTabContent() {
	document.title = "Costco Travel";
}

function loadThemeParkTabContent(themeParkTabContentUrl, themeParkTabContentUrlQueryString, trackingText) {
	makeAjaxCall(themeParkTabContentUrl, themeParkTabContentUrlQueryString, null, 'themeParkTabContent', 'callbackThemeParkTabContent', trackingText);
}

function callbackThemeParkTabContent() {
	document.title = "Costco Travel";
}

function loadThemeParkInnerTabContent(themeParkInnerTabContentUrl, themeParkInnerTabContentUrlQueryString, trackingText) {
	makeAjaxCall(themeParkInnerTabContentUrl, themeParkInnerTabContentUrlQueryString, null, 'themeParkInnerTabContent', 'callbackThemeParkInnerTabContent', trackingText);
}

function callbackThemeParkInnerTabContent() {
	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?mac=2';
	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 = "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 = "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 = "trackPageView('" + trackingText + "')";
		}
		
		submitWithoutReload(asynchronousRequest);
	}
}



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] == PageHistoryConstants.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(PageHistoryConstants.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 PageHistoryConstants.HISTORY_LANDING_URL: {
				if(storageData) {
					window.location.href = storageData;
					if(browser.chrome || browser.safari) {
						window.location.reload();
					}
				}
				break;
			}
			case PageHistoryConstants.HISTORY_HOME: {
				loadHomePage();
				break;
			}
			case PageHistoryConstants.HISTORY_DESTINATION_HOME: {
				loadDestinationHome();
				break;
			}
			case PageHistoryConstants.HISTORY_DESTINATION_LANDING: {
				loadDestination(tokens[1]);
				break;
			}
			case PageHistoryConstants.HISTORY_REGION_LANDING: {
				loadRegion(tokens[1], tokens[2]);
				break;
			}
			case PageHistoryConstants.HISTORY_AREA_LANDING: {
				loadArea(tokens[1], tokens[2], tokens[3]);
				break;
			}
			case PageHistoryConstants.HISTORY_CRUISE_HOME: {
				loadCruiseWidgetHome(false);
				break;
			}
			case PageHistoryConstants.HISTORY_CRUISE_DESTINATION_LANDING: {
				loadCruiseDestination(tokens[1]);
				break;
			}
			case PageHistoryConstants.HISTORY_CRUISE_LINE_LANDING: {
				loadCruiseLine(tokens[1]);
				break;
			}
			case PageHistoryConstants.HISTORY_CRUISE_SHIP_LANDING: {
				loadCruiseShip(tokens[1], tokens[2]);
				break;
			}
			case PageHistoryConstants.HISTORY_ANCILLARY_HOME: {
				loadAncillaryHome();
				break;
			}
			case PageHistoryConstants.HISTORY_ANCILLARY_LANDING: {
				loadAncillary(tokens[1]);
				break;
			}
			case PageHistoryConstants.HISTORY_ANCILLARY_CATEGORY_LANDING: {
				loadAncillaryCategory(tokens[1], tokens[2]);
				break;
			}
			case PageHistoryConstants.HISTORY_LAND_PACKAGE: {
				loadRightContentPackage(tokens[1], tokens[2], tokens[3], tokens[4], tokens[5], tokens[6], tokens[7], tokens[8], false);
				break;
			}
			case PageHistoryConstants.HISTORY_CRUISE_PACKAGE: {
				loadRightContentCruisePackage(tokens[1], tokens[2], tokens[3], tokens[4], tokens[5]);
				break;
			}
			case PageHistoryConstants.HISTORY_ANCILLARY_PACKAGE: {
				loadRightContentAncillaryPackage(tokens[1], tokens[2], tokens[3]);
				break;
			}
			case PageHistoryConstants.HISTORY_HOTEL: {
				loadHotel(tokens[1], tokens[2], tokens[3], tokens[4], tokens[5], tokens[6]);
				break;
			}
			case PageHistoryConstants.HISTORY_RIGHT_CONTENT_HOTEL: {
				loadRightContentHotel(tokens[1], tokens[2], tokens[3], tokens[4], tokens[5], tokens[6]);
				break;
			}
			case PageHistoryConstants.HISTORY_RIGHT_CONTENT_THEME_PARK: {
				loadRightContentThemePark(tokens[1], tokens[2], tokens[3], tokens[4]);
				break;
			}
			case PageHistoryConstants.HISTORY_GENERAL_INFO: {
				loadGeneralInfo(tokens[1]);
				break;
			}
			case PageHistoryConstants.HISTORY_SITE_MAP: {
				loadSiteMap();
				break;
			}
			case PageHistoryConstants.HISTORY_BLAST_OFFER_LANDING: {
				loadBlastOffer(tokens[1]);
				break;
			}
			case PageHistoryConstants.HISTORY_SWEEPSTAKES_LANDING: {
				loadSweepstakes(tokens[1]);
				break;
			}
			case PageHistoryConstants.HISTORY_SEARCH_RESULT_ALL_PACKAGES: {
				if(storageData) {
					searchAllPackagesForDestinationAndRegion(storageData.queryString, storageData.showSplashScreen);
				}
				else {
					reLoadPackageResults();
				}
				break;
			}
			case PageHistoryConstants.HISTORY_SEARCH_RESULT_PACKAGE_FLIGHT_HOTEL: {
				loadSearchResults_1();
				break;
			}
			case PageHistoryConstants.HISTORY_SEARCH_RESULT_PACKAGE_TRANSPORTATION: {
				loadSearchResults_2();
				break;
			}
			case PageHistoryConstants.HISTORY_BOOKING_RECAP: {
				loadBookingRecap();
				break;
			}
			case PageHistoryConstants.HISTORY_PASSENGER_DETAILS: {
				loadPassengerInformation();
				break;
			}
			case PageHistoryConstants.HISTORY_SPECIAL_REQUESTS: {
				loadSpecialRequests();
				break;
			}
			case PageHistoryConstants.HISTORY_SEAT_MAP_SELECTION: {
				loadFlightSeatMapForBooking();
				break;
			}
			case PageHistoryConstants.HISTORY_PAYMENT: {
				loadPaymentInformation();
				break;
			}
			case PageHistoryConstants.HISTORY_PAYMENT_SUMMARY: {
				loadPaymentConfirmation();
				break;
			}
			case PageHistoryConstants.HISTORY_BALANCE_PAYMENT: {
			    loadBalancePayment();
			    break;
			}
			case PageHistoryConstants.HISTORY_BALANCE_PAYMENT_SUMMARY: {
			    loadBalancePaymentConfirmation();
			    break;
			}
			case PageHistoryConstants.HISTORY_ORDER_CONFIRMATION: {
				if(storageData) {
					loadBooking(storageData.bookingId);
				}
				else {
					loadBooking('');
				}
				break;
			}
			case PageHistoryConstants.HISTORY_CRUISE_SAILING_SEARCH_RESULTS : { 
				loadCruiseResultsOrLandingPage();
				break;
			}
			case PageHistoryConstants.HISTORY_CRUISE_PASSENGER_INFO : {
				reLoadCruisePassengerDetailPage();
				break;
			}
			case PageHistoryConstants.HISTORY_CRUISE_CATEGORY_RESULTS : {
				reLoadCruiseCategoryResults();
				break;
			}
			case PageHistoryConstants.HISTORY_CRUISE_CABIN_RESULTS : {
				if( storageData && ( storageData.cruiseCategoryItemUid ) ) {
					reLoadCruiseCabinResults( storageData.cruiseCategoryItemUid );
				} else {
					reLoadCruiseCabinResults();
				}
				break;
			}
			case PageHistoryConstants.HISTORY_CRUISE_PASSENGER_DETAILS : {
				reLoadCruisePassengerDetails();
				break;
			}
			case PageHistoryConstants.HISTORY_CRUISE_SPECIAL_REQUESTS : {
				reLoadCruiseSpecialRequests();
				break;
			}
			case PageHistoryConstants.HISTORY_CRUISE_BOOKING_RECAP : {
				loadBookingRecapPage();
				break;
			}
			case PageHistoryConstants.HISTORY_CRUISE_BOOKING_CONFIRMATION : {
				if(storageData) {
					loadBooking(storageData.bookingId);
				}
				else {
					loadBooking('');
				}
				break;
			}
			case PageHistoryConstants.HISTORY_CRUISE_PRE_POST_SEARCH : {
				reLoadCruisePrePostSearch();
				break;
			}
			case PageHistoryConstants.HISTORY_CRUISE_PRE_POST_FLIGHT_RESULTS : {
				reLoadCruisePrePostSearch();
				break;
			}
			case PageHistoryConstants.HISTORY_CRUISE_PRE_HOTEL_RESULTS : {
				reLoadCruisePrePostSearch();
				break;
			}
			case PageHistoryConstants.HISTORY_CRUISE_POST_HOTEL_RESULTS : {
				reLoadCruisePrePostSearch();
				break;
			}
			case PageHistoryConstants.HISTORY_CRUISE_PRE_POST_TRANSFER_RESULTS : {
				reLoadCruisePrePostSearch();
				break;
			}
			case PageHistoryConstants.HISTORY_SEARCH_RESULT_CAR_AGENCY : {
				performCarAgencySearchAgain();
				break;
			}
			case PageHistoryConstants.HISTORY_SEARCH_RESULT_CAR_AGENCY_MATRIX :{
				if( storageData && !( storageData.isAirport ) ) {
					performCarSearchAndLoadCarMatrix();
				} else {
					loadCarMatrixResults();
				}
				break;
			}
			case PageHistoryConstants.HISTORY_SEARCH_RESULT_CAR_EQUIPMENT : {
				loadCarEquipmentResults();
				break;
			}
			case PageHistoryConstants.HISTORY_FINALIZE_CAR_BOOKING : {
				loadFinalizeCarBookingDetails();
				break;
			}
			case PageHistoryConstants.HISTORY_CAR_BOOKING_RECAP : {
				loadCarBookingRecapPage();
				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 displayTermsConditionsFromDisplayString(displayString) {
	var bookingType;
	var destination;
	var cruiseLineCode;
	
	if(displayString) {
		var stringTokens = displayString.split("_");
		if(stringTokens) {
			if(stringTokens.length > 0) {
				bookingType = stringTokens[0];
				if(bookingType) {
					if(bookingType == "All") {
						bookingType = "0";
					}
					else if(bookingType == "Land") {
						bookingType = "1";						
					}
					else if(bookingTyep == "Cruise") {
						bookingType = "2";
					}
					else if(bookingType == "SuperPNR") {
						bookingType = "3";
					}
				}
				
				if(stringTokens.length > 1) {
					destination = stringTokens[1];
					if(destination && destination == "General") {
						destination = null;
					}
					
					if(stringTokens.length > 2) {
						cruiseLineCode = stringTokens[2];
						if(cruiseLinCode && cruiseLineCode == "General") {
							cruiseLineCode = null;
						}
					}
				}
			}
		}
		
		var queryString = "tcc=1";
		queryString += "&bookingType=" + bookingType;
		
		if(destination) {
			queryString += "&destination=" + destination;
		}
		
		if(cruiseLineCode) {
			queryString += "&cruiseLineCode=" + cruiseLineCode;
		}
		
		makeAjaxCall( 'termsAndConditionsContent.act', queryString, null, 'termsConditionsDiv', 'callbackDisplayTermsConditionsFromDisplayString', null, null  );		
	}	
}

function callbackDisplayTermsConditionsFromDisplayString() {
}

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";
}

function proceedToCruiseMemberLogin() {
	if (!isEmpty(_cruisePackageId)) {
		var trackingText = "/cr/booking/bookingPackage/memberLogin/" + _cruisePackageId + _departureDate;
		trackPageView(trackingText);
	}
	else {
		var trackingText = "/cr/booking/bookingWidget/memberLogin/" + _destinationName + "/" + _cruiseLineName + "/" + _shipName + "/" + _departureDate;
		trackPageView(trackingText);
	}

	window.location.href = _secureContextRoot + _webLoc + "/?h=5&checkMemberInactivity=true&uid=" + UID();
}

function loadSurveyLogin()
{
	var queryString = "md=14&uid=" + UID();
	makeAjaxCall( 'membershipDetail.act', queryString, null, 'rightContent', 'callbackLoadSurveyLogin', '/gi/memberInfo/BookDetailLogin');
	//makeAjaxCall(mainContentUrl, mainContentUrlQueryString, null, 'mainContent', 'callbackLoadMainContent', trackingText);
}

function callbackLoadSurveyLogin()
{
	document.title = "Costco Travel";	
	scrollWindowTop("scrollablePageContent");
}


/*
 * Keep the following as the last entry in this file. Add all functions above
 * this comment
 */

window.onload = windowOnLoad;

//*****************************************************************************
// Do not remove this notice.
//
// Copyright 2000-2004 by Mike Hall.
// See http://www.brainjar.com for terms of use.
//*****************************************************************************
//----------------------------------------------------------------------------
// Code for handling the menu bar and active button.
//----------------------------------------------------------------------------

var _activeButton = null;
var _activeItem = null;

var SUBMENU_DISPLAY_LAG = 120;

function buttonClick(event, menuId) {
  var button;
  // Get the target button element.

  if (isIE())
    button = window.event.srcElement;
  else
    button = event.currentTarget;
  
  addTouchEndListener();
  // Blur focus from the link to remove that annoying outline.
  button.blur();

  // Associate the named menu to this button if not already done.
  // Additionally, initialize menu display.
  if (button.menu == null) {
    button.menu = document.getElementById(menuId);
    if (button.menu && button.menu.isInitialized == null)
      menuInit(button.menu);
  }

  // [MODIFIED] Added for activate/deactivate on mouseover.
  // Set mouseout event handler for the button, if not already done.
  if (button.onmouseout == null)
    button.onmouseout = buttonOrMenuMouseout;

  // Exit if this button is the currently active one.
  if (button == _activeButton)
    return false;

  // [END MODIFIED]
  // Reset the currently active button, if any.
  if (_activeButton != null)
    resetButton(_activeButton);

  // Activate this button, unless it was the currently active one.
  if (button != _activeButton) {
    depressButton(button);
    _activeButton = button;
  }
  else
    _activeButton = null;
  return false;
}

function buttonMouseover(event, menuId) {
  // [MODIFIED] Added for activate/deactivate on mouseover.
  // Activates this button's menu if no other is currently active.
  if (_activeButton == null) {
    buttonClick(event, menuId);
    return;
  }
  
  // If any other button menu is active, make this one active instead.
  //if (_activeButton != null && _activeButton != button)
    buttonClick(event, menuId);
}

function depressButton(button) {
  var x, y;

  // [MODIFIED] Added for activate/deactivate on mouseover.
  // Set mouseout event handler for the button, if not already done.
  if (button.onmouseout == null)
    button.onmouseout = buttonOrMenuMouseout;
  if (button.menu && button.menu.onmouseout == null)
    button.menu.onmouseout = buttonOrMenuMouseout;

  // [END MODIFIED]
  // Position the associated drop down menu under the button and
  // show it.
  x = getPageOffsetLeft(button);
  y = getPageOffsetTop(button) + button.offsetHeight;

  // For IE, adjust position.
  if (isIE()) {
    x += button.offsetParent.clientLeft;
    y += button.offsetParent.clientTop;
  }

  // Update the button's style class to make it look like it's
  // depressed.
  if(button.menu) {
	  modifyClassName (button, "+menuButtonActive");
	  button.menu.style.left = x + "px";
	  button.menu.style.top  = y + "px";
	  button.menu.style.visibility = "visible";
	
	  // For IE; size, position and show the menu's IFRAME as well.
	  if (button.menu.iframeEl != null) {
	    button.menu.iframeEl.style.left = button.menu.style.left;
	    button.menu.iframeEl.style.top  = button.menu.style.top;
	    button.menu.iframeEl.style.width  = toPixels(button.menu.offsetWidth);
	    button.menu.iframeEl.style.height = toPixels(button.menu.offsetHeight);
	    button.menu.iframeEl.style.display = "";
	  }
  } else {
	  modifyClassName(button, "+menuButtonHover");
  }
}

function resetButton(button) {
  // Restore the button's style class.
  modifyClassName(button, "-menuButtonActive -menuButtonHover");

  // Hide the button's menu, first closing any sub menus.
  if (button.menu != null) {
    closeSubMenu(button.menu);
    button.menu.style.visibility = "hidden";

    // For IE, hide menu's IFRAME as well.
    if (button.menu.iframeEl != null)
      button.menu.iframeEl.style.display = "none";
  }
}

//----------------------------------------------------------------------------
// Code to handle the menus and sub menus.
//----------------------------------------------------------------------------

function menuMouseover(event) {
  var menu;

  // Find the target menu element.
  if (isIE())
    menu = getContainerWith(window.event.srcElement, "DIV", "menu");
  else
    menu = event.currentTarget;

  // Close any active sub menu.
  //if (menu.activeItem != null)
  //  closeSubMenu(menu);
}

function menuItemMouseover(event, menuId) {
  var item;

  // Find the target item element and its parent menu element.
  if (isIE())
    item = getContainerWith(window.event.srcElement, "A", "menuItem");
  else
    item = event.currentTarget;
  
  item.menuId = menuId;
  item.onmousemove = menuItemMousemove;
  item.onmouseout = menuItemMouseout;
  _activeItem = item;
  
  var f = function() {
	  if(item == _activeItem) {
		  item.canShowSubMenu = true;
		  fireEvent(item, "mousemove");
	  }	  
  };
  //alert(item.menuId);
  item.timeoutId = setTimeout(f, SUBMENU_DISPLAY_LAG);
}

function menuItemMousemove(event) {
   var item, menu, x, y;

  // Find the target item element and its parent menu element.
  if (isIE())
    item = getContainerWith(window.event.srcElement, "A", "menuItem");
  else
    item = event.currentTarget;
  
  if(item.canShowSubMenu) {	  
	  menu = getContainerWith(item, "DIV", "menu");
	  if(menu.activeItem != item) {
		  // Close any active sub menu mark this item as active.
		  if (menu.activeItem != null) {
			  closeSubMenu(menu);
		  }
		  if (item.menuId != null) {
			  menu.activeItem = item;
		  
		  // Highlight the item element.
		  item.className += " menuItemHighlight";
		  
	
		  // Initialize the sub menu, if not already done.
		  showSubMenu(item, item.menuId);
	
		  // Stop the event from bubbling.
		  if (isIE())
		    window.event.cancelBubble = true;
		  else
		    event.stopPropagation();
		  }else {
			  menu.activeItem = null;		  
		  }
	  }
  }
}

function menuItemMouseout(event) {
   var item;
	  // Find the target item element and its parent menu element.
   
   if (isIE()) {	
    item = getContainerWith(window.event.srcElement, "A", "menuItem");
    //alert(item.menuId);   
   }
   else
    item = event.currentTarget;
   
   clearTimeout(item.timeoutId);
   item.canShowSubMenu = false;
   _activeItem = null;
}

function showSubMenu(item, menuId) {
	if (item.subMenu == null) {
	    item.subMenu = document.getElementById(menuId);
	    if (item.subMenu.isInitialized == null)
	      menuInit(item.subMenu);
	  }

	  // [MODIFIED] Added for activate/deactivate on mouseover.
	  // Set mouseout event handler for the sub menu, if not already done.
	  if (item.subMenu.onmouseout == null)
	    item.subMenu.onmouseout = buttonOrMenuMouseout;

	  // [END MODIFIED]
	  // Get position for submenu based on the menu item.
	  x = getPageOffsetLeft(item) + item.offsetWidth;
	  y = getPageOffsetTop(item);

	  // Adjust position to fit in view.
	  var maxX, maxY;
	  if (isIE()) {
	    maxX = Math.max(document.documentElement.scrollLeft, document.body.scrollLeft) +
	      (document.documentElement.clientWidth != 0 ? document.documentElement.clientWidth : document.body.clientWidth);
	    maxY = Math.max(document.documentElement.scrollTop, document.body.scrollTop) +
	      (document.documentElement.clientHeight != 0 ? document.documentElement.clientHeight : document.body.clientHeight);
	  }else if (isOpera()) {
	    maxX = document.documentElement.scrollLeft + window.innerWidth;
	    maxY = document.documentElement.scrollTop  + window.innerHeight;
	  }else if (isNetscape()) {
	    maxX = window.scrollX + window.innerWidth;
	    maxY = window.scrollY + window.innerHeight;
	  }
	  
	  maxX -= item.subMenu.offsetWidth;
	  maxY -= item.subMenu.offsetHeight;

	  if (x > maxX)
	    x = Math.max(0, x - item.offsetWidth - item.subMenu.offsetWidth
	      + (menu.offsetWidth - item.offsetWidth));
	  y = Math.max(0, Math.min(y, maxY));

	  // Position and show the sub menu.
	  item.subMenu.style.left       = toPixels(x);
	  item.subMenu.style.top        = toPixels(y);
	  item.subMenu.style.visibility = "visible";

	  // For IE; size, position and display the menu's IFRAME as well.
	  if (item.subMenu.iframeEl != null) {
	    item.subMenu.iframeEl.style.left    = item.subMenu.style.left;
	    item.subMenu.iframeEl.style.top     = item.subMenu.style.top;
	    item.subMenu.iframeEl.style.width   = toPixels(item.subMenu.offsetWidth);
	    item.subMenu.iframeEl.style.height  = toPixels(item.subMenu.offsetHeight);
	    item.subMenu.iframeEl.style.display = "";
	  }
}

function closeSubMenu(menu) {	
  if (menu == null || menu.activeItem == null)
    return true;

 
  // Recursively close any sub menus.
  if (menu.activeItem.subMenu != null) {
    if(closeSubMenu(menu.activeItem.subMenu)) {
    	
	    menu.activeItem.subMenu.style.visibility = "hidden";
	    // For IE, hide the sub menu's IFRAME as well.
	    if (menu.activeItem.subMenu.iframeEl != null)
	      menu.activeItem.subMenu.iframeEl.style.display = "none";
	    menu.activeItem.subMenu = null;
    }
  }

  // Deactivate the active menu item.
  removeClassName(menu.activeItem, "menuItemHighlight");
  menu.activeItem = null;
  
  return true;
}

// [MODIFIED] Added for activate/deactivate on mouseover. Handler for mouseout
// event on buttons and menus.

function buttonOrMenuMouseout(event) {
  var el;

  // If there is no active button, exit.
  if (_activeButton == null)
    return;

  // Find the element the mouse is moving to.
  if (isIE())
    el = window.event.toElement;
  else if (event.relatedTarget != null)
      el = (event.relatedTarget.tagName ? event.relatedTarget : event.relatedTarget.parentNode);

  // If the element is not part of a menu, reset the active button.
  if (getContainerWith(el, "DIV", "menu") == null) {
    resetButton(_activeButton);
    _activeButton = null;
  }
}

// [END MODIFIED]

//----------------------------------------------------------------------------
// Code to initialize menus.
//----------------------------------------------------------------------------

function menuInit(menu) {
  var itemList, spanList;
  var textEl, arrowEl;
  var itemWidth;
  var w, dw;
  var i, j;

  // For IE, replace arrow characters.
  if (isIE()) {
    menu.style.lineHeight = "2.5ex";
    spanList = menu.getElementsByTagName("SPAN");
    for (i = 0; i < spanList.length; i++)
      if (hasClassName(spanList[i], "menuItemArrow")) {
        spanList[i].style.fontFamily = "Webdings";
        spanList[i].firstChild.nodeValue = "4";
      }
  }

  // Find the width of a menu item.
  itemList = menu.getElementsByTagName("A");
  if (itemList.length > 0)
    itemWidth = itemList[0].offsetWidth;
  else
    return;

  // For items with arrows, add padding to item text to make the
  // arrows flush right.
  for (i = 0; i < itemList.length; i++) {
    spanList = itemList[i].getElementsByTagName("SPAN");
    textEl  = null;
    arrowEl = null;
    for (j = 0; j < spanList.length; j++) {
      if (hasClassName(spanList[j], "menuItemText"))
        textEl = spanList[j];
      if (hasClassName(spanList[j], "menuItemArrow"))
        arrowEl = spanList[j];
    }
    if (textEl != null && arrowEl != null) {
      textEl.style.paddingRight = (itemWidth 
        - (textEl.offsetWidth + arrowEl.offsetWidth)) + "px";
      // For Opera, remove the negative right margin to fix a display bug.
      if (browser.isOP)
        arrowEl.style.marginRight = "0px";
    }
  }

  // Fix IE hover problem by setting an explicit width on first item of
  // the menu.
  if (isIE()) {
    w = itemList[0].offsetWidth;
    itemList[0].style.width = toPixels(w);
    dw = itemList[0].offsetWidth - w;
    w -= dw;
    itemList[0].style.width = toPixels(w);
  }

  // Fix the IE display problem (SELECT elements and other windowed controls
  // overlaying the menu) by adding an IFRAME under the menu.

  if (isIE7Under()) {
    var iframeEl = document.createElement("IFRAME");
    iframeEl.frameBorder = 0;
    iframeEl.src = "javascript:false;";
    iframeEl.style.display = "none";
    iframeEl.style.position = "absolute";
    iframeEl.style.filter = "progid:DXImageTransform.Microsoft.Alpha(style=0,opacity=0)";
    menu.iframeEl = menu.parentNode.insertBefore(iframeEl, menu);
  }

  // Mark menu as initialized.
  menu.isInitialized = true;
}

//----------------------------------------------------------------------------
// General utility functions.
//----------------------------------------------------------------------------

function getContainerWith(node, tagName, className) {

  // Starting with the given node, find the nearest containing element
  // with the specified tag name and style class.
  while (node != null) {
    if (node.tagName != null && node.tagName == tagName &&
        hasClassName(node, className))
      return node;
    node = node.parentNode;
  }
  return node;
}

function removeClassName(el, name) {
  var i, curList, newList;
  if (el.className == null)
    return;

  // Remove the given class name from the element's className property.
  newList = new Array();
  curList = el.className.split(" ");
  for (i = 0; i < curList.length; i++)
    if (curList[i] != name)
      newList.push(curList[i]);
  el.className = newList.join(" ");
}

function getPageOffsetLeft(el) {
	return getPosRelativeToContainer(el, "pageContent").x;
}

function getPageOffsetTop(el) {
	return getPosRelativeToContainer(el, "pageContent").y;
}

function addTouchEndListener() {
	if(!document.touchendListenerPresent && document.addEventListener) {
		document.addEventListener("touchend", function(){		
			if(!getContainerWith(event.srcElement, 'DIV', 'menuBar') && !getContainerWith(event.srcElement, 'DIV', 'menu')) {	
				if(_activeButton) {
					var evt = document.createEvent("MouseEvents");
					evt.initMouseEvent(
					    "mouseout",
					    true,
					    true,
					    this,
					    0,
					    0,
					    0,
					    0,
					    0,
					    false,
					    false,
					    false,
					    false,
					    0,
					    null
					);
					
					var a = _activeButton;
					var p = a.parentNode;
					var nextSibling = a.nextSibling;
					
					_activeButton.dispatchEvent(evt);
					removeElement(a);	
					
					var div = document.createElement('DIV');
					div.className = a.className;
	
					var childNodes = a.childNodes;
					for(var i=0; i< childNodes.length; i++) {
						div.appendChild(childNodes[i]);
					}
					div.onmouseover = a.onmouseover;
					div.onclick = a.onclick;
					p.insertBefore(div, nextSibling);
				};
			}
		}, false);
		document.touchendListenerPresent = true;
	}
	
}/* Pre-Loading the Ad Images */
function preloadAdImages() {
	for(var index = 0; index < numberOfAdImages; ++index) {
		var adImage = new Image();				
		preloadImage(adImage, _webLoc + '/shared/images/core/bannersAndAds/waitingAd_' + index + '.jpg');
		
		adImages[index] = adImage;
	}
}

preloadAdImages();

/* Pre-Loading the Searching Image */
var searchingImage = new Image();
preloadImage(searchingImage, _webLoc + '/shared/images/core/searching.gif');

/* Pre-Loading the Close Image */
var closeImage = new Image();
preloadImage(closeImage, _webLoc + '/shared/images/core/buttons/close.gif');

/* Pre-Loading the "No Image Available" Image */
var noImage = new Image();
preloadImage(noImage, _webLoc + '/shared/images/core/icons/noImageAvailable.gif');
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;
	var noHotelsAvailable = isEmpty( markedHotelInfos ) && isEmpty( 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/>";
		     			}
		     			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;
		document.getElementById( "noHotelsAvailableDiv" ).style.display = noHotelsAvailable ? "BLOCK" : "NONE";
	}
}
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, offerDivId) {
	var displayEndIndex = displayStartIndex + numberOfOffersToDisplay - 1;
	if(!offerDivId) {
		offerDivId = "offerDiv";
	}
	
	//First, hide all offers
	for(var offerIndex = 1; offerIndex <= totalOffers; ++offerIndex) {
		var offerDiv = document.getElementById(offerDivId + "_" + offerIndex);
		
		if(offerDiv) {
			offerDiv.style.display = "none";
		}
	}
	
	//Display offers on the current page
	var displayIndex = displayStartIndex;
	for(; displayIndex <= displayEndIndex; ++displayIndex) {
		var offerDiv = document.getElementById(offerDivId + "_" + (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 displayOffersForPage( pagination, pageIndex ) {
	var displayStartIndex = (pageIndex - 1) * numberOfOffersToDisplay;
	displayOffers(displayStartIndex, numberOfOffersToDisplay, pagination._totalOffers, pagination._offerDivId);
	pagination._selectedPage = pageIndex;
	pagination.loadPaginationDivs ();
}

function updatePackageLandingPageInfo( cruiseSailingItemUid, packageStartAtPrice, isCruiseTour, isSailingResultsAvailable, displayItinerary, packageId, itineraryName, destination, cruiseLineName, shipName, departureDate ) {
	if( !isNull( document.getElementById( "packageStartAtPriceSpan" ) ) && !isNull( document.getElementById( "specialInstructionsSpan" ) ) ) {
		if( ( parseFloat( packageStartAtPrice ) > 0.0 ) ) {
			document.getElementById( "specialInstructionsSpan" ).style.display = "block";
			packageStartAtPrice = formatCurrency( parseFloat( packageStartAtPrice ).toFixed( 2 ) );
			document.getElementById( "packageStartAtPriceSpan" ).innerHTML = packageStartAtPrice.substring( 0, packageStartAtPrice.indexOf( "." ) ) + "<sup>*</sup>";
		} else {
			document.getElementById( "specialInstructionsSpan" ).style.display = "none";
		}
	}
	if( !isNull( document.getElementById( "cruisePackageLeadinPricesDiv" ) ) ) {
		if( isSailingResultsAvailable ) {
			document.getElementById( "cruisePackageLeadinPricesDiv" ).style.display = "block";
		} else {
			document.getElementById( "cruisePackageLeadinPricesDiv" ).style.display = "none";
		}
	}
	if( !isNull( document.getElementById( "divCruiseTourHighlights" ) ) ) {
		if( isCruiseTour ) {
			document.getElementById( "divCruiseTourHighlights" ).style.display = "block";
			registerListener( document.getElementById( "divCruiseTourHighlights" ), "click", function () { loadCruiseTourHighlights( cruiseSailingItemUid, itineraryName ); } );
		} else {
			document.getElementById( "divCruiseTourHighlights" ).style.display = "none";
		}
	}
	if( !isNull( document.getElementById( "divCruiseItinerary" ) ) ) {
		if(isCruiseTour) {
			registerListener( document.getElementById( "divCruiseItinerary" ), "click", function () { document.getElementById( 'cruiseTabContent' ).innerHTML = "<div class='w682 tac p10'>Loading...</div>"; loadCruiseItinerary( cruiseSailingItemUid, false, packageId, itineraryName ); } );
		}
		else {
			registerListener( document.getElementById( "divCruiseItinerary" ), "click", function () { document.getElementById( 'cruiseTabContent' ).innerHTML = "<div class='w682 tac p10'>Loading...</div>"; loadCruiseItinerary( cruiseSailingItemUid, false, packageId, destination, cruiseLineName, shipName, departureDate ); } );
		}

		if(displayItinerary) {
			document.getElementById( 'cruiseTabContent' ).innerHTML = "<div class='w682 tac p10'>Loading...</div>"; 
			if(isCruiseTour) {
				loadCruiseItinerary( cruiseSailingItemUid, false, packageId, itineraryName );
			}
			else {
				loadCruiseItinerary( cruiseSailingItemUid, false, packageId, destination, cruiseLineName, shipName, departureDate );
			}
		}
	}
}function Pagination() {
	this._pageCount = 0;
	this._selectedPage = 0;
	this._numberOfPagesToDisaplay = 10;
	this._startPage = 1;
	this._endPage = 0;
	this._currentPage = 1;
	this._previousPage = 1;	
	this._paginationDivId = '';
	this._pageLoadFunctionName = '';
}

Pagination.prototype.initialize = function() {
	if( this._selectedPage > 1 ){
		this.setPageRange ( this._selectedPage );
		this.updatePageSelection ( this._selectedPage );
	}else if( this._pageCount > 0 ){
		this.loadPaginationDivs(); 
	}
}

/* Load the pagination div after perform the cruise search. */
Pagination.prototype.loadPaginationDivs = function() {
	//update page selection	when
	//moving to right side , which means increasing page number
	//moving to left side , which means decreasing page number
	if ( this._selectedPage != this._startPage && this._selectedPage != this._endPage ) {
		this.updatePageSelection ( this._selectedPage );
	}

	//create page numbers when 
	//selected page is first page displayed and has more pages downwards to display
	if ( this._selectedPage == this._startPage ) {
		this.setPageRange ( ( this._selectedPage - this._numberOfPagesToDisaplay  + 1) > 0 ? ( this._selectedPage - this._numberOfPagesToDisaplay + 1) : 1 );
		this.updatePageSelection ( this._selectedPage );
		return;
	}
	//selected page is last page displayed and has more pages upwards to display
	if ( this._selectedPage == this._endPage ) {
		this.setPageRange ( this._selectedPage );
		this.updatePageSelection ( this._selectedPage );
	}
}

/* On click of next link from the cruise search results page selection changes to the next page.*/
Pagination.prototype.nextPage = function() {
	this._selectedPage = ( parseInt ( this._currentPage ) + parseInt ( 1 ) ) <= this._pageCount ? ( parseInt ( this._currentPage ) + parseInt ( 1 ) )
			: this._pageCount;
	if ( this._selectedPage > this._endPage ) {
		this._endPage = this._selectedPage;
	}
	
	var callbackFunction = this._pageLoadFunctionName;
	if(callbackFunction && callbackFunction != "") {
		callbackFunction = callbackFunction + "(this, " + this._selectedPage + ")";
		eval(callbackFunction);
	}
}

/* On click of previous link from the cruise search results page selection changes to the previous page.*/
Pagination.prototype.previousPage = function() {
	_isNextPrevious = true;
	this._selectedPage = ( this._currentPage - 1 ) > 1 ? ( this._currentPage - 1 ) : 1;
	if ( this._selectedPage < this._startPage ) {
		this._startPage = this._selectedPage;
	}

	var callbackFunction = this._pageLoadFunctionName;
	if(callbackFunction && callbackFunction != "") {
		callbackFunction = callbackFunction + "(this, " + this._selectedPage + ")";
		eval(callbackFunction);
	}
}

/* Sets the start and end pages to the showing pagination of the cruise search results page*/
Pagination.prototype.setPageRange = function( startPage ) {
	this._startPage = startPage;
	var temp = parseInt ( startPage , 10 ) + parseInt ( this._numberOfPagesToDisaplay - 1, 10 );
	this._endPage = temp < ( this._pageCount ) ? temp : this._pageCount;
	
	//When the displayed end page is equal to total available pages make sure we are displaying 
	//number of pages equal to number of pages to be displayed 
	if(((this._endPage - this._startPage) < (this._numberOfPagesToDisaplay - 1)) && (this._endPage == this._pageCount)){	
		this._startPage = this._pageCount - this._numberOfPagesToDisaplay + 1;
	}
	this._startPage = ( this._startPage < 1 ) ? 1 : this._startPage;
	this.createPaginationDiv ( this._startPage , this._endPage );
}

/* Creates all pagination numbers */
Pagination.prototype.createPaginationDiv = function( startPage, endPage ) {
	var paginationDiv = document.getElementById ( this._paginationDivId );
	if(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.pagination = this;
		anchorPrevious.onclick = function () {
			this.pagination.previousPage ();
		};
		anchorPrevious.appendChild ( document.createTextNode ( "Previous" ) );
		anchorPrevious.id = this._paginationDivId + '_Previous';
		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++ ) {
			this.createPage ( pageIndex, 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.pagination = this;
		anchorNext.onclick = function () {
			this.pagination.nextPage ();
		};
		anchorNext.appendChild ( document.createTextNode ( "Next" ) );
		anchorNext.id = this._paginationDivId + '_Next';
		paginationDiv.appendChild ( anchorNext );
		paginationDiv.style.display = "";
	}
}

/* Creates particular page number from the pagination div. */
Pagination.prototype.createPage = function( pageIndex, paginationDiv ) {
	var pageNumberDiv = document.createElement ( 'DIV' );
	pageNumberDiv.style.display = 'inline';
	var pageNumberAnchor = document.createElement ( 'A' );
	pageNumberAnchor.className = 'pagenos';
	pageNumberAnchor.href = "javascript:;";
	pageNumberAnchor.pagination = this;
	
	var callbackFunction = this._pageLoadFunctionName;
	if(callbackFunction && callbackFunction != "") {
		callbackFunction = callbackFunction + "(this.pagination," + pageIndex + ")";
		pageNumberAnchor.onclick = new Function ( callbackFunction );
	}		

	pageNumberAnchor.appendChild ( document.createTextNode ( pageIndex ) );
	pageNumberAnchor.id = this._paginationDivId + "_Anchor_" + pageIndex;
	
	pageNumberDiv.appendChild ( pageNumberAnchor );
	paginationDiv.appendChild ( pageNumberDiv );
}

/* Updates the selection from the pagination div. */
Pagination.prototype.updatePageSelection = function( selectedPage ) {
	this._previousPage = this._currentPage;
	this._currentPage = selectedPage;
	
	// de-select the previous page
	var pageNumberAnchor = document.getElementById ( this._paginationDivId + "_Anchor_" + this._previousPage );
	if ( pageNumberAnchor ) {
		pageNumberAnchor.className = "pagenos";
		pageNumberAnchor.href = "javascript:;";
		pageNumberAnchor.pagination = this;
		
		var callbackFunction = this._pageLoadFunctionName;
		if(callbackFunction && callbackFunction != "") {
			callbackFunction = callbackFunction + "(this.pagination," + this._previousPage + ")";
			pageNumberAnchor.onclick = new Function ( callbackFunction );
		}		
	}

	// select the current page	
	pageNumberAnchor = document.getElementById ( this._paginationDivId + "_Anchor_" + this._currentPage );
	if ( pageNumberAnchor ) {
		pageNumberAnchor.className = "pagenos-sel";
		pageNumberAnchor.onclick = "";
		pageNumberAnchor.removeAttribute ( "href" );
	}

	// If current page > 1 then show the previous page
	if ( this._currentPage == 1 ) {
		//Hide Previous link
		document.getElementById ( this._paginationDivId + "_Previous" ).style.display = 'none';
	} else {
		//Show Previous link
		document.getElementById ( this._paginationDivId + "_Previous" ).style.display = 'inline';
	}
	
	// Handling next link
	if ( this._currentPage == this._pageCount ) {
		//Hide Next link
		document.getElementById ( this._paginationDivId + "_Next" ).style.display = 'none';
	} else {
		//Show Next link
		document.getElementById ( this._paginationDivId + "_Next" ).style.display = 'inline';
	}
}


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(!showMessage(this.messageType, this.messageCode, this.message, 'dataContent')){
		loadSweepstakesSuccessPopup();
	}
	return true;	
}

function loadSweepstakesSuccessPopup() {
	sweepstakesSuccessPopupDiv = document.getElementById("sweepstakesSuccessPopupDiv");
	if(!sweepstakesSuccessPopupDiv) {
		sweepstakesSuccessPopupDiv = createPopupDiv( "sweepstakesSuccessPopupDiv", 0, 0, 410, -1, 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('Hawaii', 'Europe', 'Fiji', 'Tahiti', 'Cook Islands');
var DEFAULT_MULTI_DESTINATIONS_CHECKED = new Array('Europe', 'Tahiti', 'Cook Islands');

function showPackagesWithLeadInPrice( pageNumber ) {
	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-region 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-region 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");
	scrollWindowTop("scrollablePageContent");
}
/*
 * Sort Package results based LIP and package display type.
 */
function sortPackageResults( firstPackageInfo, secondPackageInfo ) {
	if( firstPackageInfo.recommendedPackage && !secondPackageInfo.recommendedPackage ) {
		return -1;
	} else if( !firstPackageInfo.recommendedPackage && secondPackageInfo.recommendedPackage ) {
		return 1;
	} else 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 ) {
	var isRecommendedPackage = packageInfo.recommendedPackage;
	var isIncludeFlightIncludedRates = packageInfo.isIncludeFlightIncludedRates;
	
	// 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;
	var ticket = searchResult.ticket;
	
	_packageId = packageInfo.packageId;
	_destinationCode = searchResult.destination;
	_regionCode = searchResult.region;

	var itineraryComponentTitlePrintDiv = document.createElement( 'DIV' );
	itineraryComponentTitlePrintDiv.className = "itineraryComponentTitleBgPrint";
	
	var itineraryComponentTitlePrintImage = document.createElement( 'IMG' );
	itineraryComponentTitlePrintImage.src = _webLoc + "/shared/images/core/backgrounds/itineraryCompTitleBg-big.gif";
	
	itineraryComponentTitlePrintDiv.appendChild( itineraryComponentTitlePrintImage );

	//Itinerary Component Div
	var itineraryComponentTitleDiv = document.createElement( 'DIV' );
	if( isRecommendedPackage ) {
		itineraryComponentTitleDiv.className = "costcoRecommendsComponentTitleBg";
	} else {
		itineraryComponentTitleDiv.className = "itineraryComponentTitleBg";
	}

	var itineraryComponentIconsDiv = document.createElement( 'DIV' );
	itineraryComponentIconsDiv.className = "itineraryComponentTitleIconContainer";

	var flightComponentIconDiv = null;
	var flightRecommendedComponentIconDiv = null;
	var hotelComponentIconDiv = null; 
	var carComponentIconDiv = null;
	var sightSeeingComponentIconDiv = null;
	var ticketComponentIconDiv = 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 (flight.length == 0 && isIncludeFlightIncludedRates && !isFlightIncluded){
		flightRecommendedComponentIconDiv = document.createElement( 'DIV' );
		flightRecommendedComponentIconDiv.className = "itineraryComponentTitleIcon mr-10";

		var flightIconImage = document.createElement( 'IMG' );
		flightIconImage.src = _webLoc + "/shared/images/core/icons/flightRecommendedIcon.gif";
		flightIconImage.alt = "Flight Recommended Icon";

		flightRecommendedComponentIconDiv.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 ticket present, create ticket icon.
	if( ticket.length > 0 ) {
		ticketComponentIconDiv = document.createElement( 'DIV' );
		ticketComponentIconDiv.className = "itineraryComponentTitleIcon mr-10";

		var ticketIcon = document.createElement( 'IMG' );
		ticketIcon.src = _webLoc + "/shared/images/core/icons/ticketsIcon.gif";
		ticketIcon.alt = "Sightseeing Icon";

		ticketComponentIconDiv.appendChild( ticketIcon );
	}

	if( flight.length > 0 ) {
		itineraryComponentIconsDiv.appendChild( flightComponentIconDiv );		 
	}
	if( hotel.length > 0 ) {
		itineraryComponentIconsDiv.appendChild( hotelComponentIconDiv );	
	}
	if( car.length > 0 ) {
		itineraryComponentIconsDiv.appendChild( carComponentIconDiv );	
	}
	if( greeting.length > 0 ) {
		itineraryComponentIconsDiv.appendChild( greetingComponentIconDiv );
	}
	if( transfer.length > 0 ) {
		itineraryComponentIconsDiv.appendChild( transferComponentIconDiv );
	}
	if( tour.length > 0 ) {
		itineraryComponentIconsDiv.appendChild( sightSeeingComponentIconDiv );	
	}
	if( ticket.length > 0 ) {
		itineraryComponentIconsDiv.appendChild( ticketComponentIconDiv );	
	}
	if (flight.length == 0 && isIncludeFlightIncludedRates && !isFlightIncluded){
		itineraryComponentIconsDiv.appendChild(flightRecommendedComponentIconDiv);
	}	
	
	if( isRecommendedPackage ) {
		var costcoRecommendedIconDiv = document.createElement( 'DIV' );
		costcoRecommendedIconDiv.className = "itineraryComponentTitleIcon mr-10";

		var costcoRecommendedIcon = document.createElement( 'IMG' );
		costcoRecommendedIcon.src = _webLoc + "/shared/images/core/icons/costcoRecommendedIcon.gif";
		costcoRecommendedIcon.alt = "Costco Recommended Icon";

		costcoRecommendedIconDiv.appendChild( costcoRecommendedIcon );
		itineraryComponentIconsDiv.appendChild( costcoRecommendedIconDiv );

		var costcoRecommendedTextDiv = document.createElement( 'DIV' );
		costcoRecommendedTextDiv.className = "fs12 fll pl10 pt15 b";
		costcoRecommendedTextDiv.appendChild( document.createTextNode( "Costco Travel Recommends " ) );

		var costcoRecommendedHelpLink = document.createElement( 'A' );
		costcoRecommendedHelpLink.href ="javascript:;";
		costcoRecommendedHelpLink.onclick = function() { loadRecommendedPackagePopup(); };
		var costcoRecommendedHelpIcon = document.createElement( 'IMG' );
		costcoRecommendedHelpIcon.src = _webLoc + "/shared/images/core/icons/help.gif";
		costcoRecommendedHelpIcon.alt = "Help Icon";
		costcoRecommendedHelpLink.appendChild( costcoRecommendedHelpIcon );
		costcoRecommendedTextDiv.appendChild( costcoRecommendedHelpLink );

		itineraryComponentIconsDiv.appendChild( costcoRecommendedTextDiv );
	}
	itineraryComponentTitleDiv.appendChild( itineraryComponentIconsDiv );

	//Package Price Div
	var packagePriceDiv = document.createElement( 'DIV' );
	if( isRecommendedPackage ) {
		packagePriceDiv.className = "costcoRecommendsComponentTitleRightBg";
	} else {
		packagePriceDiv.className = "";
	}
	var packagePriceInnerDiv = document.createElement( 'DIV' );
	if( isRecommendedPackage ) {
		packagePriceInnerDiv.className = "costcoRecommendsComponentTitleRight fs12";
	} else {
		packagePriceInnerDiv.className = "itineraryComponentTitleRight fs12";
	}
	var packagePriceSpan = document.createElement( 'SPAN' );
	packagePriceSpan.className = "fs10 nob";
	packagePriceSpan.appendChild( document.createTextNode( "Total Package Price " ) );
	packagePriceInnerDiv.appendChild( packagePriceSpan );
	if ( packageInfo.isRequiredFlightAvailable && packageInfo.isRequiredHotelAvailable ){
		packagePriceInnerDiv.appendChild( document.createTextNode( formatCurrency( parseFloat( packageInfo.leadInPrice ).toFixed( 2 ) ) ) );
	} else{
		packagePriceInnerDiv.appendChild( document.createTextNode( "N/A" ));
	}
	packagePriceDiv.appendChild( packagePriceInnerDiv );

	itineraryComponentTitleDiv.appendChild( packagePriceDiv );
	
	//itineraryComponent BR
	var itineraryComponentTitleBR = document.createElement( "BR" );
	itineraryComponentTitleBR.clear = "all";
	itineraryComponentTitleDiv.appendChild( itineraryComponentTitleBR );
	
	var packageResultDiv = document.createElement( "DIV" );
	if( isRecommendedPackage ) {
		packageResultDiv.className = "costcoRecommendsPackageResultBottomBg";
	} else {
		packageResultDiv.className = "bo07";
	}

	// Div for all component.
	var mainDiv = document.createElement( 'DIV' );
	if( isRecommendedPackage ) {
		mainDiv.className = "costcoRecommendsPackageResultRightBg";
	} else {
		mainDiv.className = "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 );

	var componentBlocks = new Array();
	if( hotel.length > 0 ) {
		componentBlocks[ componentBlocks.length ] = loadHotelResultDiv( hotel );
	}
	
	if( flight.length > 0 ) {
		componentBlocks[ componentBlocks.length ] = loadFlightResultDiv( flight[0], packageInfo );	
	}

	if( greeting.length > 0 ) {
		componentBlocks[ componentBlocks.length ] = loadTransferResultDiv( greeting[0], false );
	}
	
	if( car.length > 0 ) {
		componentBlocks[ componentBlocks.length ] = loadCarResultDiv( car[0] );
	}
	
	if( transfer.length > 0 ) {
		var transferSpan = document.createElement( "SPAN" );
		transferSpan.className = "b";
		transferSpan.appendChild( document.createTextNode( "Airport Transfer(s) Included." ) );
		componentBlocks[ componentBlocks.length ] = transferSpan;
	}
	
	if( tour.length > 0 ) {
		componentBlocks[ componentBlocks.length ] = loadTourResultDiv( tour );
	}

	if( ticket.length > 0 ) {
		componentBlocks[ componentBlocks.length ] = loadTicketResultsDiv( ticket );
	}

	var numberOfComponentBlocks = componentBlocks.length;
	for( var index = 0 ; index < numberOfComponentBlocks ; index++ ) {
		mainDiv.appendChild( componentBlocks[ index ] );
		if( index < ( numberOfComponentBlocks - 1 ) ) {
			var spacerImgDiv = document.createElement( 'DIV' );
			spacerImgDiv.className = "divider p05";
			var spacerImg = document.createElement( 'IMG' );
			spacerImg.src = _webLoc + "/shared/images/core/spacer.gif";
			spacerImg.alt = "";
			spacerImgDiv.appendChild( spacerImg );
			mainDiv.appendChild( spacerImgDiv );
		}
	}
	document.getElementById( "searchResults" ).appendChild( itineraryComponentTitlePrintDiv );	
	document.getElementById( "searchResults" ).appendChild( itineraryComponentTitleDiv  );
	if( isRecommendedPackage && !isEmpty( packageInfo.marketingVoice )) {
		var recommendedPackageDividerDiv = document.createElement( "DIV" );
		recommendedPackageDividerDiv.className = "divider mt05";
		var recommendedPackageDividerImage = document.createElement( "IMG" );
		recommendedPackageDividerImage.src = _webLoc + "/shared/images/core/spacer.gif";
		recommendedPackageDividerImage.alt = "";
		recommendedPackageDividerDiv.appendChild( recommendedPackageDividerImage );
		mainDiv.appendChild( recommendedPackageDividerDiv );
		
		var marketingVoiceDiv = document.createElement( "DIV" );
		marketingVoiceDiv.className = "p10";
		marketingVoiceDiv.appendChild( document.createTextNode( packageInfo.marketingVoice ) );
		mainDiv.appendChild( marketingVoiceDiv );
	}
	packageResultDiv.appendChild( mainDiv );
	document.getElementById( "searchResults" ).appendChild( packageResultDiv );
	
	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.
	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 = "87";

	packageImageDiv.appendChild( packageImage );

	//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 valt pl10";
	
	var packageNameSpan = document.createElement( 'SPAN' );
	packageNameSpan.className = "sup fs14 b";
	//Package Name( SignLine1 ) Text node.
	packageNameSpan.appendChild( document.createTextNode( decodeHTML( packageInfo.signLine1 ) ));
	packageDetailTd1.appendChild( packageNameSpan );
	
	var packageNameLinkBR1 = document.createElement( 'br' );
	packageDetailTd1.appendChild( packageNameLinkBR1 );
	
	/*commented as part of the ticket 2184(modified requirement)
	//Package Name( accommodationTypes ) Text node.
	packageDetailTd1.appendChild( document.createTextNode( decodeHTML( packageInfo.accommodationTypes ) ) );
	var packageNameLinkBR2 = document.createElement( 'br' );
	packageDetailTd1.appendChild( packageNameLinkBR2 );
	
	if ( packageInfo.contentAvailable ){
		//Offer Details Link.
		var offerDetailsLink = document.createElement( 'A' );
		offerDetailsLink.href ="javascript:;";
		offerDetailsLink.onclick = function() { parent.loadRightContentPackage( selectedDestinationCode, selectedRegionCode, null, null, packageId, null, null, null, true); } ;
		
		//Offer Details Text node.
		offerDetailsLink.className ="u";
		offerDetailsLink.appendChild( document.createTextNode( "Offer Details" ) );
		packageDetailTd1.appendChild( offerDetailsLink );
	}*/
	
	//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";
    	
		packageDetailTd2.appendChild( callCenterImage );
	}
	
	var isIncludeFlightIncludedRates = packageInfo.isIncludeFlightIncludedRates;

	if (isIncludeFlightIncludedRates && !isFlightIncluded){
		var airfareHoteRatesMessageDiv = document.createElement( 'DIV' );
		airfareHoteRatesMessageDiv.className = "tc06 pt05";
		airfareHoteRatesMessageDiv.appendChild( document.createTextNode("This package offers the best value when airfare is included.") );
		packageDetailTd1.appendChild(airfareHoteRatesMessageDiv);
	}	
	
	packageDetailTr.appendChild( packageDetailTd1 );
	packageDetailTr.appendChild( packageDetailTd2 );
	packageDetailTBody.appendChild( packageDetailTr );
	packageDetailTable.appendChild( packageDetailTBody );
	packageDetailDiv.appendChild( packageDetailTable ); 

	mainDiv.appendChild( packageDetailDiv );
}

/*
 *  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 pb04 mt-02";

	//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( 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 );

	return hotelDetailDiv;
}

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() {
	disableElement( 'dataContent', false );
	showMessage(this.messageType, this.messageCode, this.message, 'dataContent');
	return true;
}

/*
 * Loads flight information into package search result section. 
 */
function loadFlightResultDiv( flightResult, packageInfo ) {
    var outboundItinerary = flightResult.outboundItinerary;
	var inboundItinerary = flightResult.inboundItinerary;

	var flightDetailsDiv = document.createElement( "DIV" );
	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 );
	flightDetailsDiv.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 );
	
	flightDetailsDiv.appendChild( allFlightLinksDiv );
	
	return flightDetailsDiv;
}

/*
 * Loads Car result category information into car result section.
 */
function loadCarResultDiv( 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 carRow2 = 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 );
	
	//Car Icon
	var space = document.createElement( 'IMG' );
	space.src = _webLoc + "/shared/images/core/spacer.gif";
	carImg.alt = carResult.carCompanyName;
	carRow1TD1.appendChild( carImg );
	
	var carRow2TD1 = document.createElement( "TD" );
	carRow2TD1.className = "tac";
	
	var br = document.createElement( 'br' );
	carRow2TD1.appendChild( br );
	
	carRow1.appendChild( carRow1TD1 );
	carRow1.appendChild( carRow1TD2 );
	carRow1.appendChild( carRow1TD3 );
	carRow1.appendChild( carRow1TD4 );
	
	carRow2.appendChild( carRow2TD1 );
	
	carTableTBody.appendChild( carRow1 );
	carTableTBody.appendChild( carRow2 );
	
	carTable.appendChild( carTableTBody );
	return carTable;
}

/*
 * Loads tour information into tour result section of package result.
 * */
function loadTourResultDiv( tourResult ) {
	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 );
	return tourTable;
}

function loadTicketResultsDiv( selectedTicketVendorItems ) {
	var ticketTable = document.createElement( "TABLE" );
	ticketTable.className = "fs11";
	ticketTable.width = "95%";
	ticketTable.cellPadding = '0';
	ticketTable.cellSpacing = '0';
	ticketTable.border="0";
	
	var ticketTableTBody = document.createElement( "TBODY" );

	var ticketHearderRow = document.createElement( "TR" );
	var ticketHearderRowColumn1 = document.createElement( "TD" );
	ticketHearderRowColumn1.className = "pb05 b valt";
	ticketHearderRowColumn1.colSpan = 2;
	ticketHearderRowColumn1.appendChild( document.createTextNode( "Tickets Included:" ) );
	ticketHearderRow.appendChild( ticketHearderRowColumn1 );
	ticketTableTBody.appendChild( ticketHearderRow );

	var numberOfSelectedTicketVendors = selectedTicketVendorItems.length;
	for( var index1 = 0 ; index1 < numberOfSelectedTicketVendors ; index1++ ) {
		var selectedTicketVendorItem = selectedTicketVendorItems[ index1 ];
		var selectedTicketDayItems = selectedTicketVendorItem.SELECTED_TICKETS;
		var numberOfSelectedTicketDayItems = selectedTicketDayItems.length;
		var ticketVendorRow = document.createElement( "TR" );
		var ticketVendorRowColumn1 = document.createElement( "TD" );
		ticketVendorRowColumn1.className = "p02 pl25 b valt";
		ticketVendorRowColumn1.rowSpan = ( numberOfSelectedTicketDayItems + 1 );
		ticketVendorRowColumn1.appendChild( getTicketVendorDisplay( selectedTicketVendorItem.vendor, selectedTicketVendorItem.supplier ) );
		var ticketVendorRowColumn2 = document.createElement( "TD" );
		ticketVendorRowColumn2.appendChild( document.createTextNode( " " ) );
		ticketVendorRow.appendChild( ticketVendorRowColumn1 );
		ticketVendorRow.appendChild( ticketVendorRowColumn2 );
		ticketTableTBody.appendChild( ticketVendorRow );
		for( var index2 = 0 ; index2 < numberOfSelectedTicketDayItems ; index2++ ) {
			var selectedTicketDayItem = selectedTicketDayItems[ index2 ];

			var ticketId = selectedTicketDayItem.ticketId;
			var category = decodeHTML( selectedTicketDayItem.category );
			var passengerIndex = selectedTicketDayItem.passengerIndex;
			var rate = decodeHTML( selectedTicketDayItem.rate );
			var day = selectedTicketDayItem.day;
			var itineraryCode = selectedTicketDayItem.itineraryCode;
			var ticketDate = selectedTicketDayItem.date;

			var selectedTicketRow = document.createElement( "TR" );
			var selectedTicketRowColumn1 = document.createElement( "TD" );
			selectedTicketRowColumn1.className = "p02";

			selectedTicketRowColumn1.appendChild( document.createTextNode( "Passenger " + ( passengerIndex + 1 ) + ": " ) );
			selectedTicketRowColumn1.appendChild( getPassengerTicketDisplay( selectedTicketVendorItem.supplier, day, category, rate, ticketId ) );

			selectedTicketRow.appendChild( selectedTicketRowColumn1 );
			ticketTableTBody.appendChild( selectedTicketRow );
		}
	}

	ticketTable.appendChild( ticketTableTBody );
	return ticketTable;
}

function getTicketVendorDisplay( vendor, supplier ) {
	var anchor = document.createElement( "A" );
	anchor.appendChild( document.createTextNode( vendor ) );
	anchor.className = "u";
	anchor.href = "javascript:;";
	if( !isEmpty( supplier ) ) {
		anchor.onclick = function () { loadParkAndTheaterVendorPopup( supplier ); };
	}
	return anchor;
}

function getPassengerTicketDisplay( supplier, day, category, rate, ticketId ) {
	var anchor = document.createElement( "A" );
	anchor.className = "text u";
	anchor.appendChild( document.createTextNode( day + " Day " + category + " " + rate ) );
	anchor.href = "javascript:;";
	anchor.onclick = function () { loadParkAndTheaterVendorPopup( supplier ); }; 
	return anchor;
}

/*
 * Loads transfer information( which displays greeting information also ) 
 * into transfer result section of package result.
 * 
 * */
function loadTransferResultDiv( 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 );
	return transferTable;
}

/*
 *Function which displays multi city packages.  
 */
function showPackagesWithoutLeadInPrice( pageNumber ) {
	document.getElementById( "searchResults" ).innerHTML = "";
	var packageResults = _packagesWithCityIndex[ _selectedCityTab - 1 ];
	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 isRecommendedPackage = packageResults[ packageCounter ].recommendedPackage;
		var summary = decodeHTML( packageResults[ packageCounter ].summary );
		
		if( isRecommendedPackage ) {
			var itineraryComponentTitleDiv = document.createElement( 'DIV' );
			itineraryComponentTitleDiv.className = "costcoRecommendsComponentTitleBg";
			itineraryComponentTitleDiv.style.marginTop = "-15px";
			itineraryComponentTitleDiv.style.marginBottom = "10px";

			var itineraryComponentIconsDiv = document.createElement( 'DIV' );
			itineraryComponentIconsDiv.className = "itineraryComponentTitleIconContainer";
			
			var costcoRecommendedIconDiv = document.createElement( 'DIV' );
			costcoRecommendedIconDiv.className = "itineraryComponentTitleIcon mr-10";

			var costcoRecommendedTextDiv = document.createElement( 'DIV' );
			costcoRecommendedTextDiv.className = "fs12 fll pl10 pt15 b";
			costcoRecommendedTextDiv.appendChild( document.createTextNode( "Costco Travel Recommends " ) );

			var costcoRecommendedHelpLink = document.createElement( 'A' );
			costcoRecommendedHelpLink.href ="javascript:;";
			costcoRecommendedHelpLink.onclick = function() { loadRecommendedPackagePopup(); };
			var costcoRecommendedHelpIcon = document.createElement( 'IMG' );
			costcoRecommendedHelpIcon.src = _webLoc + "/shared/images/core/icons/help.gif";
			costcoRecommendedHelpIcon.alt = "Help Icon";
			costcoRecommendedHelpLink.appendChild( costcoRecommendedHelpIcon );
			costcoRecommendedTextDiv.appendChild( costcoRecommendedHelpLink );

			var itineraryComponentTitleBR = document.createElement( "BR" );
			itineraryComponentTitleBR.clear = "all";

			itineraryComponentIconsDiv.appendChild( costcoRecommendedIconDiv );
			itineraryComponentIconsDiv.appendChild( costcoRecommendedTextDiv );
			itineraryComponentTitleDiv.appendChild( itineraryComponentIconsDiv );

			searchResultsDiv.appendChild( itineraryComponentTitleBR );
			searchResultsDiv.appendChild( itineraryComponentTitleDiv );
		}
		
		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( 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.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");	
	scrollWindowTop("scrollablePageContent");
}

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(packageJsonResults) {
	if(!showMessage(this.messageType, this.messageCode, this.message, 'dataContent')) {
		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 queryString = 'fr=14';
	queryString += '&uid=' + itemUid;
	queryString += '&forLIP=' + isForLIP;
	queryString += '&packageId=' + packageId;
	var trackingText = '/vp/booking/searchFlights/' + _destinationCode + '/'+ _regionCode + '/package/' + packageId;
	
	createPopupDiv ( "additionalSearchResultsPopupDivContainer", -1, -1, -1, -1, 200 , false , true , "tal popupDiv" );
	disableElement( 'dataContent', true);
	makeAjaxCallWithWaitingDiv ( 'flightResults.act' , queryString , null , 'additionalSearchResultsPopupDivContainer' , 'callbackLoadAdditionalSearchResultsPopup' , null, trackingText );
}

function callbackLoadAdditionalSearchResultsPopup() {
	if( !showMessage(this.messageType, this.messageCode, this.message, 'dataContent' ) ) {
		showBlock ( "additionalSearchResultsPopupDivContainer" );
		positionBlockCentrally ( "additionalSearchResultsPopupDivContainer" );
		disableElement ( "dataContent" , true );
	}
}


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() {
	showMessage(this.messageType, this.messageCode, this.message, 'dataContent');
	return true;
}

function isMultiCityTabEnabled() {
	//var isMultiCityRegion = _isMultiRegionChecked;
	//for( var index = 0; index < DEFAULT_MULTI_DESTINATIONS.length; index++ ) {
	//	if( DEFAULT_MULTI_DESTINATIONS[index].toLowerCase() == selectedDestinationCode.toLowerCase() ){
	//		isMultiCityDestination = true;
	//	}
	//}
	return _isMultiRegionChecked;
}

/* 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() {
	showMessage(this.messageType, this.messageCode, this.message, '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(message) {
	if(!showMessage(this.messageType, this.messageCode, this.message, 'dataContent' )) {
		if( !isNull( message ) && message != '' ){
			showGeneralMessage(message, '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(){
	showMessage(this.messageType, this.messageCode, this.message, '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 );
	}
}

function loadRecommendedPackagePopup() {
	var recommendedPackagePopupDiv = createPopupDiv('recommendedPackagePopupDivContainer', 0, 0, 450, -1, 204, false, true,  "tal popupDiv p10");

	disableElement( 'dataContent', true );
	makeAjaxCall('search/recommendedPackagesPopup.jsp', '', null, 'recommendedPackagePopupDivContainer', 'callbackLoadRecommendedPackagePopup');
}

function callbackLoadRecommendedPackagePopup() {
	showBlock('recommendedPackagePopupDivContainer');
	positionBlockCentrally('recommendedPackagePopupDivContainer');
}
var _event;
var _cityName;
var _cityNameAndState;
var _departureCityString;
var _fromWidget;
var searchedDestinationCode;
var searchedRegionCode;
var _packageId;
var airportInfos;
var _fromMenu;
var _hotelName;
var _selectedDestination;
var _isMultiRegionChecked;
var BOOKABLE_DESTINATION = new Array( 'AUSTRALIA', 'CARIBBEAN', 'EUROPE', 'HAWAII', 'MEXICO', 'NEW ZEALAND', 'FIJI', 'TAHITI', 'COOK ISLANDS', 'FLORIDA', 'LAS VEGAS' );
var FROM_WIDGET = 0;
var FROM_SEARCH_POPUP = 1;
var FROM_CRUISE_PRE_POST = 2;
var _numChildren = 0;
var _numLapChildren = 0;
var _departureDate = 'mm/dd/yyyy';
var _returnDate = 'mm/dd/yyyy';
var _numberOfNights = 0;
var _suggestionCityNames;
var _isRoundtripFlightOptional = false;
var _isIntercityFlightsOptional = false;
var _isIncludeRoundtripFlight = false;
var _isIncludeIntercityFlight = false;
var _lasVegasDestination = "Las Vegas";
var _lasVegasCityCode = "LAS";

/* 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;
		queryString += '&fromMenu=true';
		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, -1, 200, false, true,  "");
		}
	
		// 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.messageType, this.messageCode, this.message, 'dataContent')) {
		var searchPopupDiv = document.getElementById('searchPopupDiv');
		if(searchPopupDiv) {
			showBlock('searchPopupDivContainer');
			positionBlockCentrally('searchPopupDivContainer');	
			disableElement('dataContent', true);
			searchPopupDiv.focus();
		}	
		return true;
	}
	return false;
}

function callbackIsFromWidget( fromWidget, packageId ) {
	if(!showMessage(this.messageType, this.messageCode, this.message, 'dataContent')) {
		if( fromWidget ){
			_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" );
	var flightType = 0;
	

	//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 ) {
		flightType = getCheckedValue("flightType");
		if( trim( departureCity ) == '' ){
			departureCityCode = "";
		}
		
		if(  trim( departureCityCode ) == '' && _isIncludeRoundtripFlight && flightType != 2) {
			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( 'dataContent', true );
	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;
	queryString += '&flightType=' + flightType;
	
	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.messageType, this.messageCode, this.message, '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.messageType, this.messageCode, this.message, '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 ) {
		if(!showMessage(this.messageType, this.messageCode, this.message, 'searchPopupDivContainer' )) {
			initiatePackageSearch( _packageId, fromWidget );
		}else {
			return false;
		}
	}else {
		if(showMessage(this.messageType, this.messageCode, this.message, '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;
	
	//Google Analytics event tracker
	trackEvent('vp_event_searchWidget', 'Travellers', 'Rooms', 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;
		adultsInRoom.onchange = function(){ reportAdultNumberChange(); };
		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 ); reportChildrenNumberChange();};
		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 + "); reportChildrenNumberChange();" );
	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);			
	infantSeatSelectWidget.onchange = new Function("reportChildrenNumberChange();");
	
	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 + "); reportChildrenNumberChangeForWidget();");
				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);		
				infantSeatSelectWidget.onchange = new Function("reportChildrenNumberChangeForWidget();");
				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;
	
	//Google Analytics event tracker
	trackEvent('vp_event_searchWidget', 'Travellers', 'Rooms', 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;
		adultsInRoom.onchange = function(){ reportAdultNumberChangeForWidget(); };
		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 ); reportChildrenNumberChangeForWidget(); };

		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 includeFlightItinerary = document.getElementById( "includeFlightItinerary" ).value == "true";
	if (includeFlightItinerary){
		var flightItineraryCheckbox = document.getElementById( "flightItineraryCheckbox" );
		_isRoundtripFlightOptional = document.getElementById("isRoundtripFlightOptional").value == "true";
		_isIntercityFlightsOptional = document.getElementById("isIntercityFlightsOptional").value == "true";
		_isIncludeRoundtripFlight = document.getElementById("isIncludeRoundtripFlight").value == "true";
		_isIncludeIntercityFlight = document.getElementById("isIncludeIntercityFlight").value == "true";
	
		setFlightTypeOptionsForSearchPopup();
		
		if( flightItineraryCheckbox != undefined ){
			var isFlightItinerary = flightItineraryCheckbox.checked;
			if( !isFlightItinerary ){
				document.getElementById( "flightItineraryBlockRow1" ).style.display = "none";
				document.getElementById( "flightItineraryBlockRow2" ).style.display = "none";
				document.getElementById( "flightItineraryBlockRow3" ).style.display = "none";
				document.getElementById( "departureCityText" ).value = "";
			}else {
				document.getElementById( "flightItineraryBlockRow1" ).style.display = "";
				document.getElementById( "flightItineraryBlockRow2" ).style.display = "";
				document.getElementById( "flightItineraryBlockRow3" ).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 setFlightItineraryCheckbox(){
	var flightItineraryCheckbox = document.getElementById( "flightItineraryCheckbox" );
	if (flightItineraryCheckbox){
		_isRoundtripFlightOptional = document.getElementById("isRoundtripFlightOptional").value == "true";
		_isIntercityFlightsOptional = document.getElementById("isIntercityFlightsOptional").value == "true";
		_isIncludeRoundtripFlight = document.getElementById("isIncludeRoundtripFlight").value == "true";
		_isIncludeIntercityFlight = document.getElementById("isIncludeIntercityFlight").value == "true";
		
		flightItineraryCheckbox.checked = (_isIncludeRoundtripFlight || _isIncludeIntercityFlight);
		flightItineraryCheckbox.disabled = ((!_isRoundtripFlightOptional && _isIncludeRoundtripFlight) || (!_isIntercityFlightsOptional && _isIncludeIntercityFlight) );
	}	
}

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){
		var 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 = infantSeatSelect.value;
									infantSeatSelect.style.display="";									
								}	
							}	
						}else {
							infantSeatSelect.style.display="none";
						}
					}
				}	
			}	
		}
	}	
}

function displayInfantSeatSelectsForWidget(show){
	var numberOfRoomsWidget = document.getElementById("numberOfRoomsWidget");
	if(numberOfRoomsWidget){
		var 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;    

	//Google Analytics event tracker
	trackEvent('vp_event_searchWidget', 'Destination', 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;
		}
		if(isMultiCityDestination(destination)) {
			modifyClassName("multiRegionCheckboxTd", "-displayNone");
			document.getElementById("multiRegionCheckboxWidget").checked = isMultiCityDestinationChecked(destination);			
		}else {
			modifyClassName("multiRegionCheckboxTd", "+displayNone");
			document.getElementById("multiRegionCheckboxWidget").checked = 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 == "luxuryVillaRentals"     ||
        destination == "houseboatVacations") {
          return false;           
    }    
    return true;
}

function isMultiCityDestination(destination) {
	for(var i=0; i<DEFAULT_MULTI_DESTINATIONS.length; i++) {
		if(destination.toLowerCase() == DEFAULT_MULTI_DESTINATIONS[i].toLowerCase()) {
			return true;
		}
	}
	return false;
}

function isMultiCityDestinationChecked(destination) {
	for(var i=0; i<DEFAULT_MULTI_DESTINATIONS_CHECKED.length; i++) {
		if(destination.toLowerCase() == DEFAULT_MULTI_DESTINATIONS_CHECKED[i].toLowerCase()) {
			return true;
		}
	}
	return false;
}




/*
 *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 == "luxuryVillaRentals" ) {
        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.messageType, this.messageCode, this.message, 'dataContent' ) ) {
		if( document.getElementById( "themeParksTD" ).style.display == "block" ){
			document.getElementById( "themeParksTD" ).style.display = "none";
		}
		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(); loadVPMoreOptionsInfoBySelectedRegion();reportChangedRegion();showHideVPMoreOptionLabel();'>" + citiesList + "</select></label></div>";
		}
	}
	displayWidgetFieldsForSelectedDestination();
	return true;
}

function displayWidgetFieldsForSelectedDestination() {
    if( !_selectedDestination || _selectedDestination == "" ) {
    	document.getElementById( "themeParksTD" ).style.display = "none";
        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 ) ) {
    	if( _selectedDestination == _lasVegasDestination ){
			 document.getElementById( "cityTd").style.display = "none"; 
		}
		else {
			document.getElementById( "cityTd").style.display = "block"; 
		}
        document.getElementById( "hotelNameTd").style.display = "none";
        document.getElementById( "searchFieldsWidgetDiv" ).style.display = "";
        document.getElementById( "otherDestinationsDiv" ).style.display = "none";
    } else {
    	document.getElementById( "themeParksTD" ).style.display = "none";
        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 = "";
    }
    
    if(isMultiCityDestination(_selectedDestination)) {
		modifyClassName("multiRegionCheckboxTd", "-displayNone");
		document.getElementById("multiRegionCheckboxWidget").checked = isMultiCityDestinationChecked(_selectedDestination);			
	}else {
		modifyClassName("multiRegionCheckboxTd", "+displayNone");
		document.getElementById("multiRegionCheckboxWidget").checked = false;
	}
    //_selectedDestination = "";
	showHideVPMoreOptionLabel();
}

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>.";
    }else if(destination =="luxuryVillaRentals"){
        return "From the famed California wine country to stunning locales in Italy, France and Mexico, BeautifulPlaces offers spectacular private homes for rent.";
    }
}

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;
	}
	_selectedDestination = destination;

	var isRegionValidationRequired = isRegionRequired( destination );
	var region = document.getElementById( "region" ).value;
	
	if( isRegionValidationRequired && !(_selectedDestination == _lasVegasDestination)) {
		if ( region == "" ) {
			var msg ="Please select a region.";
			showErrorMessage( msg, 'dataContent', 'regionDiv', '#7f9db9');
			return false;
		}
	}
	
	_isMultiRegionChecked = document.getElementById("multiRegionCheckboxWidget").checked;
	
	//GA Event Tracking vp_event_searchWidget
	trackEvent('vp_event_searchWidget', 'Click', "Search");

    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=' + ((_selectedDestination == _lasVegasDestination)? _lasVegasCityCode : 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;
    	if( document.getElementById ( "vpMoreSearchOptionBlock" ).style.display == "block" ){
    		var list = document.getElementById("moreOptionsHotels");
			var options = list.options;
    		if( options[0].selected == true ){
    			options[0].selected = false;
    			for(var i=1; i<options.length; i++) {
					options[i].selected = true;
				}
    		}
    		var preferredHotels = getSelectedOptionsAsQueryString("moreOptionsHotels", "preferredHotels", 1, 0, -1);
    		var location = document.getElementById ( "moreOptionsArea" ).value
    		var rating = document.getElementById ( "moreOptionsRatings" ).value
    		queryString += "&" + preferredHotels;
    		queryString += '&displayMoreSearchOption=true';
    		queryString += '&location='+location;
    		queryString += '&rating='+rating;
    		var accommodationTypesString = "";
    		var accommodationTypes = document.getElementsByName("accommodationTypes");
    		var counter = 0;
    		for( var index = 0; index < accommodationTypes.length; index++ ){
    			if( accommodationTypes[ index ].checked ){
    				if( counter == 0 ){
    					accommodationTypesString = accommodationTypes[ index ].id;
    				} else {
    					accommodationTypesString += "," + accommodationTypes[ index ].id;
    				}
    				counter++;
    			}
    		}
    		queryString += '&accommodationTypes='+accommodationTypesString;
    	}
    	if( document.getElementById("themeParksTD").style.display == 'block' && !isNull(document.getElementById("themeParks"))){
	    	var themeParksList = document.getElementById("themeParks");
			var themeParksOptions = themeParksList.options;
			if( themeParksOptions[0].selected == true ){
				/*themeParksOptions[0].selected = false;
				for(var i=1; i<themeParksOptions.length; i++) {
					themeParksOptions[i].selected = true;
				}*/
				queryString += '&preferredVendors=';
			} else {
		    	var preferredVendors = getSelectedOptionsAsQueryString("themeParks", "preferredVendors", 1, 0, -1);
				queryString += "&" + preferredVendors;
			}
    	}
    	//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(PageHistoryConstants.HISTORY_SEARCH_RESULT_ALL_PACKAGES, historyData);
	setSupportPhoneNumber(bookingPhoneNumber);
}

function callbackSearchPackagesForWidget() {
	if(!showMessage(this.messageType, this.messageCode, this.message, 'dataContent')){
		disableElement( 'dataContent', false );
		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();
	}
	document.getElementById("multiRegionCheckboxWidget").checked = _isMultiRegionChecked;
	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() {
	if(!showMessage(this.messageType, this.messageCode, this.message, 'dataContent')) {
		disableElement( 'dataContent', false );
	}
	return true;
}

function showHiddenSearchPopup() {
	var searchPopupDivContainer = document.getElementById('searchPopupDivContainer');
	if( searchPopupDivContainer != null && searchPopupDivContainer != undefined ){
		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, fromWhere ) {
	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 = parseInt(fromWhere);

	if( FROM_WIDGET == _fromWidget ){
		//from package search widget
		cityNameField = document.getElementById( "departureCityTextWidget" );
		content = "mainContent";
		_departureCityString = "departureCityTextWidget";
	}
	else if ( FROM_SEARCH_POPUP == _fromWidget ) {
		//from search popup (flight)
		cityNameField = document.getElementById( "departureCityText" );
		content = "searchPopupDivContainer";
		_departureCityString = "departureCityText";
	} else {
		//from pre post cruise package
		cityNameField = document.getElementById( "departureCityTextPrePost" );
		content = "rightContent";
		_departureCityString = "departureCityTextPrePost";
	}
	
	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(airportInfosJson ) {
	if(hasMessage(this)) {
		if( FROM_WIDGET==_fromWidget  ) {
			showMessage(this.messageType, this.messageCode, this.message, 'dataContent');
		} else if ( FROM_SEARCH_POPUP==_fromWidget  ) {
			showMessage(this.messageType, this.messageCode, this.message, 'searchPopupDivContainer');
		} else {
			// from pre post packages
			showMessage(this.messageType, this.messageCode, this.message, 'dataContent');
		}
	} else {
		if(airportInfosJson) {
			airportInfos = eval(airportInfosJson);
		}
		
		var suggestions = new Array();
		_suggestionCityNames = 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; 
					_suggestionCityNames[airportInfos[index].code] = airportInfos[index].cityName;
					_cityNameAndState = airportInfos[index].cityName + ", " + airportInfos[index].state;
				}
				if(airportInfos[index].cityName.toUpperCase().indexOf(_cityName) == 0) {
					suggestions[airportInfos[index].code] = "(" + airportInfos[index].code + ") " + airportInfos[index].name;
					_suggestionCityNames[airportInfos[index].code] = airportInfos[index].cityName;
					_cityNameAndState = airportInfos[index].cityName + ", " + airportInfos[index].state;
				}
				if(airportInfos[index].code.toUpperCase() == _cityName) {
					suggestions[airportInfos[index].code] = "(" + airportInfos[index].code + ") " + airportInfos[index].name;
					_suggestionCityNames[airportInfos[index].code] = airportInfos[index].cityName;
					_cityNameAndState = airportInfos[index].cityName + ", " + airportInfos[index].state;
				}			
			}
		}
		
		if( FROM_WIDGET==_fromWidget ){
			document.getElementById( "departureCityCodeWidget" ).value ="";
			showSuggestionBox( _event, 'departureCityTextWidget', suggestions, 'tc04 w295 fs11 h90','No departure cities found with given criteria' );
		}
		else {
				if ( FROM_SEARCH_POPUP==_fromWidget ) {
					document.getElementById( "departureCityCode" ).value ="";
					showSuggestionBox( _event, 'departureCityText', suggestions, 'tc04 w295 fs11 h90','No departure cities found with given criteria' );
				} else if ( FROM_CRUISE_PRE_POST==_fromWidget ) {
					document.getElementById( "departureCityCodePrePost" ).value ="";
					showSuggestionBox( _event, 'departureCityTextPrePost', 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";

	//Google Analytics event tracking
	trackEvent('WidgetTabs', 'Packages', 'Click');
}

function showSearchCruisesTab() {
	//Google Analytics event tracking
	trackEvent('WidgetTabs', 'Cruises', 'Click');

	loadCruiseWidgetHome(false);
}

function showSearchCarsTab() {
	window.scrollTo(0,0);
	//Google Analytics event tracking
	trackEvent('WidgetTabs', 'Cars', 'Click');
	var queryString = 'lc=19&lbc=5&rc=6&ancillary=rentalCars';
	addHistory(PageHistoryConstants.HISTORY_ANCILLARY_LANDING,'rentalCars');
	loadMainContentWithWaitingDiv('mainContent.act', queryString, '/rc/browse/carsHome');
}

function showSearchHotelsTab() {
	//Google Analytics event tracking
	trackEvent('WidgetTabs', 'Hotels', 'Click');

	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 and Hyatt online.<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 getDisabledDateRangesForReturnDate( departureDateFieldName ) {
	var departureDateValue = document.getElementById( departureDateFieldName ).value;
	var dateRange = getDisabledDateRangeForReturnDate( departureDateFieldName );
	var disabledDateRanges = new Array();
	if( !( isNull( dateRange ) ) ) {
		disabledDateRanges[ disabledDateRanges.length ] = dateRange;
		disabledDateRanges.sort( sortByDateRange );
	} 
	return disabledDateRanges;
}

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 );
		var isSpecialDateAdded = false;
		while( firstDate <= secondDate ) {
			var date = new Date( firstDate );
			specialDatesForPackage[ date ] = date;
			firstDate.setDate( firstDate.getDate() + 1 );
			isSpecialDateAdded = true;
		}
		//If special dates are not added, then we are adding the first date into the list.
		if( !isSpecialDateAdded ) {
			specialDatesForPackage[ firstDate ] = firstDate;
		}
	} 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, dependentDateElementName ) {
	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, null, false, dependentDateElementName );
}

function showTravelCalendar(elementName, isReturnDate, dependentDateElementName ) {

	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, false, dependentDateElementName);
}

function flightItineraryCheckBoxOnClick() {
	loadFlightItineraryInformation();
	var isFlightItineraryField = document.getElementById( "flightItineraryCheckbox" );
	if( isFlightItineraryField ){
		var isFlightItinerary = isFlightItineraryField.checked;
		if( !isFlightItinerary ){
			displayInfantSeatSelects(false);
		}else {
			displayInfantSeatSelects(true);
		}
	}	
	trackEvent('vp_event_searchWidget', 'Flight', (isFlightItinerary ? "Yes" : "No"));
}

function flightItineraryCheckBoxWidgetOnClick() {
	loadFlightItineraryInformationForWidget();
	var isFlightItineraryField = document.getElementById( "flightItineraryCheckboxWidget" );
	if( isFlightItineraryField ){
		var isFlightItinerary = isFlightItineraryField.checked;
		if( !isFlightItinerary ){
			displayInfantSeatSelectsForWidget(false);
		}else {
			displayInfantSeatSelectsForWidget(true);
		}
	}	
	//Google Analytics event tracker
	trackEvent('vp_event_searchWidget', 'Flight', (isFlightItinerary ? "Yes" : "No"));
} 

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(hotelIdList ) {
	if(!showMessage(this.messageType, this.messageCode, this.message, 'dataContent')){
		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, elementKey ){
	if( elementName != null && elementName != undefined ){
		var suggestionBoxSelect = document.getElementById("_suggestionBoxSelect");
		var cityName = "";
		
		if (_suggestionCityNames){
			for (var index in _suggestionCityNames){
				if (index == suggestionBoxSelect.value){
					cityName = _suggestionCityNames[index];
					break;
				}	
			}	
		}
		if( elementName.id == 'hotelNameWidget' ){
			document.getElementById( "hotelIdWidget" ).value = suggestionBoxSelect.value;
		} else if( elementName.id == 'departureCityTextWidget' ){
			document.getElementById( "departureCityCodeWidget" ).value = suggestionBoxSelect.value;
			reportDepartureCityChangeForWidget();
		} else if( elementName.id == 'departureCityText' ){
			document.getElementById( "departureCityCode" ).value = suggestionBoxSelect.value;
			document.getElementById( "departureCityName" ).value = cityName;
			reportDepartureCityChange();
			setFlightTypes();
		} else if( elementName.id == 'departureCityTextPrePost' ){
			document.getElementById( "departureCityCodePrePost" ).value = suggestionBoxSelect.value;
		} else if( elementName.id == 'pickupAirportTextWidget' ) {
			document.getElementById( "pickupAirportCodeWidget" ).value = suggestionBoxSelect.value;
			loadCarDriverAges( CAR_SEARCH_WIDGET );
		} else if( elementName.id == 'dropoffAirportTextWidget' ) {
			document.getElementById( "dropoffAirportCodeWidget" ).value = suggestionBoxSelect.value;
		} else if( elementName.id == 'pickupAirportTextPopup' ) {
			document.getElementById( "pickupAirportCodePopup" ).value = suggestionBoxSelect.value;
			loadCarDriverAges( CAR_SEARCH_POPUP );
		} else if( elementName.id == 'dropoffAirportTextPopup' ) {
			document.getElementById( "dropoffAirportCodePopup" ).value = suggestionBoxSelect.value;
		} else if( elementName.id == 'pickupCityTextWidget' ) {
			document.getElementById( "pickupCityCodeWidget" ).value = suggestionBoxSelect.value;
			loadCarDriverAges( CAR_SEARCH_WIDGET );
		} else if( elementName.id == 'dropoffCityTextWidget' ) {
			document.getElementById( "dropoffCityCodeWidget" ).value = suggestionBoxSelect.value;
		} else if( elementName.id == 'pickupCityTextPopup' ) {
			document.getElementById( "pickupCityCodePopup" ).value = suggestionBoxSelect.value;
			loadCarDriverAges( CAR_SEARCH_POPUP );
		} else if( elementName.id == 'dropoffCityTextPopup' ) {
			document.getElementById( "dropoffCityCodePopup" ).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;
}

function reportChangedRegion(){
	var regionName;
	var regionList = document.getElementById( "region");
	
	for (var i=0; i < regionList.options.length; i++){
		if (regionList.options[i].selected){
			regionName = regionList.options[i].text;
			break;
		}	
	}	
	//Google Analytics event tracker
	trackEvent('vp_event_searchWidget', 'Region', regionName);
	return true;
}

function reportDepartureCityChangeForWidget(){
	var departureCityCode = document.getElementById( "departureCityCodeWidget" ).value;

	//Google Analytics event tracker
	trackEvent('vp_event_searchWidget', 'Departure_City', departureCityCode, _cityNameAndState);
	return true;
}

function reportDepartureCityChange(){
	var departureCityCode = document.getElementById( "departureCityText" ).value;
	
	//Google Analytics event tracker
	trackEvent('vp_event_searchWidget', 'Departure_City', departureCityCode, _cityNameAndState);
	return true;
}

function reportServiceClassChangeForWidget(){
	var serviceClass = document.getElementById( "serviceClassWidget" ).value;

	//Google Analytics event tracker
	trackEvent('vp_event_searchWidget', 'Class', serviceClass);
	return true;
}

function reportServiceClassChange(){
	var serviceClass = document.getElementById( "serviceClass" ).value;

	//Google Analytics event tracker
	trackEvent('vp_event_searchWidget', 'Class', serviceClass);
	return true;
}

function reportDateChangeForWidget(){
	var departureDate = document.getElementById( "departureDateWidget" ).value;
	var returnDate = document.getElementById( "returnDateWidget" ).value;
	var numberOfNights = document.getElementById( "numberOfNightsWidget" ).value;
	
	//Google Analytics event tracker
	
	if (departureDate != "mm/dd/yyyy" && _departureDate != departureDate){
		trackEvent('vp_event_searchWidget', 'Depart', departureDate);
	}	

	if (returnDate != "mm/dd/yyyy" && _returnDate != returnDate){
		trackEvent('vp_event_searchWidget', 'Return', returnDate);
	}	
	
	if (_numberOfNights != numberOfNights){
		trackEvent('vp_event_searchWidget', 'Nights', 'Nights', numberOfNights);
	}	
	
	_numberOfNights = numberOfNights;
	_departureDate = departureDate;
	_returnDate = returnDate;
	
	return true;
}
function reportDateChange(){
	var departureDate = document.getElementById( "departureDate" ).value;
	var returnDate = document.getElementById( "returnDate" ).value;
	var numberOfNights = _totalNumberOfNights;		
	
	//Google Analytics event tracker
	
	if (departureDate != "mm/dd/yyyy" && _departureDate != departureDate){
		trackEvent('vp_event_searchWidget', 'Depart', departureDate);
	}	

	if (returnDate != "mm/dd/yyyy" && _returnDate != returnDate){
		trackEvent('vp_event_searchWidget', 'Return', returnDate);
	}	
	
	if (_numberOfNights != numberOfNights){
		trackEvent('vp_event_searchWidget', 'Nights', 'Nights', numberOfNights);
	}	
	
	_numberOfNights = numberOfNights;
	_departureDate = departureDate;
	_returnDate = returnDate;
	
	return true;
}


function reportAdultNumberChangeForWidget(){
	var numAdults = 0;
	var hotelRooms = document.getElementById( "numberOfRoomsWidget" ).value;

	for( var roomCounter = 1; roomCounter <= hotelRooms; roomCounter++ ) {
		if (document.getElementById( "adultsInRoomForWidget_" + roomCounter )){
			numAdults += parseInt( document.getElementById( "adultsInRoomForWidget_" + roomCounter ).value );
		}
	}
	
	//Google Analytics event tracker
	trackEvent('vp_event_searchWidget', 'pax_Adults', 'Adults', numAdults);
	return true;
}

function reportAdultNumberChange(){
	var numAdults = 0;
	var hotelRooms = document.getElementById( "numberOfRooms" ).value;

	for( var roomCounter = 1; roomCounter <= hotelRooms; roomCounter++ ) {
		if (document.getElementById( "adultsInRoom_" + roomCounter )){
			numAdults += parseInt( document.getElementById( "adultsInRoom_" + roomCounter ).value );
		}
	}
	
	//Google Analytics event tracker
	trackEvent('vp_event_searchWidget', 'pax_Adults', 'Adults', numAdults);
	return true;
}

function reportChildrenNumberChangeForWidget(){
	var numChildren = 0;
	var numLapChildren = 0;
	var TYPE_LAP_CHILDREN = "0";
	var hotelRooms = document.getElementById( "numberOfRoomsWidget" ).value;
	
  	for( var roomCounter = 1; roomCounter <= hotelRooms; roomCounter++ ) {
  		numChildren += parseInt( document.getElementById( "childrenInRoomForWidget_" + roomCounter ).value );
  			
		for ( var childCounter = 1; childCounter <= numChildren ; childCounter++ ){
			if (document.getElementById( "childAgeForWidget_" + childCounter + "_" + roomCounter ) != null && 
				document.getElementById( "infantSeatSelectWidget_" + childCounter + "_" + roomCounter ) != null	){
				var childrenAgesPerRoom = document.getElementById( "childAgeForWidget_" + childCounter + "_" + roomCounter ).value;
		  		var infantSeatSelectWidgetValue = document.getElementById( "infantSeatSelectWidget_" + childCounter + "_" + roomCounter ).value;
				if (childrenAgesPerRoom != -1 && childrenAgesPerRoom < 2 && infantSeatSelectWidgetValue == TYPE_LAP_CHILDREN){
					numLapChildren++;
				}
			}
			
		}	
	}	
	
	//Google Analytics event tracker
	if (_numChildren != numChildren || _numLapChildren != numLapChildren){
		_numChildren = numChildren;
		trackEvent('vp_event_searchWidget', 'pax_Children', 'Children', (numChildren - numLapChildren));
	}
	
	if (_numLapChildren != numLapChildren){
		_numLapChildren = numLapChildren;
		trackEvent('vp_event_searchWidget', 'pax_LapChildren', 'Lap Children', numLapChildren);
	}	
	return true;
}

function reportChildrenNumberChange(){
	var numChildren = 0;
	var numLapChildren = 0;
	var TYPE_LAP_CHILDREN = "0";
	var hotelRooms = document.getElementById( "numberOfRooms" ).value;
	
  	for( var roomCounter = 1; roomCounter <= hotelRooms; roomCounter++ ) {
  		numChildren += parseInt( document.getElementById( "childrenInRoom_" + roomCounter ).value );

  		for ( var childCounter = 1; childCounter <= numChildren ; childCounter++ ){
			if (document.getElementById( "childAge_" + childCounter + "_" + roomCounter ) != null && 
				document.getElementById( "infantSeatSelect_" + childCounter + "_" + roomCounter ) != null	){
				var childrenAgesPerRoom = document.getElementById( "childAge_" + childCounter + "_" + roomCounter ).value;
				var infantSeatSelectValue = document.getElementById( "infantSeatSelect_" + childCounter + "_" + roomCounter ).value;
				if (childrenAgesPerRoom != -1 && childrenAgesPerRoom < 2 && infantSeatSelectValue == TYPE_LAP_CHILDREN){
					numLapChildren++;
				}
			}
		}	
	}	
	
	//Google Analytics event tracker
	if (_numChildren != numChildren || _numLapChildren != numLapChildren){
		_numChildren = numChildren;
		trackEvent('vp_event_searchWidget', 'pax_Children', 'Children', (numChildren - numLapChildren));
	}
	
	if (_numLapChildren != numLapChildren){
		_numLapChildren = numLapChildren;
		trackEvent('vp_event_searchWidget', 'pax_LapChildren', 'Lap Children', numLapChildren);
	}	
	return true;
}

function setFlightTypeOptionsForSearchPopup(){
	var departureCityCode = document.getElementById("departureCityCode").value;
	
	var radioFlightTypeAll = getRadioWithValue("flightType", 0);
	var radioFlightTypeRoundtrip = getRadioWithValue("flightType", 1);
	var radioFlightTypeIntercity = getRadioWithValue("flightType", 2);

	var flightItineraryAllSpan = document.getElementById("allFlightSegments");
	var flightItineraryRoundtripSpan = document.getElementById("roundtripFlightSegments");
	var flightItineraryIntercitySpan = document.getElementById("intercityFlightSegments");

	flightItineraryAllSpan.style.display = "none";
	flightItineraryRoundtripSpan.style.display = "none";
	flightItineraryIntercitySpan.style.display = "none";

	radioFlightTypeAll.checked = false;
	radioFlightTypeRoundtrip.checked = false;
	radioFlightTypeIntercity.checked = false;

	radioFlightTypeAll.disabled = false;
	radioFlightTypeRoundtrip.disabled = false;
	radioFlightTypeIntercity.disabled = false;

	if (_isIncludeRoundtripFlight == true && _isIncludeIntercityFlight == true){
		if (_isRoundtripFlightOptional == true && _isIntercityFlightsOptional == true){
			if (departureCityCode != ""){
				flightItineraryAllSpan.style.display = "";
				flightItineraryRoundtripSpan.style.display = "";
				radioFlightTypeAll.checked = true;
			}
			else{
				radioFlightTypeAll.disabled = true;
				radioFlightTypeRoundtrip.disabled = true;
				
				radioFlightTypeIntercity.checked = true;
			}
			
			flightItineraryIntercitySpan.style.display = "";
		}
		else if (_isRoundtripFlightOptional == true && _isIntercityFlightsOptional == false){
			if (departureCityCode != ""){
				flightItineraryAllSpan.style.display = "";
			}	
			else{
				radioFlightTypeAll.disabled = true;
			}
			
			flightItineraryIntercitySpan.style.display = "";
	
			radioFlightTypeRoundtrip.disabled = true;
			radioFlightTypeIntercity.checked = true;
		}
		else if (_isRoundtripFlightOptional == false && _isIntercityFlightsOptional == true){
			if (departureCityCode != ""){
				flightItineraryAllSpan.style.display = "";
				flightItineraryRoundtripSpan.style.display = "";
				radioFlightTypeAll.checked = true;
			}
			else{
				radioFlightTypeAll.disabled = true;
				radioFlightTypeRoundtrip.disabled = true;
			}	
			
			radioFlightTypeIntercity.disabled = true;
		}	
		else if (_isRoundtripFlightOptional == false && _isIntercityFlightsOptional == false){
			if (departureCityCode != ""){
				flightItineraryAllSpan.style.display = "";
				radioFlightTypeAll.checked = true;
			}
			else{
				radioFlightTypeAll.disabled = true;
			}	
			
			radioFlightTypeRoundtrip.disabled = true;
			radioFlightTypeIntercity.disabled = true;
		}	
	}
	else {
		if (_isIncludeRoundtripFlight == false && _isIncludeIntercityFlight == true){
			radioFlightTypeAll.disabled = true;
			radioFlightTypeRoundtrip.disabled = true;
			radioFlightTypeIntercity.disabled = false;
			
			radioFlightTypeIntercity.checked = true;
			
			flightItineraryAllSpan.style.display = "none";
			flightItineraryRoundtripSpan.style.display = "none";
			flightItineraryIntercitySpan.style.display = "";
		}
		
		if (_isIncludeIntercityFlight == false && _isIncludeRoundtripFlight == true){
			radioFlightTypeAll.disabled = true;
			radioFlightTypeRoundtrip.disabled = false;
			radioFlightTypeIntercity.disabled = true;

			radioFlightTypeRoundtrip.checked = true;

			flightItineraryAllSpan.style.display = "none";
			flightItineraryRoundtripSpan.style.display = "";
			flightItineraryIntercitySpan.style.display = "none";
		}
	}	
}


function setFlightTypes(){
	var displayIntercityFlightOptions = document.getElementById("displayIntercityFlightOptions").value;
	var numberOfCities = document.getElementById("numberOfCities").value;
	
	if (document.getElementById("departureCityCode").value != ''){

		setFlightTypeOptionsForSearchPopup();		

		var departureCityCode = document.getElementById("departureCityCode").value;
		var departureCityName = document.getElementById("departureCityName").value;
		var departureCityDisplay = departureCityName + (departureCityName.indexOf("(") == -1 ? "(" + departureCityCode + ")" : "" );

		document.getElementById("departureOutboundRoundtripSpan").innerHTML = departureCityDisplay;
		document.getElementById("departureInboundRoundtripSpan").innerHTML = departureCityDisplay;
		document.getElementById("departureOutboundAllSpan").innerHTML = departureCityDisplay;
		document.getElementById("departureInboundAllSpan").innerHTML = departureCityDisplay;
		
		
	}else{
		document.getElementById("departureOutboundRoundtripSpan").innerHTML = "";
		document.getElementById("departureInboundRoundtripSpan").innerHTML = "";

		if (numberOfCities > 1){
			document.getElementById("departureOutboundAllSpan").innerHTML = "";
			document.getElementById("departureInboundAllSpan").innerHTML = "";
		}	
	}
}

function loadServiceClassesByDestinationCode( destination ){
	_selectedDestination = destination;
	var serviceClass =  document.getElementById( "serviceClassWidget");
	var queryString = 'lc=16';
	queryString += '&destination=' + destination;
	queryString += '&serviceClass=' + serviceClass.value;
	makeAjaxCall( 'leftContent.act', queryString, null, null, 'callbackLoadServiceClassesByDestinationCode', '' );	
}

function callbackLoadServiceClassesByDestinationCode(serviceClassesOptions){
	document.getElementById ( "serviceClassesDiv" ).innerHTML = "<select name='serviceClassWidget' id='serviceClassWidget' class='w105 mt05 textbox fs11' onChange='reportServiceClassChangeForWidget()'>"+serviceClassesOptions+"</select>";
}

/**
 *	vpShowHideMoreSearchOptionsBlock(...) method show or hides 'More search options' block in the package search widget.  
 */
function vpShowHideMoreSearchOptionsBlock() {
	clearErrorElements();
	var displayStatus = document.getElementById ( "vpMoreSearchOptionBlock" ).style.display;
	if ( ( displayStatus == "block"  ) ) {
		document.getElementById ( "vpMoreSearchOptionBlock" ).style.display = "none";
		document.getElementById ( "moreOptionsArea" ) [ 0 ].selected = true;
		document.getElementById ( "moreOptionsHotels" ) [ 0 ].selected = true;
		document.getElementById ( "moreOptionsRatings" ) [ 0 ].selected = true;
	} else {
		document.getElementById ( "vpMoreSearchOptionBlock" ).style.display = "block";
	}
	trackEvent("Search Vocation Package", "Vocation Package More Options", "Click");
}

/**
 *	showHideVPMoreOptionLabel(...) method show or hides 'More search options' label in the package search widget.  
 */
function showHideVPMoreOptionLabel(){
	var destination = document.getElementById( "destination" );
	var region = document.getElementById( "region" );
	if( ( ( isNull(region) || ( region.length > 0 && region[ 0 ].selected == true ) || region.value == ""  )|| (isNull(destination) || destination[ 0 ].selected == true || destination.value == ""  ) ) || ( document.getElementById( "cityTd").style.display =='none' && destination.value != "" )){
		document.getElementById ( "vpMoreOptionLabeldiv" ).style.display = "none";
		if(  document.getElementById ( "vpMoreSearchOptionBlock" ).style.display == "block"){
			document.getElementById ( "vpMoreSearchOptionBlock" ).style.display = "none";
		}
	} else {
		document.getElementById ( "vpMoreOptionLabeldiv" ).style.display = "block";
	}
}

/**
 *	loadVPMoreOptionsInfoBySelectedRegion(...) method loads the hotels based on selected region in search widget.  
 */
function loadVPMoreOptionsInfoBySelectedRegion(){
	var region = document.getElementById( "region" ).value;
	if( region == "" ){
		document.getElementById( "themeParksTD" ).style.display = "none";
		return false;
	}
	var queryString = "lc=17";
	queryString += '&cityCode=' + region;
	makeAjaxCall( 'leftContent.act', queryString, null, 'mainContent', 'callbackLoadVPMoreOptionsInfo', '' );		
}

function callbackLoadVPMoreOptionsInfo( areaList, ratingList, hotelList,accommodationTypes, themeParks ){
	var sb = "";
	replaceOptions ( "moreOptionsArea", areaList );
	replaceOptions ( "moreOptionsRatings", ratingList );
	replaceOptions ( "moreOptionsHotels", hotelList );
	if( !isNull(themeParks) && themeParks != '' ){
		replaceOptions ( "themeParks", themeParks );
		document.getElementById( "themeParksTD" ).style.display = "block";
	} else {
		document.getElementById( "themeParksTD" ).style.display = "none";
	}
	if( !isNull(accommodationTypes) && accommodationTypes != "" ){
		var accommodationTypesArray = accommodationTypes.split( "," );
		for( var index = 0; index < accommodationTypesArray.length; index ++ ){
			var accommodationType = accommodationTypesArray[ index ];
			if( trim(accommodationType) != "" ){
				sb += "<label><input type='checkbox' id='"+ accommodationType + "' name='accommodationTypes' onclick='loadHotelsBySelectedOptions();'/>&nbsp;&nbsp;"+ accommodationType +"</label><br />"
			}
		}
	}
	document.getElementById( "accommadationTypesDiv" ).innerHTML = sb;
}

/**
 *	loadHotelsBySelectedOptions(...) method loads the hotels based on selected options like area,rating and accommadations types in search widget.  
 */
function loadHotelsBySelectedOptions( allowRating ){
	var region = document.getElementById( "region" ).value;
	var location = document.getElementById( "moreOptionsArea" ).value;
	var rating = document.getElementById( "moreOptionsRatings" ).value;
	var accommodationTypesString = "";
	var accommodationTypes = document.getElementsByName("accommodationTypes");
	var counter = 0;
	for( var index = 0; index < accommodationTypes.length; index++ ){
		if( accommodationTypes[ index ].checked ){
			if( counter == 0 ){
				accommodationTypesString = accommodationTypes[ index ].id;
			} else {
				accommodationTypesString += "," + accommodationTypes[ index ].id;
			}
			counter++;
		}
	}
	
	var queryString = "lc=18";
	queryString += '&cityCode=' + region;
	queryString += '&location=' + location;
	if( isNull( allowRating)){
		queryString += '&rating=' + rating;
	}
	queryString += '&accommodationTypes='+accommodationTypesString;
	makeAjaxCall( 'leftContent.act', queryString, null, 'mainContent', 'callbackLoadHotelsBySelectedOptions', '' );	
}

function callbackLoadHotelsBySelectedOptions( hotelList,ratingList ){
	replaceOptions ( "moreOptionsHotels", hotelList );
	replaceOptions ( "moreOptionsRatings", ratingList )
}
/*****global variable section.*****/ 
var _productUid;
var _targetAct;
var _fromSearchResults;
var _cityUid;
var _tickingPriceTicker;
var _sightseeingDates;
var _itemUid;
var HOURS_ALLOWED_WITHOUT_EXTRA_CHARGE = 1;
var MINUTES_ALLOWED_WITHOUT_EXTRA_CHARGE = 59;
var _disableSearch = false;
var SUPER_PNR_SEARCH_FLOW = 2;

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() {
	showMessage(this.messageType, this.messageCode, this.message, 'dataContent');
	return true;
}

function loadSearchResults_2( fromBookingRecap ) {
	var queryString = 'sr=2';
	queryString += '&fromBookingRecap=' + fromBookingRecap;
	makeAjaxCall( 'searchResults.act', queryString, null, 'mainContent', 'callbackLoadSearchResults_2', '' );	
}

function callbackLoadSearchResults_2( isShowTripProtectionPopup ) {
	if( !showMessage(this.messageType, this.messageCode, this.message, 'dataContent')){
		if( !isNull( isShowTripProtectionPopup )){
			if(isShowTripProtectionPopup == "true"){
				loadTripProtectionPopup();
			}
			else{	
				createBooking();
			}
		}
	}
}

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() {
	showMessage(this.messageType, this.messageCode, this.message, '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(targetValue , message ) {
	if( !showMessage(this.messageType, this.messageCode, this.message, 'dataContent') ){
		disableElement( 'dataContent', false );
		var queryString;
		if (targetValue == 0){
			queryString = 'sr=1';
			if( !isNull( message ) && message != '' ){
				showGeneralMessage( message, 'dataContent' );
			}
		}	
		else {
			queryString = 'sr=2';
		}	
		makeAjaxCall( 'searchResults.act', queryString, null, 'mainContent', 'callbackAfterApplyChanges', '' );
	}
}

function callbackAfterApplyChanges(){
	showMessage(this.messageType, this.messageCode, this.message, '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, showTripProtection ) {
	if( cityCounter == -1 ){
		loadSearchResults_1();
	}else if( cityCounter == totalCities ){
		if (showTripProtection){
			loadTripProtectionPopup();
		}
		else{	
			createBooking();
		}	
	}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( isShowTripProtectionPopup ){
	if( !showMessage(this.messageType, this.messageCode, this.message, 'dataContent') && isShowTripProtectionPopup == "true" ){
		loadTripProtectionPopup();
	}
}

function validateHotelAndFlightSelection() {
	var queryString = 'sr=10';
	makeAjaxCall( 'searchResults.act', queryString, null, 'mainContent', 'callbackValidateHotelAndFlightSelection', '' );
}

function callbackValidateHotelAndFlightSelection( successfull, uid ,message ) {
	if( !showMessage(this.messageType, this.messageCode, this.message, 'dataContent') ) {
		if( successfull == 'false' ) {
			showWarningMessage( message, 'dataContent' );
			if( !isEmpty(uid) ) {
				chooseDifferentFlight( uid );
				scrollWindowTop();
			}
		} else {
			continueToSearchResults02();
		}
	}
}
function continueToSearchResults02() {
	var queryString = 'sr=9';
	makeAjaxCall( 'searchResults.act', queryString, null, 'mainContent', 'callbackLoadSearchResults_2', '' );
}

/*****************************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, null );	
}

function callbackChooseDifferentFlight() {
	showMessage(this.messageType, this.messageCode, this.message, 'dataContent' );
	loadTripSummary();
	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.messageType, this.messageCode, this.message, '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.messageType, this.messageCode, this.message, '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.messageType, this.messageCode, this.message, '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, -1, 204, false, true,  "");
	}
	

		
	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.messageType, this.messageCode, this.message, 'flightDetailsPopupDivContainer' );

	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 callbackChangeFlightItemAndLoadTripSummary() {
	showMessage(this.messageType, this.messageCode, this.message, 'dataContent' );
	loadCruiseTripSummary();
	return true;
}

function callbackChangeFlightItem() {
	showMessage(this.messageType, this.messageCode, this.message, 'dataContent' );
	return true;
}

function callbackChangeFlightItemFromDetails() {
	showMessage(this.messageType, this.messageCode, this.message, 'dataContent' );
	removeElement('flightDetailsPopupDivContainer'); 
	disableElement( 'dataContent', false );
	return true;
}

function callbackChangeFlightItemFromSeatMap() {
	removeElement('flightSeatMapPopupDiv'); 
	disableElement( 'dataContent', false );
	showMessage(this.messageType, this.messageCode, this.message, '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, -1, 204, false, true,  "tal popupDivSmall");

	}

	
	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);
}

function loadRecommendedFlightsPopup() {
	var parentDiv = getContainerDiv("recommendedHelpButton");
	var recommendedFlightsPopupDiv = recommendedFlightsPopupDiv = createPopupDiv('recommendedFlightsPopupDiv', 0, 0, 700, -1, 300, false, true,  "tal popupDivBig", parentDiv);
	disableElement(parentDiv, true);
	makeAjaxCall('search/recommendedFlightsPopup.jsp', 'recommends=true', null, 'recommendedFlightsPopupDiv', 'callbackLoadRecommendedFlightsPopup', '');	
}

function callbackLoadRecommendedFlightsPopup() {
	document.title = "Costco Travel";	
	showBlock('recommendedFlightsPopupDiv'); 
	positionBlockCentrally('recommendedFlightsPopupDiv');
}

function closeRecommendedFlightsPopup() {
	hideBlock("recommendedFlightsPopupDiv");
	disableElement(getPopupParent("recommendedFlightsPopupDiv"), false);
}

/*************************************hotel results section***********************************************/
function chooseDifferentHotel( productUid ) {
	var queryString = 'hr=11';
	queryString += '&uid=' + productUid;
	makeAjaxCall( 'hotelResults.act', queryString, null, 'rightContent', 'callbackChooseDifferentHotel', '' );
}

function callbackChooseDifferentHotel() {
	showMessage(this.messageType, this.messageCode, this.message, 'dataContent' );
	return true;
}

function sortHotelsByPrice( productUid, fromSearchResults , isAscendingOrder ) {
	var queryString = 'hr=3';
	queryString += '&uid=' + productUid;
	queryString += '&fromSearchResults=' + fromSearchResults;
	queryString += '&ascendingOrder=' + isAscendingOrder;
	makeAjaxCall( 'hotelResults.act', queryString, null, productUid, 'callbackSortHotelsByPrice', '' );
}

function callbackSortHotelsByPrice() {
	showMessage(this.messageType, this.messageCode, this.message, 'dataContent' );
	return true;
}

function sortHotelsByBestValue( productUid, fromSearchResults , isAscendingOrder ) {
	var queryString = 'hr=4';
	queryString += '&uid=' + productUid;
	queryString += '&fromSearchResults=' + fromSearchResults;
	queryString += '&ascendingOrder=' + isAscendingOrder;
	makeAjaxCall( 'hotelResults.act', queryString, null, productUid, 'callbackSortHotelsByBestValue', '' );
}

function callbackSortHotelsByBestValue() {
	showMessage(this.messageType, this.messageCode, this.message, 'dataContent' );
	return true;
}

function changeHotelItem( itemUid, productUid, fromSearchResults, targetActivity, isSuperPNRSearch ) {
	window.clearTimeout( _tickingPriceTicker );
	var queryString = 'hr=1';
	queryString += '&uid=' + itemUid;
	queryString += '&fromSearchResults=' + fromSearchResults;
	
	disableElement( 'dataContent', true );
	
	if( fromSearchResults || isSuperPNRSearch ) {
		var productSummaryInvokeInfo = getLoadProductSummaryInvokeInfo(targetActivity, productUid );
		makeMultiAjaxCall(new Array(
				new AsynchronousMultiRequestItem('hotelResults.act', queryString, null, productUid, "callbackChangeHotelItem"),
				new AsynchronousMultiRequestItem(productSummaryInvokeInfo[0], productSummaryInvokeInfo[1], null, productSummaryInvokeInfo[2], productSummaryInvokeInfo[3])
			   ), true);
	}else {
		makeAjaxCallWithWaitingDiv( 'hotelResults.act', queryString, null, productUid, 'callbackChangeHotelItem');
	}
}

function callbackChangeHotelItem() {
	disableElement( 'dataContent', false );
	showMessage(this.messageType, this.messageCode, this.message, 'dataContent' );
	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.messageType, this.messageCode, this.message, '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.messageType, this.messageCode, this.message, '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.messageType, this.messageCode, this.message, '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.messageType, this.messageCode, this.message, '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.messageType, this.messageCode, this.message, 'dataContent' );
	if( this.messageCode == null || this.messageCode == 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.messageType, this.messageCode, this.message, 'dataContent' );
	if( this.messageCode == null || this.messageCode == undefined ) {
		expandSubCategoriesOfRoom( _itemUid );
		_itemUid = null;
	}
	return true;
}

function displayItineraryRemarks( itineraryCode ) {
	var itineraryRemarksDivContainer = document.getElementById( 'itineraryRemarksDivContainer' );
	if( isNull( itineraryRemarksDivContainer ) ) {
		itineraryRemarksDivContainer = createPopupDiv('itineraryRemarksDivContainer', 0, 0, 450, -1, 200, false, true, 'popupDivSmall tal');
	}

	var queryString = 'hr=15';
	queryString += '&itineraryCode=' + itineraryCode;
	makeAjaxCall( 'hotelResults.act', queryString, null, 'itineraryRemarksDivContainer', 'callbackDisplayItineraryRemarks', '' );
}

function callbackDisplayItineraryRemarks() {
	showMessage(this.messageType, this.messageCode, this.message, 'dataContent' );
	showBlock( 'itineraryRemarksDivContainer' );
	positionBlockCentrally( 'itineraryRemarksDivContainer' );	
	disableElement( 'dataContent', true );
	return true;
}

/* function to check availability calendar.*/
function loadAllotmentCalendar( itemUid, disableSearch ) {
	var queryString = 'hr=16';
	queryString += '&uid=' + itemUid;
	_itemUid = itemUid;
	_disableSearch = disableSearch;
	makeAjaxCall( 'hotelResults.act', queryString, null, 'dataContent', 'callbackLoadAllotmentCalendar', '' );
}

function callbackLoadAllotmentCalendar(allotmentAvailability ) {
	if( showMessage(this.messageType, this.messageCode, this.message, '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, _disableSearch );
		disableElement( 'dataContent', true );
	}
	return true;
}

function selectHotelItem( productUid, hotelItemUid, fromSearchResults, targetActivity, searchFlow ) {
	window.clearTimeout( _tickingPriceTicker );
	var queryString = 'hr=19';	
	queryString += '&selectedHotelItemUid=' + hotelItemUid + '&fromSearchResults=' + fromSearchResults;
	
	disableElement( 'dataContent', true );
	
	if(fromSearchResults || ( searchFlow == SUPER_PNR_SEARCH_FLOW ) ) {
		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.messageType, this.messageCode, this.message, '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() {
	showMessage(this.messageType, this.messageCode, this.message, '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() {
	disableElement( 'dataContent', false );
	showMessage(this.messageType, this.messageCode, this.message, '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() {
	showMessage(this.messageType, this.messageCode, this.message, '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() {
	showMessage(this.messageType, this.messageCode, this.message, '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() {
   disableElement( 'dataContent', false );
   showMessage(this.messageType, this.messageCode, this.message, '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() {
	showMessage(this.messageType, this.messageCode, this.message, '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() {
	showMessage(this.messageType, this.messageCode, this.message, 'dataContent');
	return true;
}

function changeTransferItemForSuperPNR( transferDayTourId, cityUid ) {
	window.clearTimeout( _tickingPriceTicker );
	var queryString = 'trr=26';
	queryString += '&uid=' + cityUid;
	queryString += '&transferDayTourId=' + transferDayTourId;
	makeAjaxCall( 'transferResults.act', queryString, null, 'cruisePrePostAdditionalTransportationResultsDiv', 'callbackChangeTransferItemForSuperPNR', '' );
}

function callbackChangeTransferItemForSuperPNR( message, errorCode ) {
	showMessage(this.messageType, this.messageCode, this.message, '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() {
	showMessage(this.messageType, this.messageCode, this.message, 'dataContent');
	return true;
}

function clearTransferSelectionForCity( cityUid, displayCarFirst ) {
	window.clearTimeout( _tickingPriceTicker );
	var queryString = 'trr=28';
	queryString += '&uid=' + cityUid;
	queryString += '&displayCarFirst=' + displayCarFirst;
	makeAjaxCall( 'transferResults.act', queryString, null, cityUid, 'callbackClearTransferSelectionForCity', '' );
}

function callbackClearTransferSelectionForCity() {
	showMessage(this.messageType, this.messageCode, this.message, 'dataContent');
	return true;
}

function clearCarItemSelection( productUid, displayCarFirst ) {
	window.clearTimeout( _tickingPriceTicker );
	var queryString = 'trr=29';
	queryString += '&uid=' + productUid;
	queryString += '&displayCarFirst=' + displayCarFirst;
	makeAjaxCall( 'transferResults.act', queryString, null, productUid, 'callbackClearCarItemSelection', '' );
}

function callbackClearCarItemSelection() {
	showMessage(this.messageType, this.messageCode, this.message, 'dataContent');
	return true;
}

function reLoadTransportation( cityUid, displayCarFirst, previousPickupTime, previousDropoffTime, isPickupTime, isPickupAndDropoffOnSameDay ) {
	clearErrorElements();
	var pickupTimeField = document.getElementById( "pickupTime" );
	var dropoffTimeField = document.getElementById( "dropoffTime" );
	
	 /*
     * We are providing drop downs to select the values of pickupTime or dropoffTime 
	 * whenever flights are not available in the vacation packages ( intercity or round 
	 * trip fligts options selected ). If the pickupTime drop down is not available, we 
	 * are taking previousPickupTime. If the dropoffTime drop down is not available, 
	 * we are taking previousDropoffTime. So, we are using isPickupTime flag to determine
	 *  the availability of either pickupTime or  dropoffTime ( TFS: 8039 ).
    */	
    	
	var pickupTime = ( isPickupTime )? pickupTimeField.value : previousPickupTime;
	var dropoffTime = !( isPickupTime )? dropoffTimeField.value : previousDropoffTime ;
	
	if( ( pickupTime != "-1" ) && ( dropoffTime != "-1" ) ) {
		//Changes for #8475 task.
		if( !validateSameDayCarPickupAndDropoffTime( pickupTime, dropoffTime, isPickupTime, isPickupAndDropoffOnSameDay ) ) {
			return false;
		}
		if( ( isPickupAndDropoffOnSameDay ) || ( 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 {
			if( isPickupTime ) {
				pickupTimeField.value = previousPickupTime;
			} else {
				dropoffTimeField.value = previousDropoffTime;
			}
		}
	} else {
		showErrorMessage( 'Please select a pick-up/drop-off time', 'dataContent' );
		return false;
	}
}

function callbackReLoadTransportation() {
	disableElement( 'dataContent', false );
	showMessage(this.messageType, this.messageCode, this.message, '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() {
	showMessage(this.messageType, this.messageCode, this.message, '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() {
	showMessage(this.messageType, this.messageCode, this.message, '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() {
	showMessage(this.messageType, this.messageCode, this.message, '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() {
	showMessage(this.messageType, this.messageCode, this.message, '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() {
	showMessage(this.messageType, this.messageCode, this.message, '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() {
	disableElement( 'dataContent', false );
	showMessage(this.messageType, this.messageCode, this.message, '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() {
	disableElement( 'dataContent', false );

	showMessage(this.messageType, this.messageCode, this.message, '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() {
	disableElement( 'dataContent', false );
	showMessage(this.messageType, this.messageCode, this.message, '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() {
	showMessage(this.messageType, this.messageCode, this.message, 'dataContent');
	return true;
}

function sortToursByDescription( cityUid ) {
	var queryString = 'tr=11';
	queryString += '&uid=' + cityUid;
	makeAjaxCall( 'tourResults.act', queryString, null, cityUid, 'callbackToursByDescription', '' );
}

function callbackToursByDescription() {
	showMessage(this.messageType, this.messageCode, this.message, 'dataContent');
	return true;
}
/*********************************** ticket results section ***************************************/
function customizeTickets( productUid ) {
	_productUid = productUid;
	var queryString = 'tir=1';
	queryString += '&uid=' + productUid;
	queryString += "&selectedPassengerIndex=0";
	makeAjaxCall( 'ticketResults.act', queryString, null, 'rightContent', 'callbackCustomizeTickets', '' );
}

function callbackCustomizeTickets() {
	showMessage(this.messageType, this.messageCode, this.message, 'dataContent' );
	loadTicketSummaryBlock( _productUid, true );
	_productUid = null;
	scrollWindowTop();
	return true;
}

function loadTicketSummaryBlock( productUid, isHighlightBlock ) {
	var queryString = 'tir=12';
	queryString += '&uid=' + productUid;
	queryString += '&highlightedProduct=' + isHighlightBlock;
	makeAjaxCall( 'ticketResults.act', queryString, null, "summary_" + productUid, 'callbackLoadTicketSummaryBlock', '' );
}

function callbackLoadTicketSummaryBlock() {
	showMessage(this.messageType, this.messageCode, this.message, 'dataContent' );
	return true;
}

function clearTicketSelection( ticketCategoryItemUid, passengerIndex ) {
	showHidePassengerDetails( ticketCategoryItemUid, false );
	if( isNull( passengerIndex ) ) {
		var queryString = "tir=7";
		queryString += "&uid=" + ticketCategoryItemUid;
		makeAjaxCall( 'ticketResults.act', queryString, null, ticketCategoryItemUid, 'callbackClearTicketSelection', '' );
	} else {
		var queryString = "tir=8";
		queryString += "&uid=" + ticketCategoryItemUid;
		queryString += "&selectedPassengerIndex=" + passengerIndex;
		makeAjaxCall( 'ticketResults.act', queryString, null, ticketCategoryItemUid, 'callbackClearTicketSelection', '' );
	}
}

function callbackClearTicketSelection() {
}

function selectDefaultTicketsForAllPassengers( ticketCategoryItemUid ) {
	var queryString = "tir=9";
	queryString += "&uid=" + ticketCategoryItemUid;
	makeAjaxCall( 'ticketResults.act', queryString, null, ticketCategoryItemUid, 'callbackShowCommonTicketSelection', '' );
}

function callbackShowCommonTicketSelection() {
}

function showCustomizedTicketSelection( ticketCategoryItemUid, passengerIndex, numberOfPassengers ) {
	showHidePassengerDetails( ticketCategoryItemUid, true );
	if( ( passengerIndex >= 0 ) && ( passengerIndex < numberOfPassengers ) ) {
		document.getElementById( "passenger_" + ticketCategoryItemUid + "_" + passengerIndex ).checked = true;

		for( var i = 0 ; i < numberOfPassengers ; i++ ) {
			document.getElementById( "passengerRow_" + ticketCategoryItemUid + "_" + i ).className = "";
			document.getElementById( "removeTicketButton_" + ticketCategoryItemUid + "_" + i ).style.display = "none";
		}
		document.getElementById( "passengerRow_" + ticketCategoryItemUid + "_" + passengerIndex ).className = "bgc16";
		document.getElementById( "removeTicketButton_" + ticketCategoryItemUid + "_" + passengerIndex ).style.display = "block";

		var queryString = "tir=6";
		queryString += "&uid=" + ticketCategoryItemUid;
		queryString += "&selectedPassengerIndex=" + passengerIndex;
		makeAjaxCall( 'ticketResults.act', queryString, null, ( "ticketSelectionGrid_" + ticketCategoryItemUid ), 'callbackShowCustomizedTicketSelection', '' );
	}
}

function callbackShowCustomizedTicketSelection() {
}

function showHidePassengerDetails( ticketCategoryItemUid, showDetails ) {
	document.getElementById( "passengerDetails_" + ticketCategoryItemUid ).style.display = showDetails ? "block" : "none";
}

function selectTicketForPassenger( ticketCategoryItemUid, rateCode, ticketDay, passengerIndex ) {
	if( passengerIndex >= 0 ) {
		var queryString = "tir=11";
		queryString += "&uid=" + ticketCategoryItemUid;
		queryString += "&rateCode=" + rateCode;
		queryString += "&day=" + ticketDay;
		queryString += "&selectedPassengerIndex=" + passengerIndex;
	} else {
		var queryString = "tir=10";
		queryString += "&uid=" + ticketCategoryItemUid;
		queryString += "&rateCode=" + rateCode;
		queryString += "&day=" + ticketDay;
		queryString += "&selectedPassengerIndex=" + passengerIndex;
	}		
	makeAjaxCall( 'ticketResults.act', queryString, null, ticketCategoryItemUid, 'callbackSelectTicketForPassenger', '' );
}

function callbackSelectTicketForPassenger() {
}

/***********************************package summary(lef content) section ***************************************/
function loadTripSummary( isCruiseFlow ) {
	var queryString = 'lc=1';
	if( ( _productUid != null ) && ( _productUid != undefined ) && ( _productUid != "" ) ) {
		queryString += "&highlightedProductUid=" + _productUid;
	}
	if( ( isCruiseFlow != null ) && ( isCruiseFlow != undefined )  ) {
		queryString += "&cruiseFlow=" + isCruiseFlow;
	}
	makeAjaxCall( 'leftContent.act', queryString, null, 'leftContent', 'callbackLoadTripSummary', '' );
}

function callbackLoadTripSummary() {
	showMessage(this.messageType, this.messageCode, this.message, '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";
	} else if( targetActivity.indexOf( "tir" ) != -1 ) {
		targetAct = "ticketResults.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.messageType, this.messageCode, this.message, '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() {
	showMessage(this.messageType, this.messageCode, this.message, 'dataContent');
	_cityUid = "";
	return true;
}

function loadSuperPNRTransportationTripSummary( commaSeparatedCityUids, highlightedProduct ) {
	var transportationSummaryArray = new Array();
	var cityUidsArray = commaSeparatedCityUids.split( "," );
	for ( var cityIndex = 0; cityIndex < cityUidsArray.length; cityIndex++ ) {
		var queryString = 'trr=15';
		var cityUid = cityUidsArray [ cityIndex ];
		if ( cityUid != null && cityUid != '' ) {
			queryString += '&uid=' + cityUid;
			queryString += '&highlightedProduct=' + highlightedProduct;
			transportationSummaryArray [ cityIndex ] = new AsynchronousMultiRequestItem( 'transferResults.act' , queryString , null , 'transportationSummary_' + cityUid , "callbackLoadSuperPNRTransportationTripSummary" );
		}
	}
	makeMultiAjaxCall( transportationSummaryArray , true );
}

function callbackLoadSuperPNRTransportationTripSummary() {
	if ( !showMessage(this.messageType, this.messageCode, this.message , 'dataContent' ) ) {
		_cityUid = "";
	}
}

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.messageType, this.messageCode, this.message, '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.messageType, this.messageCode, this.message, '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() {
	showMessage(this.messageType, this.messageCode, this.message, '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.messageType, this.messageCode, this.message, '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() {
	showMessage(this.messageType, this.messageCode, this.message, '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, -1, 200, false, true,  "tal popupDivBig");
		tripProtectionPopupDivContainer.onkeypress = function( event ) { onKeyDownOnTripProtectionPopup(event); };
	}
	
	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 ) {
	if( !isEmpty( message ) ) {
		showErrorMessage( message, 'dataContent' );
		return false;
	}
	showMessage(this.messageType, this.messageCode, this.message, '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(packagePrice ) {
	if(!showMessage(this.messageType, this.messageCode, this.message, 'tripProtectionPopupDivContainer')) {
		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.messageType, this.messageCode, this.message, '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.messageType, this.messageCode, this.message, '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.messageType, this.messageCode, this.message, '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.messageType, this.messageCode, this.message, '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() {
	showMessage(this.messageType, this.messageCode, this.message, '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() {
	showMessage(this.messageType, this.messageCode, this.message, '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() {
	showMessage(this.messageType, this.messageCode, this.message, '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() {
	showMessage(this.messageType, this.messageCode, this.message, '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, isPickupTime, isPickupAndDropoffOnSameDay ) {
	window.clearTimeout( _tickingPriceTicker );
	clearErrorElements();
	var pickupTimeField = document.getElementById( "pickupTime" );
	var dropoffTimeField = document.getElementById( "dropoffTime" );
    
     /*
     * We are providing drop downs to select the values of pickupTime or dropoffTime 
	 * whenever flights are not available in the vacation packages ( intercity or round 
	 * trip fligts options selected ). If the pickupTime drop down is not available, we 
	 * are taking previousPickupTime. If the dropoffTime drop down is not available, 
	 * we are taking previousDropoffTime. So, we are using isPickupTime flag to determine
	 *  the availability of either pickupTime or  dropoffTime ( TFS: 8039 ).
    */	
    	
	var pickupTime = ( isPickupTime )? pickupTimeField.value : previousPickupTime;
	var dropoffTime = !( isPickupTime )? dropoffTimeField.value : previousDropoffTime ;

	if( ( pickupTime != "-1" ) && ( dropoffTime != "-1" ) ) {
		//Changes for #8475 task.
		if( !validateSameDayCarPickupAndDropoffTime( pickupTime, dropoffTime, isPickupTime, isPickupAndDropoffOnSameDay ) ) {
			return false;
		}
		//If pick up date and drop off date is same message display is not required.
		//Changes for #8475 task.
		if( ( isPickupAndDropoffOnSameDay ) || ( 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 {
			if( isPickupTime ) {
				pickupTimeField.value = previousPickupTime;
			} else {
				dropoffTimeField.value = previousDropoffTime;
			}
		}
	} else {
		showErrorMessage( 'Please select a pick-up/drop-off time', 'dataContent' );
		return false;
	}
}
/*
 * validateSameDayCarPickupAndDropoffTime(..) method to validate whether both pick up time and drop off time selected appropriately for 
 * the same day car( Both Pick up and Drop-off Date is same ).
 * 
 */
function validateSameDayCarPickupAndDropoffTime( pickupTime, dropoffTime, isPickupTime, isPickupAndDropoffOnSameDay ) {
	
	if( isPickupAndDropoffOnSameDay ) {
		var pickupHours = getHoursFromTime( pickupTime );
		var dropoffHours = getHoursFromTime( dropoffTime );
		//If pick Time is more or same as drop off time, display a message to user.
		// otherwise drop-off time is less or same as pickup time, display a message to user.
		//Changes for #8475 task.
		if( isPickupTime ) {
			var numberOfHours = pickupHours - dropoffHours;
			if( numberOfHours >= 0 ) {
				showErrorMessage('Please select Pickup Time before the Drop-off Time.', 'dataContent', 'pickupTime', '1px solid #7f9db9');
				return false;
			}
		} else {
			var numberOfHours = dropoffHours - pickupHours;
			if( numberOfHours <= 0 ) {
				showErrorMessage('Please select Drop-off Time later than Pickup Time.', 'dataContent', 'dropoffTime', '1px solid #7f9db9');
				return false;
			}
		}
	}
	return true;
}

function showConfirmMessageForCar( pickupTime, dropoffTime ){
	var pickupHours = getHoursFromTime( pickupTime );
	var dropoffHours = getHoursFromTime( dropoffTime );
	var numberOfHours = dropoffHours - pickupHours;
	var numberOfMinutes = (numberOfHours * 60);
	if( numberOfHours > HOURS_ALLOWED_WITHOUT_EXTRA_CHARGE ||	numberOfMinutes > MINUTES_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() {
	disableElement( 'dataContent', false );
	showMessage(this.messageType, this.messageCode, this.message, 'dataContent');
	loadTransportationTripSummary( _cityUid, false );
	return true;
}

function applyTicketChanges( productUid, cityCounter ) {
	clearErrorElements();
	disableElement( 'dataContent', true );
	window.clearTimeout( _tickingPriceTicker );
	_productUid = productUid;

	window.scroll( 0, 0 );
	var queryString = 'tir=13';
	queryString += '&uid=' + productUid;
	queryString += '&cityCounter=' + cityCounter;
	makeAjaxCall( 'ticketResults.act', queryString, null, 'rightContent', 'callbackApplyTicketChanges', '' );
}

function callbackApplyTicketChanges( errorMessage ) {
	disableElement( 'dataContent', false );

	if( showMessage(this.messageType, this.messageCode, this.message, 'dataContent') ) {
		_productUid = null;
		return false;
	}
	if( !isEmpty( errorMessage ) ) {
		showErrorMessage( errorMessage, 'dataContent' );
		_productUid = null;
		return false;
	}
	loadTicketSummaryBlock( _productUid, false );
	_productUid = null;
	return true;
}

function updateFlightHeader( selectedFlightAmount ){
	selectedFlightAmount = parseFloat( selectedFlightAmount );
	if( document.getElementById( "noOfAirLines" ) != null  ){
		var noOfAirLines = parseFloat( document.getElementById( "noOfAirLines" ).value );
		for( var index = 0; index < noOfAirLines ;index++ ){
			var airLineAmount = parseFloat( document.getElementById( "airLineAmount"+index ).value);
			if( selectedFlightAmount > airLineAmount ){
				document.getElementById( "airLineAmountMessage"+index ).innerHTML = "Subtract " + formatCurrency( parseFloat( selectedFlightAmount - airLineAmount ).toFixed( 2 )) ;
			}else if( selectedFlightAmount < airLineAmount ){
					document.getElementById( "airLineAmountMessage"+index ).innerHTML = "Add "+ formatCurrency( parseFloat( airLineAmount - selectedFlightAmount ).toFixed( 2 )) ;
			}else{
				document.getElementById( "airLineAmountMessage"+index ).innerHTML = "No Change";
			}
		}
	}
}
function loadPreviousSearchResults( cityCounter ){
	if( cityCounter == -1 ){
		loadSearchResults_1();
	}else{
		var queryString = 'rc=32';
		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', 'callbackPreviousSearchResults', trackingText );
	}
}
function callbackPreviousSearchResults( ){
	showMessage(this.messageType, this.messageCode, this.message, 'dataContent');
	return true;
}

function updateCarCount( cityUid,productUid, displayCarFirst,cityCounter ){
	var numberOfCars = document.getElementById( "numberOfCars" ).value
	var queryString = 'trr=30';
	queryString += '&uid=' + productUid;
	queryString += '&displayCarFirst=' + displayCarFirst;
	queryString += '&displaySelectedItemsOnly=false';
	queryString += '&numberOfCars=' + numberOfCars;
	queryString += '&cityCounter=' + cityCounter;
	makeAjaxCall( 'transferResults.act', queryString, null, cityUid, 'callbackUpdateCarCount', '' );
}

function callbackUpdateCarCount(){
	showMessage(this.messageType, this.messageCode, this.message, 'dataContent');
}/*-- global variables section --*/
var _type;
var _itemUid;
var _cruiseAmenitiesId;

/* This method show cruise results in single page as pagination. */
function showCruiseResultsPage ( pagination, pageIndex ) {
	topPagination._selectedPage = pageIndex;
	bottomPagination._selectedPage = pageIndex;
	var queryString = "csr=2";
	queryString += "&selectedPage=" + pageIndex;
	queryString += "&callerPage=SAILING_RESULTS";
	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.messageType, this.messageCode, this.message , 'dataContent' ) ) {
		disableElement ( "dataContent" , false );
		topPagination.loadPaginationDivs ();
		bottomPagination.loadPaginationDivs ();
		scrollWindowTop("scrollablePageContent");
	}
}

/* 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.messageType, this.messageCode, this.message , '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, callerPage, isMember, destination, cruiseLine, ship, departureDate ) {
	createPopupDiv ( "memberBenefitsPopupDivContainer" , -1 , -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);
	}	

	var trackingText = null;
	if(!isEmpty(_cruisePackageId)) {
		var packageType = "searchPackage";
		var pagePrefix = "sailing";
		if( !isNull(callerPage) && ( callerPage == "CATEGORY_RESULTS" ) ) {
			packageType = "bookingPackage";
			pagePrefix = "category";
		}
		trackingText = '/cr/booking/' + packageType + '/' + pagePrefix + (isMember ? '' : 'Non')+ 'MemberAddedValues/' + _cruisePackageId + '/' + year + month + day;
	} else {
		var widgetType = "searchWidget";
		var pagePrefix = "sailing";
		if( !isNull(callerPage) && ( callerPage == "CATEGORY_RESULTS" ) ) {
			widgetType = "bookingWidget";
			pagePrefix = "category";
		}
		trackingText = '/cr/booking/' + widgetType + '/' + pagePrefix + (isMember ? '' : 'Non')+ 'MemberAddedValues/' + destination + '/' + cruiseLine + '/' + ship + '/' + year + month + day;
	}

	var queryString = "";
	if( !isNull(callerPage) && ( callerPage == "CATEGORY_RESULTS" ) ) {
		queryString = "ccr=3";
		queryString += "&uid=" + itemUid;
		queryString += "&type=" + type;
		makeAjaxCall ( 'cruiseCategoryResults.act' , queryString, null , 'memberBenefitsPopupDivContainer' , 'callbackShowMemberBenefitsPopup' , trackingText );
	} else {
		queryString = "csr=4";
		queryString += "&cruiseSailingItemUid=" + itemUid;
		queryString += "&type=" + type;
		if( cruiseAmenitiesId != null && cruiseAmenitiesId != undefined ) {
			queryString += "&cruiseAmenitiesId=" + cruiseAmenitiesId;
		}
		if( !isEmpty( callerPage ) ) {
			queryString += "&callerPage=" + callerPage;
		}
		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.messageType, this.messageCode, this.message , "memberBenefitsPopupDivContainer" ) ) ) {
		showBlock ( "memberBenefitsPopupDivContainer" );
		positionBlockCentrally ( "memberBenefitsPopupDivContainer" );
		disableElement ( "dataContent" , true );
		document.getElementById("membershipNumber").focus();
	}
}

function showCruiseSailingDetails( cruiseSailingItemUid, selectedTab, backgroundDivId, searchType, destination, cruiseLine, ship, departureDate ) {
	var callbackFunctionParams = new Array();
	callbackFunctionParams.push( backgroundDivId );
	
	if(!$("detailedItineraryPopupDivContainer")) {
		createPopupDiv ( "detailedItineraryPopupDivContainer", -1, -1, -1, -1, 200 , false, true, "");
	}
	
	disableElement ( backgroundDivId, true );

	var queryString = "csr=1";
	queryString += "&cruiseSailingItemUid=" + cruiseSailingItemUid;
	queryString += "&selectedTab=" + selectedTab;
	queryString += "&searchType=" + searchType;
	
	var trackingText = null;
	var year = '';
	var month = '';
	var day = '';
	var widgetType = null;
	if (departureDate){
		year = departureDate.substring(departureDate.length - 4, departureDate.length);
		month = departureDate.substring(0, 2);
		day = departureDate.substring(3, 5);
	}
	if( !isEmpty(searchType) ) {
		if (searchType == 'sailing'){
			if(!isEmpty(_cruisePackageId)) {
				widgetType = "searchPackage";
			} else {
				widgetType = "searchWidget";
			}
		}
		else if (searchType == 'category'){
			if(!isEmpty(_cruisePackageId)) {
				widgetType = "bookingPackage";
			} else {
				widgetType = "bookingWidget";
			}
		}
	} else {
		searchType = "sailing";
		if(!isEmpty(_cruisePackageId)) {
			widgetType = "searchPackage";
		} else {
			widgetType = "searchWidget";
		}
	}
	
	var popupType = "";
	if (selectedTab == 0){
		popupType = 'PopupItinerary';
	} 
	else if (selectedTab == 1){
		popupType = 'PopupOverview';
	}	
	else if (selectedTab == 2){
		popupType = 'PopupActivities';
	}	
	else if (selectedTab == 3){
		popupType = 'PopupTourHighlights';
	}	
	
	trackingText = '/cr/booking/' + widgetType + '/' +  searchType + popupType;
	
	if(!isEmpty(_cruisePackageId)) {
		trackingText += (_cruisePackageId) ? ('/' + _cruisePackageId) : '';
		trackingText += (departureDate) ? ('/' + year + month + day) : '';
	} else {
		trackingText += (destination) ? ('/' + destination) : '';
		trackingText += (cruiseLine) ? ('/' + cruiseLine) : '';
		trackingText += (ship) ? ('/' + ship) : '';
		trackingText += (departureDate) ? ('/' + year + month + day) : '';
	}

	makeAjaxCallWithWaitingDiv ( "cruiseSailingResults.act" , queryString , null , "detailedItineraryPopupDivContainer" , "callbackShowCruiseSailingDetails", callbackFunctionParams, trackingText );
}

function callbackShowCruiseSailingDetails( backgroundDivId ) {
	disableElement ( backgroundDivId, false );

	if ( !( showMessage(this.messageType, this.messageCode, this.message , backgroundDivId ) ) ) {
		disableElement( "dataContent", true );
		showBlock ( "detailedItineraryPopupDivContainer" );
		positionBlockCentrally ( "detailedItineraryPopupDivContainer" );
	}
}

function showCruiseRatingPopup (destination, cruiseLine, ship, departureDate) {
	createPopupDiv ( "cruiseRatingPopupDivContainer", -1, -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);
	}	

	var trackingText = null;
	if(!isEmpty(_cruisePackageId)) {
		trackingText = '/cr/booking/searchPackage/sailingStarRating/' + _cruisePackageId + '/' + year + month + day;
	} else {
		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, callerPage, cruiseAmenitiesId, event, isKeyEvent, departureDate ) {
	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;
	_cruiseAmenitiesId = cruiseAmenitiesId;
	_departureDate = departureDate;
	var queryString = 'md=11';
	queryString += '&membershipNumber=' + membershipNumber;

	var callbackFunctionParams = new Array();
	callbackFunctionParams.push( callerPage );

	disableElement ( "memberBenefitsPopupDivContainer" , true );
	makeAjaxCallWithWaitingDiv ( 'membershipDetail.act' , queryString , null , null , 'callbackVerifyMembershipNumber', callbackFunctionParams );
}

function callbackVerifyMembershipNumber (callerPage) {
	if ( ! ( showMessage(this.messageType, this.messageCode, this.message , 'memberBenefitsPopupDivContainer' ) ) ) {
		disableElement ( "memberBenefitsPopupDivContainer" , false );
		callerPage = trim ( callerPage ).toUpperCase();
		var callbackFunctionParams = new Array();
		callbackFunctionParams.push( callerPage );
		disableElement ( "memberBenefitsPopupDivContainer" , true );
		if ( callerPage == 'SAILING_RESULTS' ) {
			var queryString = "rc=27";
			makeAjaxCallWithWaitingDiv ( 'rightContent.act' , queryString , null,'rightContent' , 'showUpdatedMemberBenefitsPopup', callbackFunctionParams );
		} else if ( callerPage == 'CATEGORY_RESULTS' ) {
			var queryString = "ccr=0";
			makeAjaxCallWithWaitingDiv ( 'cruiseCategoryResults.act' , queryString , null,'rightContent' , 'showUpdatedMemberBenefitsPopup', callbackFunctionParams );
		} else if( callerPage == 'CRUISE_PACKAGE' ) {
			var queryString = "pc=10";
			makeAjaxCallWithWaitingDiv ( 'packageContent.act' , queryString , null,'cruisePackageLeadinPricesDiv' , 'showUpdatedMemberBenefitsPopup', callbackFunctionParams );
		}
	}
}

function showUpdatedMemberBenefitsPopup (callerPage) {
	if ( ! ( showMessage(this.messageType, this.messageCode, this.message , 'dataContent' ) ) ) {
		disableElement ( "memberBenefitsPopupDivContainer" , false );
		var formattedDate = '';
		if( !isEmpty(_departureDate)) {
			formattedDate = _departureDate.substring(4, 6) + "/" + _departureDate.substring(6, 8) + "/" + _departureDate.substring(0, 4);
		}
		if( _cruiseAmenitiesId != '' ) {
			showMemberBenefitsPopup( _itemUid , _type , _cruiseAmenitiesId, callerPage, true, _destinationName, _cruiseLineName, _shipName, formattedDate );
		} else {
			showMemberBenefitsPopup( _itemUid , _type , null, callerPage, true, _destinationName, _cruiseLineName, _shipName, formattedDate );
		}
	}
}

function loadMemberVerificationPopup(callerPage, cruiseSailingItemUid, destination, cruiseLine, ship, departureDate) {
	createPopupDiv ( "memberVerificationDivContainer", -1, -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);
	}	

	var queryString = "csr=7";
	queryString += "&cruiseSailingItemUid=" + cruiseSailingItemUid;
	queryString += "&callerPage=" + callerPage;
	var trackingText = null;
	if(!isEmpty(_cruisePackageId)) {
		trackingText = '/cr/booking/searchPackage/sailingMemberVerification/' + _cruisePackageId + '/' + year + month + day;
	} else {
		trackingText = '/cr/booking/searchWidget/sailingMemberVerification/' + destination + '/' + cruiseLine + '/' + ship + '/' + year + month + day;
	}
	makeAjaxCall ( 'cruiseSailingResults.act' , queryString, null , 'memberVerificationDivContainer' ,
			'callbackLoadMemberVerificationPopup' , trackingText, '' );
}

function callbackLoadMemberVerificationPopup() {
	showBlock ( "memberVerificationDivContainer" );
	positionBlockCentrally ( "memberVerificationDivContainer" );
	document.getElementById("membershipNumber").select();
}

function loadCruiseResultsOnValidMembership( event, isKeyEvent, cruiseSailingItemUid , destination, cruiseLine, ship, departureDate, callerPage ) {
	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 += '&callerPage=' + callerPage;
	queryString += '&cruiseSailingItemUid=' + cruiseSailingItemUid;
	
	//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);
	}	

	var targetDivId = "cruiseSailingResultsDiv";
	if( callerPage == 'CRUISE_PACKAGE' ) {
		targetDivId = "cruisePackageLeadinPricesDiv";
	}
	makeAjaxCallWithWaitingDiv( 'membershipDetail.act', queryString, null, targetDivId, 'callbackLoadCruiseResultsOnValidMembership' );
}

function callbackLoadCruiseResultsOnValidMembership() {
	if ( !( showMessage(this.messageType, this.messageCode, this.message , 'memberVerificationDivContainer' ) ) ) {
		disableElement( 'memberVerificationDivContainer', false );
		hideBlock( 'memberVerificationDivContainer' );
		disableElement( 'dataContent', false);
		isScrollWindowDown = true;
	}
}

function proceedToPassengerDetailPage( cruiseSailingItemUid, destination, cruiseLine, ship, departureDate ) {
	isScrollWindowDown = false;
	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);
	}	

	var trackingText = null;
	if(!isEmpty(_cruisePackageId)) {
		trackingText = '/cr/booking/bookingPackage/passengerInfo/' + _cruisePackageId + '/' + year + month + day;
	} else {
		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.messageType, this.messageCode, this.message , 'dataContent' ) ) ) {
		disableElement ( "dataContent" , false );
	}
	setSupportPhoneNumber(supportPhoneNumber);
}

function loadCruiseResultsOrLandingPage( fromPackageLandingPage, cruiseLineCode, shipCode, packageId ) {
	if( fromPackageLandingPage ) {
		loadRightContentCruisePackage(cruiseLineCode, shipCode, packageId);
	} else {
		var queryString = "lc=13&lbc=2&rc=27";
		disableElement ( "dataContent" , true );
		makeAjaxCallWithWaitingDiv( 'mainContent.act', queryString, null, 'mainContent', 'callbackLoadCruiseResults' );
	}
}

function callbackLoadCruiseResults() {
	if ( !( showMessage(this.messageType, this.messageCode, this.message , 'dataContent' ) ) ) {
		disableElement ( "dataContent" , false );
	}
	setSupportPhoneNumber(bookingPhoneNumber);
}

function displayPortOfCallInfo(locationId, portOfCallsLink){
	portOfCallsLink = $(portOfCallsLink);
	var parentDiv = getContainerDiv(portOfCallsLink);
	createPopupDiv( "portOfCallInfoPopupDiv", -1, -1, -1, -1, 210, false, true, "", parentDiv);
	
	var queryString = "csr=15";
	queryString += "&locationId=" + locationId;
	disableElement(parentDiv, true );
	makeAjaxCallWithWaitingDiv("cruiseSailingResults.act", queryString, null, "portOfCallInfoPopupDiv", "callbackDisplayPortOfCallInfo", [parentDiv]);
}

function callbackDisplayPortOfCallInfo(parentDiv){
	disableElement (parentDiv, false );
	if ( !( showMessage(this.errorType, this.errorCode, this.errorMessage , parentDiv ) ) ) {
		disableElement( parentDiv, true );
		showBlock ( "portOfCallInfoPopupDiv" );
		positionBlockCentrally ( "portOfCallInfoPopupDiv" );
	}
}

function hidePortOfCallInfoPopup(){
	var parentDiv = getPopupParent("portOfCallInfoPopupDiv");
	hideBlock("portOfCallInfoPopupDiv");
	disableElement(parentDiv, false );
}

function switchMenuItem(menuItem){
	if (menuItem == "Overview"){
		document.getElementById("overviewMenuItem").className = "tab-sel01";
		document.getElementById("factsMenuItem").className = "tab01";
		document.getElementById("overviewPage").style.display = "";
		document.getElementById("factsPage").style.display = "none";
	}
	else if (menuItem == "Facts"){
		document.getElementById("overviewMenuItem").className = "tab01";
		document.getElementById("factsMenuItem").className = "tab-sel01";
		document.getElementById("factsPage").style.display = "";
		document.getElementById("overviewPage").style.display = "none";
	}	
}

function displayPortOfCallMap(mapUrl){
	document.getElementById("portOfCallMap").src = mapUrl;
}

function displayPortOfCallImage(imageUrl, imageDescription){
	document.getElementById("portOfCallImage").src = imageUrl;
	document.getElementById("imageDescription").innerHTML = imageDescription;
}

function showCruiseTourLegend() {
	createPopupDiv( "cruiseTourLegendDivContainer", -1, -1, -1, -1, 200, false , true , "" );
	disableElement( "dataContent" , true );

	makeAjaxCall( 'cruiseSailingResults.act' , "csr=18" , null , 'cruiseTourLegendDivContainer' , 'callbackShowCruiseTourLegend' );
}

function callbackShowCruiseTourLegend() {
	showBlock( "cruiseTourLegendDivContainer" );
	positionBlockCentrally( "cruiseTourLegendDivContainer" );
}
var _allCruiseLines;

function cruiseDestinationOnChange() {
	var destinationCode = document.getElementById ( "cruiseDestination" ).value;
	var cruiseOnlySearch = document.getElementById( "cruiseOnlySearch" ).checked;
	var queryString = "";
	queryString += "lc=8";
	queryString += '&destinationCode=' + destinationCode;
	queryString += '&cruiseOnlySearch=' + cruiseOnlySearch;
	trackEvent('Search Cruise', 'Destination', ((destinationCode != "") ? destinationCode : "Any"));
	
	makeAjaxCall ( 'leftContent.act', queryString, null, null, 'callbackCruiseDestinationOnChange', '' );
}

function callbackCruiseDestinationOnChange( regions, cruiseLinesList, departuresList, portsList ) {
	document.getElementById("regionList").innerHTML = regions;

	replaceOptions ( "cruiseLine", cruiseLinesList );
	document.getElementById ( "cruiseLine" ) [ 0 ].text = "Any";

	replaceOptions ( "departureDate", departuresList );

	replaceOptions ( "portOfEmbarkation", portsList );

	document.getElementById ( "cruiseShips" ).length = 1;
	document.getElementById ( "cruiseShips" ) [ 0 ].text = "Any";
}

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;
		var tourCodeField = document.getElementById ( "tourCode" );
		if(!isNull(tourCodeField)) {
			tourCodeField[ 0 ].selected = true;
		}

		var tourTypeField = document.getElementById ( "tourType" );
		if(!isNull(tourTypeField)) {
			tourTypeField[ 0 ].selected = true;
		}
	} else {
		document.getElementById ( "moreSearchOptionBlock" ).style.display = "block";
	}
	
	trackEvent("Search Cruise", "More Options", "Click");
}

function loadCruiseShipsAndPorts() {
	var destinationCode = document.getElementById( "cruiseDestination" ).value;
	var cruiseLine = document.getElementById( "cruiseLine" ).value;
	var cruiseOnlySearch = document.getElementById( "cruiseOnlySearch" ).checked;
	var queryString = "lc=9&destinationCode=" + destinationCode;
	queryString += "&cruiseLineCodes=" + cruiseLine;
	queryString += '&cruiseOnlySearch=' + cruiseOnlySearch;
	if ( _allCruiseLines != null && _allCruiseLines != undefined ) {
		var allCruiseLineList = _allCruiseLines.parseJSON();
		for ( var i = 0; i < allCruiseLineList.length; i++ ) {
			var cruiseLineOption = allCruiseLineList [ i ];
			if ( cruiseLineOption.value != "" ) {
				if ( cruiseLineOption.value == cruiseLine || cruiseLine == "0" ) {
					trackEvent( 'Search Cruise' , cruiseLineOption.text , "Yes" );
				} else {
					trackEvent( 'Search Cruise' , cruiseLineOption.text , "No" );
				}
			}
		}
	}
	if ( cruiseLine == '' ) {
		document.getElementById ( "cruiseShips" ) [ 0 ].selected = true;
		document.getElementById ( "cruiseShips" ).length = 1;
		document.getElementById ( "cruiseShips" ) [ 0 ].text = "Any";

		document.getElementById ( "portOfEmbarkation" ) [ 0 ].selected = true;
		document.getElementById ( "portOfEmbarkation" ).length = 1;
		document.getElementById ( "portOfEmbarkation" ) [ 0 ].text = "Any";
	}
	cruiseLine = ( cruiseLine != 0 ) ? cruiseLine : "Any";
	trackEvent( 'Search Cruise' , 'Cruise Line' , cruiseLine );

	makeAjaxCall( "leftContent.act" , queryString , null , 'mainContent' , 'callbackLoadShipsAndPorts' , '' );
}

function callbackLoadShipsAndPorts ( shipsJSON, seaportsJSON ) {
	if ( ! showMessage(this.messageType, this.messageCode, this.message , 'dataContent' ) ) {
		disableElement ( "dataContent" , false );
		replaceOptions ( "cruiseShips" , shipsJSON );
		replaceOptions ( "portOfEmbarkation" , seaportsJSON , 1 );
		document.getElementById ( "cruiseShips" ) [ 0 ].text = "Any";
		document.getElementById ( "portOfEmbarkation" ) [ 0 ].text = "Any";
	}
}

function doCruiseSailingSearch() {
	clearErrorElements();
	if( !validateCruiseSearchCriteria() ) {
		return false;
	}
	_cruisePackageId = null;

	var queryString = prepareCruiseSearchQuery( false );
	disableElement ( 'dataContent' , true );

	var destinationCode = document.getElementById ( "cruiseDestination" ).value;
	var cruiseLineCode = document.getElementById ( "cruiseLine" ).value;
	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);

	trackEvent("Search Cruise", "Click", "Cruise Search");
	//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', 'callbackDoCruiseSearch', null, trackingText );
}

function doCruiseTourSearch() {
	clearErrorElements();
	if( !validateCruiseSearchCriteria() ) {
		return false;
	}
	var queryString = prepareCruiseSearchQuery( true );

	disableElement ( 'dataContent' , true );

	var destinationCode = document.getElementById ( "cruiseDestination" ).value;
	var cruiseLineCode = document.getElementById ( "cruiseLine" ).value;
	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);

	trackEvent("Search Cruise", "Click", "Cruise Search");
	//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', 'callbackDoCruiseSearch', null, trackingText );
}

function validateCruiseSearchCriteria() {
	var departureDateString = document.getElementById ( "departureDate" ).value;
	if ( departureDateString == '' ) {
		var msg = "Please select departure month.";
		showErrorMessage ( msg , 'dataContent', 'departureDateDiv', '#7f9db9' );
		return false;
	}
	return true;
}

function prepareCruiseSearchQuery( fetchCruiseTours ) {
	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" );
	var tourCode = document.getElementById( "tourCode" );
	var tourType = document.getElementById( "tourType" );

	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;
		if( !isNull( tourCode ) ) {
			queryString += "&tourCode=" + tourCode.value;
		}
		if( !isNull( tourType ) && !isEmpty( tourType.value ) ) {
			queryString += "&tourType=" + tourType.value;
		}
	}
	queryString += "&cruiseLength=" + cruiseLength;
	queryString += "&fetchCruiseTours=" + fetchCruiseTours;
	return queryString;
}

function callbackDoCruiseSearch() {
	if ( ! showMessage(this.messageType, this.messageCode, this.message , 'dataContent' ) ) {
		disableElement ( 'dataContent' , false );
	}
	return true;
}

function loadCruiseChildrenAges(maxChildrensInCabin) {
	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(maxInfantsInCabin) {
	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(){
	loadTripSummary( true );
}

function showHidePastPassengerNumber(){
	if( document.getElementById( "isPastPassenger" ).checked ){
		document.getElementById ( "pastPassengerNumberRow" ).style.display = "block";
	} else {
		document.getElementById ( "pastPassengerNumberRow" ).style.display = "none";
	}
	
	var isPastPassenger = document.getElementById ( "isPastPassenger" ).checked;
	trackEvent('Search Cruise', 'Previous Cruise', (isPastPassenger ? "Yes" : "No"));
}

function showDOBCalendar ( fieldName ) {
	showCalendar ( fieldName , null , null , null , true );
}

function depatureDateChanged(){
	var departureDateText = document.getElementById ( "departureDate" )[document.getElementById ( "departureDate" ).selectedIndex].text;
	trackEvent('Search Cruise', 'Departure', departureDateText);
}

function cruiseLengthChanged( fieldName ){
	var cruiseLength = document.getElementById ( fieldName ).value;
	var cruiseLengthArray = cruiseLength.split("-");
	var minLength = trim(cruiseLengthArray[0]);
	var maxLength = trim(cruiseLengthArray[1]);
	maxLength = (maxLength != 0) ? maxLength : "Any";
	trackEvent('Search Cruise', 'Length Min', 'Min', minLength);
	trackEvent('Search Cruise', 'Length Max', 'Max', maxLength);
}

function cruiseShipsChanged(){
	var shipCode = document.getElementById ( "cruiseShips" ).value;
	shipCode = (shipCode != 0) ? shipCode : "Any";
	trackEvent('Search Cruise', 'Cruise Ship', shipCode);
}

function portOfEmbarkationChanged(){
	var portOfEmbarkation = document.getElementById ( "portOfEmbarkation" ).value;
	portOfEmbarkation = (portOfEmbarkation != "") ? portOfEmbarkation : "Any";
	trackEvent('Search Cruise', 'Embarkation Port', portOfEmbarkation);
}

function loadCruisePackageLeadInPrices( packageId, displayItinerary ) {
	var queryString = "pc=9";
	queryString += "&packageId=" + packageId;
	queryString += "&displayItinerary=" + displayItinerary;
	queryString += "&callerPage=CRUISE_PACKAGE";
	makeAjaxCall( 'packageContent.act' , queryString, null , 'cruisePackageLeadinPricesDiv', 'callbackLoadCruisePackageLeadInPrices' );
}

function callbackLoadCruisePackageLeadInPrices() {
	document.getElementById("cruisePackageLeadinPricesDiv").className = "w682 mt10";
}

function loadToursByDestinationAndCruiseLine(){
	var destinationCode = document.getElementById ( "cruiseDestination" ).value;
	var cruiseLine = document.getElementById ( "cruiseLine" ).value;
	var queryString = "";
	queryString += "lc=14";
	queryString += '&destinationCode=' + destinationCode;
	queryString += '&cruiseLineCodes=' + cruiseLine;
	makeAjaxCall ( 'leftContent.act' , queryString , null , 'mainContent' , 'callbackLoadToursByDestinationAndCruiseLine' , '' );
}

function callbackLoadToursByDestinationAndCruiseLine (  toursJSON ) {
	var cruiseLine = '';
	var tourCodeList = document.getElementById ( "tourCode" );
	if (document.getElementById ( "cruiseLine" )){
		cruiseLine = document.getElementById ( "cruiseLine" ).value;
	}	
	if (cruiseLine == ''){
		tourCodeList.length = 0;
		tourCodeList.options[0] = new Option ("Please Select a Cruise Line","");
	}else{
	replaceOptions ( "tourCode" , toursJSON, 0, true );
		tourCodeList[0].text = "Any";
	}	
}

function loadShipsForCruiseTour() {
	var destinationCode = document.getElementById ( "cruiseDestination" ).value;
	var cruiseLine = document.getElementById( "cruiseLine" ).value;
	var tourCode = document.getElementById( "tourCode" ).value;

	var queryString = "lc=15";
	queryString += "&destinationCode=" + destinationCode;
	queryString += "&cruiseLineCodes=" + cruiseLine;
	queryString += "&tourCode=" + tourCode;

	makeAjaxCall( "leftContent.act" , queryString , null , null, 'callbackLoadShipsAndPorts' , '' );
}

function callbackLoadShipsForCruiseTour(shipsJSON) {
	if ( ! showMessage(this.messageType, this.messageCode, this.message , 'dataContent' ) ) {
		disableElement ( "dataContent" , false );
		replaceOptions ( "cruiseShips" , shipsJSON );
		document.getElementById ( "cruiseShips" ) [ 0 ].text = "Any";
	}
}function loadCruiseCategories( cabinLocation, selectedCabinDiv, selectedCabinLink, destination, cruiseLine, ship, departureDate, sailingItemUid  ) {
	inActivateAllCabinTabs();
	activateCabinTab( selectedCabinDiv, selectedCabinLink );
	var queryString = "ccr=1";
	queryString += '&cabinLocation=' + cabinLocation;
	queryString += '&uid=' + sailingItemUid;
	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);
	}	

	var trackingText = null;
	if(!isEmpty(_cruisePackageId)) {
		trackingText = '/cr/booking/bookingPackage/categorySelection' + cabinLocation.replace(' ','')+ '/' + _cruisePackageId + '/' + year + month + day;
	} else {
		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 = "cruiseCategoryTitleTab";
	}
}

function activateCabinTab( cabinDivId, cabinLinkId ) {
	var cabinTab = document.getElementById( cabinDivId );
	if( !isNull( cabinTab ) ) {
		cabinTab.className = "cruiseCategoryTitleTab-sel";
	}
}

function reLoadCruiseCategoryResults(){
	var queryString = "ccr=5";

	disableElement( 'dataContent', true );
	makeAjaxCallWithWaitingDiv( 'cruiseCategoryResults.act', queryString, null, 'rightContent', 'callbackReLoadCruiseCategoryResults' );
}

function callbackReLoadCruiseCategoryResults(){
	if ( !( showMessage(this.messageType, this.messageCode, this.message , '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, -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 ( categoryItemUid, type, isMember, destination, cruiseLine, ship, departureDate ) {
	createPopupDiv ( "memberBenefitsPopupDivContainer", -1, -1, -1, -1, 200 , false , true , "" );
	disableElement ( "dataContent" , true );
	var queryString = "ccr=3";
	queryString +="&uid=" + categoryItemUid;
	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);
	}

	var trackingText = null;
	if(!isEmpty(_cruisePackageId)) {
		trackingText = '/cr/booking/bookingPackage/category' + (isMember ? '' : 'Non')+ 'MemberAddedValues/' + _cruisePackageId + '/' + year + month + day;
	} else {
		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, -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);
	}	

	var trackingText = null;
	if(!isEmpty(_cruisePackageId)) {
		trackingText = '/cr/booking/bookingPackage/categoryPopupDeckPlans/' + _cruisePackageId + '/' + year + month + day;
	} else {
		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) {
	var queryString = "css=3";
	queryString += "&cruiseCategoryItemUid=" + cruiseCategoryItemUid;

	var trackingText = null;
	if (!isEmpty(_cruisePackageId)) {
		trackingText = "/cr/booking/bookingPackage/cabinSelection/" + _cruisePackageId + "/" + _departureDate;
	}
	else {
		trackingText = "/cr/booking/bookingWidget/cabinSelection/" + _destinationName + "/" + _cruiseLineName + "/" + _shipName + "/" + _departureDate;
	}

	disableElement("dataContent", true);
	makeAjaxCallWithWaitingDiv("cruiseSearch.act", queryString, null, "rightContent", "callbackProceedToCruiseCabinSearch", null, trackingText);
}

function callbackProceedToCruiseCabinSearch() {
	if (!showMessage(this.messageType, this.messageCode, this.message, "dataContent")) {
		loadCruiseTripSummary();
		disableElement("dataContent", false);
	}
}

function selectCabin(cabinCode, cabinItemUid) {
	if (!cabinCode && getCheckedRadio("cabinOption") == null) {
		showErrorMessage("Before you continue, please select a stateroom", "dataContent");
		return false;
	}

	var queryString = "crcr=1";
	var cruiseDeckNameElement = document.getElementById("cruiseDeckName");
	if (cruiseDeckNameElement) {
		queryString += "&selectedDeckName=" + document.getElementById("cruiseDeckName").value;
	}
	if (cabinItemUid) {
		queryString += "&cruiseCabinItemUid=" + cabinItemUid;
	}
	else {
		queryString += "&cabinNumber=" + cabinCode.toUpperCase();
	}

	makeMultiAjaxCall(new Array(new AsynchronousMultiRequestItem("cruiseCabinResults.act", queryString, null, "cruiseCabinInfoDiv", "callbackLoadCabins"), new AsynchronousMultiRequestItem(
			"cruiseCabinResults.act", "crcr=4", null, null, "callbackSelectCabin", [ cabinItemUid ])));
}

function callbackLoadCabins() {
	showMessage(this.messageType, this.messageCode, this.message, "dataContent");
}
function callbackSelectCabin(bedOptionJSON, cruiseCabinItemUid) {
	if (!showMessage(this.messageType, this.messageCode, this.message, "dataContent")) {
		document.getElementById("cruiseCabinItemUid").value = cruiseCabinItemUid;
		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";
		}
	}
	else {
		document.getElementById("cabinNumber").value = "";
	}
}

function validateCabin() {
	var cabinNumber = document.getElementById("cabinNumber").value;

	if (trim(cabinNumber) == "") {
		alert("Before you continue, please select a cabin.");
		return false;
	}

	selectCabin(cabinNumber);
}

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", "callbackLoadCruiseCabins");
}

function callbackLoadCruiseCabins() {
	if (!showMessage(this.messageType, this.messageCode, this.message, "dataContent")) {
		disableElement("dataContent", false);
		unselectCabins();
	}
}

function submitCruiseCabinSelection() {
	var cabinOptions = document.getElementsByName("cabinOption");
	var cabinNumber = document.getElementById("cabinNumber").value;
	var isCabinSelected = false;
	var cruiseCabinItemUid = document.getElementById("cruiseCabinItemUid").value;

	for ( var cabinIndex = 0; cabinIndex < cabinOptions.length; cabinIndex++) {
		if (cabinOptions[cabinIndex].checked) {
			isCabinSelected = true;
			break;
		}
	}

	if (isCabinSelected && cruiseCabinItemUid != "") {
		var queryString = "crcr=5";
		disableElement("dataContent", true);

		makeAjaxCallWithWaitingDiv("cruiseCabinResults.act", queryString, null, "rightContent", "callbackSubmitCruiseCabinSelection");
	}
	else {
		showErrorMessage("Before you continue, please select a stateroom", "dataContent");
		return false;
	}
}

function callbackSubmitCruiseCabinSelection(isCruisePrePostComponentsAvailable) {
	if (this.messageCode == ErrorCodes.MEMBER_NOT_LOGGED_IN_ERROR) {
		proceedToCruiseMemberLogin();
	}
	else if (!showMessage(this.messageType, this.messageCode, this.message, "dataContent")) {
		disableElement("dataContent", false);
		if (!isEmpty(_cruisePackageId)) {
			var trackingText = "/cr/booking/bookingPackage/passengerDetails/" + _cruisePackageId + _departureDate;
			trackPageView(trackingText);
		}
		else {
			var trackingText = "/cr/booking/bookingWidget/passengerDetails/" + _destinationName + "/" + _cruiseLineName + "/" + _shipName + "/" + _departureDate;
			trackPageView(trackingText);
		}
		loadCruiseTripSummary();
	}
}

function callBackLoadCruiseMemberLoginScreen() {
	hideMessageBox(UID(), "dataContent");
	window.location.href = _secureContextRoot + _webLoc + "/?h=5&checkMemberInactivity=true&uid=" + UID();
}

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.messageType, this.messageCode, this.message, "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.messageType, this.messageCode, this.message, "dataContent");
}

function loadDeckPlan(deckCounter, travtechShipId, configId, deckId, deckName, numberOfDecks, deckPlanTitle, deckPlanImage, deckLevelImage) {
	deckPlanTitle = $(deckPlanTitle);
	if (!deckPlanTitle) {
		deckPlanTitle = $("deckPlanTitle");
	}
	deckPlanImage = $(deckPlanImage);
	if (!deckPlanImage) {
		deckPlanImage = $("deckPlanImage");
	}
	deckLevelImage = $(deckLevelImage);
	if (!deckLevelImage) {
		deckLevelImage = $("deckLevelImage");
	}
	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 unselectCabins() {
	var checkedCabinOption = getCheckedRadio("cabinOption");
	if (checkedCabinOption) {
		checkedCabinOption.checked = false;
	}
}
function proceedToCruiseCategorySearch( cruiseMaxPassengers, destination, cruiseLine, ship, departureDate ) {
	var numberOfAdults = parseInt($("adultsInCabin").value);
	var numberOfChildren = parseInt($("childrenInCabin").value);
	var numberOfInfants = parseInt($("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;
		}
 	}
 	
	if ( ! ( validateDropDownField( 'residencyCity', 'Please select your city of residence so that we may search for any available discounted prices applicable to your city.', 'residencyCityDiv' )  ) ) {
		return false;
	}
	
	if(numberOfAdults + numberOfChildren + numberOfInfants > cruiseMaxPassengers) {
		showErrorMessage ("The total number of guests per stateroom may not exceed " + cruiseMaxPassengers + ". To book multiple staterooms or larger suites please contact our call center at " + bookingPhoneNumber + ".", "dataContent", "adultsInCabinDiv", '#7f9db9');
		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 );

	var trackingText = null;
	if(!isEmpty(_cruisePackageId)) {
		trackingText = '/cr/booking/bookingPackage/categorySelectionInside/' + _cruisePackageId + '/' + departureDate;
	} else {
		trackingText = '/cr/booking/bookingWidget/categorySelectionInside/' + destination + '/' + cruiseLine + '/' + ship + '/' + departureDate;
	}

	makeAjaxCallWithWaitingDiv ( 'passengerInfo.act' , queryString , null , 'mainContent' , 'callbackProceedToCruiseCategorySearch', null, trackingText );
}

function callbackProceedToCruiseCategorySearch () {
	if ( !showMessage(this.messageType, this.messageCode, this.message , '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.messageType, this.messageCode, this.message , 'dataContent' ) ) ) {
		loadCruiseTripSummary ();
		disableElement ( "dataContent" , false );
	}
}

function updatePassengerInformationAndContinue () {
	clearErrorElements ();
	var jsonFormattedString = "";
	var passengerArray = [];
	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, true ) ) ) {
			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;

		var passengerObject = {
				paxId: paxId,
				paxType: paxType,
				paxTitle: paxTitle,
				paxFirstName: paxFirstName,
				paxMedInitial: paxMedInitial,
				paxLastName: paxLastName,
				paxSuffix: paxSuffix,
				paxDateOfBirth: paxDateOfBirth,
				paxCitizenship: paxCitizenship,
				pastPassengerNumber: frequentTravellerNumber,
				frequentTravellerId: frequentTravellerId,
				cruiseLineCode: cruiseLineCode
				
			};		
		if(paxGender != null) {
			passengerObject.paxGender = paxGender;
		}
	
		passengerArray[paxIndex] = passengerObject;
	}
	if ( !document.getElementById ( "cruiseTermsAndConditions" ).checked ) {
		showErrorMessage ( 'Please check terms and conditions' , 'dataContent' , 'termsAndConditionsDiv' , '#7f9db9' );
		return false;
	}
	jsonFormattedString={PASSENGER_INFO: passengerArray}.toJSONString();
	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() {
	disableElement ( 'dataContent' , false );
	showMessage(this.messageType, this.messageCode, this.message, 'dataContent');
	return true;
}

function reLoadCruisePassengerDetails(){
	var queryString = "pi=5";
	disableElement ( 'dataContent' , true );
	makeAjaxCallWithWaitingDiv ( 'passengerInfo.act' , queryString , null , 'rightContent' , 'callbackReLoadCruisePassengerDetails' );
}

function callbackReLoadCruisePassengerDetails(){
	if ( ! ( showMessage(this.messageType, this.messageCode, this.message , '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, cruiseSearch ){
	clearErrorElements();
	var paxType = document.getElementById("paxType_" + paxIndex).value;
	if( ! ( validateDOB( 'paxDateOfBirth_' + paxIndex, 'dataContent', paxType,cruiseSearch ) )  ) {
		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 );
		var validateAge = true;
		if ( paxType == 1 || paxType == 2 ) {
			ageInMonths = Math.floor( (referenceDate.getTime() - dateOfBirth.getTime() ) / oneMonth );
		}
		
		//validate child/infant age only if flights are present for VP
		if (document.getElementById("bookingHasValidFlights")){
			var bookingHasValidFlights = (document.getElementById("bookingHasValidFlights").value == "true");
			if (!bookingHasValidFlights){
				validateAge = false
			}
		}
				
		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( validateAge &&	(! ( 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;	
}

function residencyCityChanged(){
	var residentCityList = document.getElementById ( "residencyCity" );
	var residencyCodeDesc;
	
	for (var itemCount = 0; itemCount < residentCityList.options.length; itemCount++){
		if (residentCityList.options[itemCount].selected){
			residencyCodeDesc = residentCityList.options[itemCount].text;
		}	
	}	
	var residencyCodes = residencyCodeDesc.split(",");
	if(residencyCodes.length == 2) {
		var residencyStateAndCountry = residencyCodes[1].split("(");
		var residencyState = trim(residencyStateAndCountry[0]);	
		trackEvent('Search Cruise', 'Member State', residencyState);
	}
}

function isSomeOneSeniorChanged(){
	var isSomeOneSenior = document.getElementById ( "isSomeOneSenior" ).checked;
	trackEvent('Search Cruise', 'Senior', (isSomeOneSenior ? "Yes" : "No"));
}
function loadPrePostHotelRoomDetails( prePostHotelRoomsId, prePostdiv, componentType ) {
	var selectedNoOfRooms = document.getElementById( prePostHotelRoomsId ).value;
	if ( selectedNoOfRooms > 1 ) {
		var queryString = "cpps=4";
		queryString += "&hotelRooms=" + selectedNoOfRooms;
		queryString += "&componentType=" + componentType;
		document.getElementById( prePostdiv ).style.display = "block";
		makeAjaxCall( "cruisePrePostComponentSearch.act" , queryString , null , prePostdiv , "callbackLoadPrePostHotelRoomDetails" , "" );
	} else {
		document.getElementById( prePostdiv ).style.display = "none";
	}
}

function callbackLoadPrePostHotelRoomDetails() {
	showMessage(this.messageType, this.messageCode, this.message , "dataContent");
}

function showHideFlightInformation(flightPriceMaskedWithHotel) {
	var isFlightIncluded = document.getElementById( "flightIncluded" ).checked;
	if ( isFlightIncluded ) {
		document.getElementById( "cruisePrePostFlightDiv" ).style.display = "block";
		//TS:8273
		if( flightPriceMaskedWithHotel ){
			document.getElementById( "preCruiseHotelIncluded" ).checked = true;
			document.getElementById( "postCruiseHotelIncluded" ).checked = true;
			showHidePreCruiseHotelInformation();
			showHidePostCruiseHotelInformation();			
		}
	} else {
		document.getElementById( "cruisePrePostFlightDiv" ).style.display = "none";		
	}
	isAnyProductSelected();
}

function showHidePreCruiseHotelInformation() {
	var preCruiseHotelIncluded = document.getElementById( "preCruiseHotelIncluded" ).checked;
	if ( preCruiseHotelIncluded ) {
		loadPrePostHotelRoomDetails( "preHotelRooms" , "preCruiseHotelInformationRowDiv" , "preHotel" );
		document.getElementById( "preCruiseHotelDiv" ).style.display = "block";
	} else {
		document.getElementById( "preCruiseHotelDiv" ).style.display = "none";
	}
	isAnyProductSelected();
}

function showHidePostCruiseHotelInformation() {
	var postCruiseHotelIncluded = document.getElementById( "postCruiseHotelIncluded" ).checked;
	if ( postCruiseHotelIncluded ) {
		loadPrePostHotelRoomDetails( "postHotelRooms" , "postCruiseHotelInformationRowDiv" , "postHotel" );
		document.getElementById( "postCruiseHotelDiv" ).style.display = "block";
	} else {
		document.getElementById( "postCruiseHotelDiv" ).style.display = "none";
	}
	isAnyProductSelected();
}

/* Is Any product selected (flight, pre/post hotel then defaultly selecting the transfer product also. */
function isAnyProductSelected() {
	var isFlightIncluded = document.getElementById( "flightIncluded" ).checked;
	var isPreHotelIncluded = document.getElementById( "preCruiseHotelIncluded" ).checked;
	var isPostHotelIncluded = document.getElementById( "postCruiseHotelIncluded" ).checked;

	if ( document.getElementById( "prePostCruiseTransfersIncluded" ).disabled == false ) {
		if (  isFlightIncluded || isPreHotelIncluded || isPostHotelIncluded )  {
			document.getElementById( "prePostCruiseTransfersIncluded" ).checked = true;
		} else {
			document.getElementById( "prePostCruiseTransfersIncluded" ).checked = false;
		}
	}
}

/* perform super PNR search */
function performSuperPNRSearch() {
	var isFlightIncluded = document.getElementById( "flightIncluded" ).checked;
	var isPostHotelIncluded = document.getElementById( "postCruiseHotelIncluded" ).checked;
	var isPreHotelIncluded = document.getElementById( "preCruiseHotelIncluded" ).checked;
	var isTransferIncluded = document.getElementById( "prePostCruiseTransfersIncluded" ).checked;
	var flightInfo = null;
	var preCruiseHotelInfo = null;
	var postCruiseHotelInfo = null;
	var preHotelInfo = null;
	var postHotelInfo = null;
	var infantSeatFlag = null;
	var preHotelRooms = 0;
	var postHotelRooms = 0;
	var numberOfActualAdults = parseInt($("numberOfActualAdults").value);
	var numberOfChildren = parseInt($("numberOfActualChildren").value) + parseInt($("numberOfInfants").value); 
	var numberOfActualPassengers = numberOfActualAdults + numberOfChildren;
	var cruiseEmbarkationCity = $("cruiseEmbarkationCity").value
	var cruiseDisembarkationCity = $("cruiseDisembarkationCity").value
	var cruiseDepartureDate = $("cruiseDepartureDate").value
	var cruiseReturnDate = $("cruiseReturnDate").value
	
	// If nothing is included
	if ( !isFlightIncluded && !isPreHotelIncluded && !isPostHotelIncluded && !isTransferIncluded ) {
		var queryString = "cpps=8";
		disableElement( "dataContent" , true );
		makeAjaxCallWithWaitingDiv( "cruisePrePostComponentSearch.act" , queryString , null , "rightContent" , "callbackPerformSuperPNRSearch");
	} else {

		// If only transfers is included in pre/post cruise search
		if ( ( !isFlightIncluded && !isPreHotelIncluded && !isPostHotelIncluded && isTransferIncluded )
				|| ( isNull( isFlightIncluded ) && isNull( isPreHotelIncluded ) && isNull( isPostHotelIncluded ) ) ) {
			showErrorMessage( "At this point transfers are provided only if flight and/or hotel is included in your cruise booking." , "dataContent" );
			return false;
		}

		// If flight is included in pre/post cruise search
		if ( isFlightIncluded ) {
			var departureCity = document.getElementById( "departureCityTextPrePost" ).value;
			var serviceClass = document.getElementById( "serviceClassPrePost" ).value;
			var departureCityCode = document.getElementById( "departureCityCodePrePost" ).value;

			if ( departureCity == "" ) {
				showErrorMessage( "Please select departure city." , "dataContent" , "departureCityTextPrePost" , "1px solid #7f9db9" );
				return false;
			}

			var flightInfantInfos = new Array();
			for ( var paxIndex = 0; paxIndex < numberOfActualPassengers; paxIndex++ ) {
				var paxTypeField = document.getElementById( "flightPaxType_" + paxIndex );
				if ( document.getElementById( "infantSeatFlag_" + paxIndex ) && paxTypeField ) {
					if( paxTypeField.value == "Infant" ){
						infantSeatFlag = document.getElementById( "infantSeatFlag_" + paxIndex ).value;
						if ( infantSeatFlag != null ) {
							flightInfantInfos [ paxIndex ] = new InfantInfo( paxIndex , infantSeatFlag );
						}
					}
				}
			}
			flightInfo = new FlightInfo( departureCityCode , serviceClass , flightInfantInfos );
		}
		// If pre hotel is included in pre/post cruise search
		if ( isPreHotelIncluded ) {
			preHotelRooms = parseInt( document.getElementById( "preHotelRooms" ).value );
			var preHotelNights = document.getElementById( "preHotelNights" ).value;
			var roomWiseAdults = 0;
			var roomWiseChildren = 0;
			var roomInfos = new Array();
			if ( preHotelRooms == 1 ) {
				roomInfos [ 1 ] = new RoomInfo( 1 , numberOfActualAdults , numberOfChildren );
			} else {
				for ( var roomCounter = 1; roomCounter <= preHotelRooms; roomCounter++ ) {
					var selectedAdultsInRoom = parseInt( document.getElementById( "preHotel_Adult_Room_" + roomCounter ).value );
					var selectedChildrenInRoom = parseInt( document.getElementById( "preHotel_Children_Room_" + roomCounter ).value );

					roomWiseAdults += parseInt( selectedAdultsInRoom );
					roomWiseChildren += parseInt( selectedChildrenInRoom );
					roomInfos [ roomCounter ] = new RoomInfo( roomCounter , selectedAdultsInRoom , selectedChildrenInRoom );
				}
			}
			preHotelInfo = new HotelInfo( preHotelRooms , roomInfos , preHotelNights );
			if ( preHotelRooms > 1 && numberOfActualPassengers != ( roomWiseAdults + roomWiseChildren ) ) {
				showErrorMessage( "Pre cruise hotel : Number of actual passengers and the selected passengers in the rooms does not match." , "dataContent" );
				return false;
			}
			if ( preHotelNights == 0 ) {
				showErrorMessage( "Please select pre hotel nights." , "dataContent" , "preHotelNightsDiv" , "#7f9db9" );
				return false;
			}
		}
		// If post hotel is included in pre/post cruise search
		if ( isPostHotelIncluded ) {
			postHotelRooms = parseInt( document.getElementById( "postHotelRooms" ).value );
			var postHotelNights = document.getElementById( "postHotelNights" ).value;

			var roomWiseAdults = 0
			var roomWiseChildren = 0
			var roomInfos = new Array();
			if ( postHotelRooms == 1 ) {
				roomInfos [ 1 ] = new RoomInfo( 1 , numberOfActualAdults , numberOfChildren );
			} else {
				for ( var roomCounter = 1; roomCounter <= postHotelRooms; roomCounter++ ) {
					var selectedAdultsInRoom = parseInt( document.getElementById( "postHotel_Adult_Room_" + roomCounter ).value );
					var selectedChildrenInRoom = parseInt( document.getElementById( "postHotel_Children_Room_" + roomCounter ).value );

					roomWiseAdults += parseInt( selectedAdultsInRoom );
					roomWiseChildren += parseInt( selectedChildrenInRoom );
					roomInfos [ roomCounter ] = new RoomInfo( roomCounter , selectedAdultsInRoom , selectedChildrenInRoom );
				}
			}
			postHotelInfo = new HotelInfo( postHotelRooms , roomInfos , postHotelNights );

			if ( postHotelRooms > 1 && numberOfActualPassengers != ( roomWiseAdults + roomWiseChildren ) ) {
				showErrorMessage( "Post cruise hotel : Number of actual passengers and the selected passengers in the rooms does not match." , "dataContent" );
				return false;
			}
			if ( postHotelNights == 0 ) {
				showErrorMessage( "Please select post hotel nights." , "dataContent" , "postHotelNightsDiv" , "#7f9db9" );
				return false;
			}

		}
		/* Checking no of days difference between post hotel check out date and current date.
		 * If the difference crosses 331 days, we are not allowing user to the flight resulsts screen.
		 */
		if ( isFlightIncluded && isPostHotelIncluded ) {
			var numberOfPostHotelNights = document.getElementById( "postHotelNights" ).value;
			var postHotelCheckoutDate = addDaysToDate( cruiseReturnDate , numberOfPostHotelNights );
			var fromDate = new Date();
			var toDate = new Date( postHotelCheckoutDate );
			if ( fromDate < toDate ) {
				var noOfDays = computeDifferenceBetweenDates( fromDate , toDate );
				if( noOfDays >= 331 ) {
					showErrorMessage( "Flight results are available for only upto next 331 days from current date" , "dataContent" );
					return false;
				}
			}
		}
		var prePostCruisePackageInfo = new PrePostCruisePackageInfo( isFlightIncluded , isPreHotelIncluded , isPostHotelIncluded , isTransferIncluded , flightInfo , preHotelInfo ,
				postHotelInfo , cruiseEmbarkationCity , cruiseDisembarkationCity , cruiseDepartureDate , cruiseReturnDate );
		var queryString = "cpps=5";
		queryString += "&superPNRSearchJsonString=" + prePostCruisePackageInfo.toJSONString();
		disableElement( "dataContent" , true );
		makeAjaxCallWithWaitingDiv( "cruisePrePostComponentSearch.act" , queryString , null , "rightContent" , "callbackPerformSuperPNRSearch");
	}
}

/* Call back function for after perform super PNR search. */
function callbackPerformSuperPNRSearch() {
	if (this.messageCode == ErrorCodes.MEMBER_NOT_LOGGED_IN_ERROR) {
		proceedToCruiseMemberLogin();
	}
	else if (!showMessage(this.messageType, this.messageCode, this.message , "dataContent" )) {
		loadCruiseTripSummary();
		disableElement( "dataContent" , false );
	}
}

/* InfantInfo class holds Infant details. */
function InfantInfo( infantIndex, infantSeatFlag ) {
	this.infantIndex = infantIndex;
	this.infantSeatFlag = infantSeatFlag;
}

/* FlighInfo class holds flight search criteria. */
function FlightInfo( departureCityCode, serviceClass, infantInfos ) {
	this.departureCityCode = departureCityCode;
	this.serviceClass = serviceClass;
	this.infantInfos = infantInfos;
}
/* RoomInfo class holds room details. */
function RoomInfo( roomNumber, adults, children ) {
	this.roomNumber = roomNumber;
	this.adults = adults;
	this.children = children;
}
/* PreHotelInfo class holds pre hotel search criteria. */
function HotelInfo( numberOfRooms, roomInfos, numberOfNights ) {
	this.numberOfRooms = numberOfRooms;
	this.roomInfos = roomInfos;
	this.numberOfNights = numberOfNights;
}

function PrePostCruisePackageInfo( isFlightIncluded, isPreHotelIncluded, isPostHotelIncluded, isTransferIncluded, flightInfo, preHotelInfo, postHotelInfo, cruiseEmbarkationCity,
		cruiseDisembarkationCity, cruiseDepartureDate, cruiseReturnDate ) {
	this.isFlightIncluded = isFlightIncluded;
	this.isPreHotelIncluded = isPreHotelIncluded;
	this.isPostHotelIncluded = isPostHotelIncluded;
	this.flightInfo = flightInfo;
	this.preHotelInfo = preHotelInfo;
	this.postHotelInfo = postHotelInfo;
	this.isTransferIncluded = isTransferIncluded;
	this.cruiseEmbarkationCity = cruiseEmbarkationCity;
	this.cruiseDisembarkationCity = cruiseDisembarkationCity;
	this.cruiseDepartureDate = cruiseDepartureDate;
	this.cruiseReturnDate = cruiseReturnDate;
}

function reLoadCruisePrePostSearch() {
	var queryString = "cpps=0";
	disableElement( "dataContent" , true );
	makeAjaxCallWithWaitingDiv( "cruisePrePostComponentSearch.act" , queryString , null , "rightContent" , "callbackPerformSuperPNRSearch");
}


/**
 * PrePostHotelSearchInfo() info to search Pre and Post Hotel based on the user selected in the Pre Post Hotel selection popup.
 */
function PrePostHotelSearchInfo( preCruiseHotelSearchInfo, postCruiseHotelSearchInfo ) {
	this.preCruiseHotelSearchInfo = preCruiseHotelSearchInfo;
	this.postCruiseHotelSearchInfo = postCruiseHotelSearchInfo;
}

/*
 * includeTransfers() method to include the transfers otherwise skip the transfers continue to specialRequest/Flight Seat selection.
 */
function includeTransfers() {
	var isTransferIncluded = document.getElementById( "transferIncluded" ).checked;
	var queryString = "cpps=9";
	queryString += "&transferIncluded=" + isTransferIncluded;
	disableElement( "transferSelectionPopupContainer" , true );
	makeAjaxCallWithWaitingDiv( "cruisePrePostComponentSearch.act" , queryString , null , "rightContent" , "callbackIncludeTransfers");
}

function callbackIncludeTransfers() {
	if ( !showMessage(this.messageType, this.messageCode, this.message , "transferSelectionPopupContainer" ) ) {
		hideBlock( "transferSelectionPopupContainer" );
		disableElement( "transferSelectionPopupContainer" , false );
		disableElement( "dataContent" , false );
	}
}

function gotoCruiseCabinSelection() {
	var queryString = "cpps=2";
	disableElement( "dataContent" , true );
	makeAjaxCallWithWaitingDiv( "cruisePrePostComponentSearch.act" , queryString , null , "rightContent" , "callbackGotoCruiseCabinSelection");
}

function callbackGotoCruiseCabinSelection() {
	if ( !showMessage(this.messageType, this.messageCode, this.message , "dataContent" ) ) {
		loadCruiseTripSummary();
		disableElement( "dataContent" , false );
	}
}function validateFlightPriceMaskedWithHotels(componentType, productUid) {
	var queryString = "cpcr=9";
	disableElement("dataContent", true);
	makeAjaxCallWithWaitingDiv("cruisePrePostComponentResults.act", queryString, null, null, "callbackValidateFlightPriceMaskedWithHotels", [ componentType, productUid ]);
}

function callbackValidateFlightPriceMaskedWithHotels(componentType, productUid) {
	if (!showMessage(this.messageType, this.messageCode, this.message, "dataContent")) {
		continueToNextSearchResults(componentType, productUid);
	}
}

function continueToNextSearchResults(componentType, productUid) {
	var queryString = "cpcr=4";
	queryString += "&componentType=" + componentType;
	if (isNull(productUid)) {
		productUid = ""
	}
	queryString += "&uid=" + productUid;
	disableElement("dataContent", true);
	makeAjaxCallWithWaitingDiv("cruisePrePostComponentResults.act", queryString, null, "rightContent", "callbackContinueToNextSearchResults");
}

function callbackContinueToNextSearchResults(selection, secondParamter, uid) {
	if (this.messageCode == ErrorCodes.MEMBER_NOT_LOGGED_IN_ERROR) {
		proceedToCruiseMemberLogin();
	}
	else if (!showMessage(this.messageType, this.messageCode, this.message, "dataContent")) {
		hideBlock("hotelSelectionPopupContainer");
		disableElement("hotelSelectionPopupContainer", false);
		disableElement("dataContent", false);
	}
	if (!isNull(selection)) {
		if (selection == "FlightSelection") {
			showPrePostFlightSelection(secondParamter);
			scrollWindowTop();
		}
	}
}

function showPrePostFlightSelection(message) {
	var queryString = "cpcr=0";
	disableElement("dataContent", true);

	makeAjaxCallWithWaitingDiv("cruisePrePostComponentResults.act", queryString, null, "rightContent", "callbackShowPrePostFlightSelection", [ message ]);
}

function callbackShowPrePostFlightSelection(message) {
	if (!(showMessage(this.messageType, this.messageCode, this.message, "dataContent"))) {
		disableElement("dataContent", false);
		if (message != undefined && !isEmpty(message)) {
			showWarningMessage(message, "dataContent");
		}
		loadCruiseTripSummary();
	}
	return true;
}

function continueToPreviousSearchResults(componentType) {
	var queryString = "cpcr=5";
	componentType = componentType || "";
	queryString += "&componentType=" + componentType;
	disableElement("dataContent", true);
	makeAjaxCallWithWaitingDiv("cruisePrePostComponentResults.act", queryString, null, "rightContent", "callbackContinueToPreviousSearchResults");
}

function callbackContinueToPreviousSearchResults() {
	if (!showMessage(this.messageType, this.messageCode, this.message, "dataContent")) {
		disableElement("dataContent", false);
	}
}

function loadPrePostTransferResults() {
	var queryString = "cpcr=3";
	disableElement("dataContent", true);
	makeAjaxCallWithWaitingDiv("cruisePrePostComponentResults.act", queryString, null, "rightContent", "callbackLoadPrePostTransferResults");
}

function callbackLoadPrePostTransferResults() {
	if (!showMessage(this.messageType, this.messageCode, this.message, "dataContent")) {
		disableElement("dataContent", false);
	}
}

function continueToPassengerDetails() {
	var queryString = "cpcr=6";
	disableElement("dataContent", true);
	makeAjaxCallWithWaitingDiv("cruisePrePostComponentResults.act", queryString, null, "rightContent", "callbackContinueToPassengerDetails");
}

function callbackContinueToPassengerDetails() {
	if (this.messageCode == ErrorCodes.MEMBER_NOT_LOGGED_IN_ERROR) {
		proceedToCruiseMemberLogin();
	}
	else if (!showMessage(this.messageType, this.messageCode, this.message, "dataContent")) {
		disableElement("dataContent", false);
		if (!isEmpty(_cruisePackageId)) {
			var trackingText = "/cr/booking/bookingPackage/passengerDetails/" + _cruisePackageId + _departureDate;
			trackPageView(trackingText);
		}
		else {
			var trackingText = "/cr/booking/bookingWidget/passengerDetails/" + _destinationName + "/" + _cruiseLineName + "/" + _shipName + "/" + _departureDate;
			trackPageView(trackingText);
		}
		loadCruiseTripSummary();
	}
}
/* This method show car coupon results in single page as pagination. */
function showCarCouponResultsPage( pagination, pageIndex ) {
	topPagination._selectedPage = pageIndex;
	bottomPagination._selectedPage = pageIndex;
	var queryString = "ccs=1";
	queryString += "&selectedPage=" + pageIndex;
	makeAjaxCall ( 'carCouponSelection.act', queryString , null , 'carCouponItemResultsDiv' , 'callbackShowCarCouponResultsPage' , '' );
}

/* Callback function to load the car coupon search results on click of selected page. */
function callbackShowCarCouponResultsPage() {
	if ( this.cancelled ) {
		disableElement ( "dataContent" , false );
	} else if ( ! showMessage(this.messageType, this.messageCode, this.message , 'dataContent' ) ) {
		disableElement ( "dataContent" , false );
		topPagination.loadPaginationDivs ();
		bottomPagination.loadPaginationDivs ();
	}
}

function displayCarCouponAdditionalInfo( vendorId, couponCode ) {
	var carCouponAdditionalInfoPopupDivContainer = document.getElementById( 'carCouponAdditionalInfoPopupDivContainer' );
	if( isNull( carCouponAdditionalInfoPopupDivContainer ) ) {
		carCouponAdditionalInfoPopupDivContainer = createPopupDiv('carCouponAdditionalInfoPopupDivContainer', 0, 0, 450, -1, 200, false, true, 'popupDivSmall tal');
	}
	var queryString = "ccs=2";
	queryString += "&vendorId=" + vendorId + "&couponCode=" + couponCode;
	makeAjaxCall( 'carCouponSelection.act', queryString , null , 'carCouponAdditionalInfoPopupDivContainer' , 'callbackDisplayCarCouponAdditionalInfo' , '' );
}

function callbackDisplayCarCouponAdditionalInfo() {
	 if( !showMessage(this.messageType, this.messageCode, this.message , 'dataContent' ) ) {
		showBlock( 'carCouponAdditionalInfoPopupDivContainer' );
		positionBlockCentrally( 'carCouponAdditionalInfoPopupDivContainer' );	
		disableElement( 'dataContent', true );
	 }
}

function displayCarCategoriesPopup( vendorId, couponCode ) {
	var carCategoriesPopupDivContainer = document.getElementById( 'carCategoriesPopupDivContainer' );
	if( isNull( carCategoriesPopupDivContainer ) ) {
		carCategoriesPopupDivContainer = createPopupDiv('carCategoriesPopupDivContainer', 0, 0, 450, -1, 200, false, true, 'popupDivSmall tal');
	}
	var queryString = "ccs=3";
	queryString += "&vendorId=" + vendorId + "&couponCode=" + couponCode;
	makeAjaxCall( 'carCouponSelection.act', queryString , null , 'carCategoriesPopupDivContainer' , 'callbackDisplayCarCategoriesPopup' , '' );
}

function callbackDisplayCarCategoriesPopup() {
	 if( !showMessage(this.messageType, this.messageCode, this.message , 'dataContent' ) ) {
		showBlock( 'carCategoriesPopupDivContainer' );
		positionBlockCentrally( 'carCategoriesPopupDivContainer' );	
		disableElement( 'dataContent', true );
	 }
}

function loadCarAgencyResults() {
	makeAjaxCall( 'carAgencySelection.act', '' , null , 'rightContent' , 'callBackLoadCarAgencyResults' , '' );
}

function callBackLoadCarAgencyResults() {
}var _event;
var _fromCarWidget;
var _cityNameAndState;
var _carPickupOrDropoff;
var CAR_SEARCH_WIDGET = 0;
var CAR_SEARCH_POPUP = 1;
var CAR_PICKUP_AT_AIRPORT = 1;
var CAR_PICKUP_AT_CITY = 2;
var CAR_DROPOFF_AT_AIRPORT = 3;
var CAR_DROPOFF_AT_CITY = 4;
var CAR_DROPOFF_SAME_AS_PICKUP = 5;
var defaultCarPickupRadius = 0;
var defaultCarDropoffRadius = 0;
var _couponCode = '';
var _carPopupSearch = 'false';

function choosePickupLocationType( fromWhere ) {
	_fromCarWidget = parseInt(fromWhere);
	if( CAR_SEARCH_WIDGET == _fromCarWidget ) {
		var pickupLocation = parseInt( document.getElementById( "pickupLocationType" ).value );
		if( pickupLocation == CAR_PICKUP_AT_AIRPORT ) {
			document.getElementById( "pickupAirportCodeWidget" ).value ="";
			document.getElementById( "pickupAirportTextWidget" ).value ="";
			document.getElementById( "pickupAsAirport" ).style.display = "";
			document.getElementById( "pickupAsCity" ).style.display = "none";
			document.getElementById( "pickupZipCodeTd" ).style.display = "none";
			document.getElementById( "pickupFindCarsWithInTd" ).style.display = "none";
			document.getElementById( "dropoffAsAirport" ).style.display = "none";
		} else if( pickupLocation == CAR_PICKUP_AT_CITY ) {
			clearStateAndZipForPickup( _fromCarWidget );
			document.getElementById( "pickupAsAirport" ).style.display = "none";
			document.getElementById( "pickupAsCity" ).style.display = "";
			document.getElementById( "pickupZipCodeTd" ).style.display = "";
			document.getElementById( "pickupFindCarsWithInTd" ).style.display = "";
		}
	} else if ( CAR_SEARCH_POPUP == _fromCarWidget ) {
		var pickupLocation = parseInt( document.getElementById( "pickupLocationTypePopup" ).value );
		if( pickupLocation == CAR_PICKUP_AT_AIRPORT ) {
			document.getElementById( "pickupAirportCodePopup" ).value = "";
			document.getElementById( "pickupAirportTextPopup" ).value = "";
			document.getElementById( "pickupAsAirportPopup" ).style.display = "";
			document.getElementById( "pickupAsCityPopup" ).style.display = "none";
			document.getElementById( "pickupZipCodeBlockPopup" ).style.display = "none";
			document.getElementById( "pickupFindCarsWithInBlockPopup" ).style.display = "none";
			document.getElementById( "dropoffAsAirportPopup" ).style.display = "none";
		} else if( pickupLocation == CAR_PICKUP_AT_CITY ) {
			clearStateAndZipForPickup( _fromCarWidget );
			document.getElementById( "pickupAsAirportPopup" ).style.display = "none";
			document.getElementById( "pickupAsCityPopup" ).style.display = "";
			document.getElementById( "pickupZipCodeBlockPopup" ).style.display = "";
			document.getElementById( "pickupFindCarsWithInBlockPopup" ).style.display = "";
		}
	}
	// Change drop off location options depending on pick up location type
	updateDropoffLocationType( _fromCarWidget );
}

function clearStateAndZipForPickup( fromWhere ) {
	var pickupFindCarsWithInField = null;
	if( CAR_SEARCH_WIDGET == fromWhere ) {
		document.getElementById("pickupCityTextWidget" ).value = "";
		document.getElementById("pickupCityCodeWidget").value = "";
		document.getElementById("pickupZipCode").value = "";
		pickupFindCarsWithInField = document.getElementById("pickupFindCarsWithIn");
	} else if( CAR_SEARCH_POPUP == fromWhere ) {
		document.getElementById("pickupCityTextPopup" ).value = "";
		document.getElementById("pickupCityCodePopup").value = "";
		document.getElementById("pickupZipCodePopup").value = "";
		pickupFindCarsWithInField = document.getElementById("pickupFindCarsWithInPopup");
		
	}
	if( !isNull( pickupFindCarsWithInField ) ) {
		var numberOfOptions = pickupFindCarsWithInField.options.length; 
		for( var index = 0;  index <numberOfOptions ; index++ ) {
			if( pickupFindCarsWithInField.options[index].value == defaultCarPickupRadius ) {
				pickupFindCarsWithInField.options[index].selected = true;
				break;
			}
		}
	}
}

function clearStateAndZipForDropoff( fromWhere ) {
	var dropoffFindCarsWithInField = null;
	if( CAR_SEARCH_WIDGET == fromWhere ) {
		document.getElementById("dropoffCityTextWidget").value = "";
		document.getElementById("dropoffCityCodeWidget").value = "";
		document.getElementById("dropoffZipCode").value = "";
		dropoffFindCarsWithInField = document.getElementById("dropoffFindCarsWithIn");
	} else if( CAR_SEARCH_POPUP == fromWhere ) {
		document.getElementById("dropoffCityTextPopup").value = "";
		document.getElementById("dropoffCityCodePopup").value = "";
		document.getElementById("dropoffZipCodePopup").value = "";
		dropoffFindCarsWithInField = document.getElementById("dropoffFindCarsWithInPopup");
	}
	if( !isNull( dropoffFindCarsWithInField ) ) {
		var numberOfOptions = dropoffFindCarsWithInField.options.length; 
		for( var index = 0;  index <numberOfOptions ; index++ ) {
			if( dropoffFindCarsWithInField.options[index].value == defaultCarDropoffRadius ) {
				dropoffFindCarsWithInField.options[index].selected = true;
				break;
			}
		}
	}
}

function updateDropoffLocationType( fromWhere ) {
	if( CAR_SEARCH_WIDGET == fromWhere ) {
		var pickupLocation  = parseInt( document.getElementById( "pickupLocationType" ).value );
		var dropoffBox = document.getElementById( "dropoffLocationTypeContainer" );
		if( pickupLocation == CAR_PICKUP_AT_CITY ) {
			dropoffBox.innerHTML = "<select name='dropoffLocationType' id='dropoffLocationType' class = 'w205 mt03 textbox fs11' onChange='return chooseDropoffLocationType( 0 )';><option value='5' selected='selected'>Same as Pick up location</option><option value='3'>An airport</option></select>";
			document.getElementById( "dropoffAsAirport" ).style.display = "none";
			document.getElementById( "dropoffAsCity" ).style.display = "none";
			document.getElementById( "dropoffZipCodeTd" ).style.display = "none";
			document.getElementById( "dropoffFindCarsWithInTd" ).style.display = "none";
		} else {
			dropoffBox.innerHTML = "<select name='dropoffLocationType' id='dropoffLocationType' class = 'w205 mt03 textbox fs11' onChange='return chooseDropoffLocationType( 0 )';><option value='5' selected='selected'>Same as Pick up location</option><option value='3'>An airport</option><option value='4'>A U.S. city - state</option></select>";
		}
	} else if( CAR_SEARCH_POPUP == fromWhere ) {
		var pickupLocation  = parseInt( document.getElementById( "pickupLocationTypePopup" ).value );
		var dropoffBox = document.getElementById( "dropoffLocationTypePopupContainer" );
		if( pickupLocation == CAR_PICKUP_AT_CITY ) {
			dropoffBox.innerHTML = "<select name='dropoffLocationTypePopup' id='dropoffLocationTypePopup' class = 'w215 mt03 textbox fs11' onChange='return chooseDropoffLocationType( 1 )';><option value='5' selected='selected'>Same as Pick up location</option><option value='3'>An airport</option></select>";
			document.getElementById( "dropoffAsAirportPopup" ).style.display = "none";
			document.getElementById( "dropoffAsCityPopup" ).style.display = "none";
			document.getElementById( "dropoffZipCodeBlockPopup" ).style.display = "none";
			document.getElementById( "dropoffFindCarsWithInBlockPopup" ).style.display = "none";
		} else {
			dropoffBox.innerHTML = "<select name='dropoffLocationTypePopup' id='dropoffLocationTypePopup' class = 'w215 mt03 textbox fs11' onChange='return chooseDropoffLocationType( 1 )';><option value='5' selected='selected'>Same as Pick up location</option><option value='3'>An airport</option><option value='4'>A U.S. city - state</option></select>";
		}
	}
}

function selectDropoffLocationType( locationType, fromWhere ) {
	fromWhere = parseInt(fromWhere);
	var dropoffLocationType = null;
	if( CAR_SEARCH_WIDGET == fromWhere ) {
		dropoffLocationType = document.getElementById( "dropoffLocationType" );
	} else if( CAR_SEARCH_POPUP == fromWhere ) {
		dropoffLocationType = document.getElementById( "dropoffLocationTypePopup" );
	}
	if( !isNull( dropoffLocationType ) ) {
		var numberOfOptions = dropoffLocationType.options.length;
		for( var index = 0 ; index < numberOfOptions ;  index++ ) {
			if( parseInt( dropoffLocationType.options[index].value ) == parseInt( locationType ) ) {
				dropoffLocationType.options[index].selected = true;
				break;
			}
		}
	}
} 

function chooseDropoffLocationType( fromWhere ) {
	_fromCarWidget = parseInt(fromWhere);
	if( CAR_SEARCH_WIDGET == _fromCarWidget ) {
		var dropoffLocation  = parseInt( document.getElementById( "dropoffLocationType" ).value );
		if( dropoffLocation == CAR_DROPOFF_AT_AIRPORT ) {
			document.getElementById( "dropoffAirportCodeWidget" ).value ="";
			document.getElementById( "dropoffAirportTextWidget" ).value ="";
			document.getElementById( "dropoffAsAirport" ).style.display = "";
			document.getElementById( "dropoffAsCity" ).style.display = "none";
			document.getElementById( "dropoffZipCodeTd" ).style.display = "none";
			document.getElementById( "dropoffFindCarsWithInTd" ).style.display = "none";
		} else if( dropoffLocation == CAR_DROPOFF_AT_CITY ) {
			clearStateAndZipForDropoff( _fromCarWidget );
			document.getElementById( "dropoffAsAirport" ).style.display = "none";
			document.getElementById( "dropoffAsCity" ).style.display = "";
			document.getElementById( "dropoffZipCodeTd" ).style.display = "";
			document.getElementById( "dropoffFindCarsWithInTd" ).style.display = "";
		} else if( dropoffLocation == CAR_DROPOFF_SAME_AS_PICKUP ) {
			document.getElementById( "dropoffAsAirport" ).style.display = "none";
			document.getElementById( "dropoffAsCity" ).style.display = "none";
			document.getElementById( "dropoffZipCodeTd" ).style.display = "none";
			document.getElementById( "dropoffFindCarsWithInTd" ).style.display = "none";
		}
	} else if( CAR_SEARCH_POPUP == _fromCarWidget ) {
		var dropoffLocation  = parseInt( document.getElementById( "dropoffLocationTypePopup" ).value );
		if( dropoffLocation == CAR_DROPOFF_AT_AIRPORT ) {
			document.getElementById( "dropoffAsAirportPopup" ).style.display = "";
			document.getElementById( "dropoffAsCityPopup" ).style.display = "none";
			document.getElementById( "dropoffZipCodeBlockPopup" ).style.display = "none";
			document.getElementById( "dropoffFindCarsWithInBlockPopup" ).style.display = "none";
		} else if( dropoffLocation == CAR_DROPOFF_AT_CITY ) {
			clearStateAndZipForDropoff( _fromCarWidget );
			document.getElementById( "dropoffAsAirportPopup" ).style.display = "none";
			document.getElementById( "dropoffAsCityPopup" ).style.display = "";
			document.getElementById( "dropoffZipCodeBlockPopup" ).style.display = "";
			document.getElementById( "dropoffFindCarsWithInBlockPopup" ).style.display = "";
		} else if( dropoffLocation == CAR_DROPOFF_SAME_AS_PICKUP ) {
			document.getElementById( "dropoffAsAirportPopup" ).style.display = "none";
			document.getElementById( "dropoffAsCityPopup" ).style.display = "none";
			document.getElementById( "dropoffZipCodeBlockPopup" ).style.display = "none";
			document.getElementById( "dropoffFindCarsWithInBlockPopup" ).style.display = "none";
		}
	}
}

function loadCarPickupOrDropoffAirports( event, fromWhere, carPickupOrDropoff ) {
	var cityNameField;
	var content = "";
	//Cannot set _event = event because 
	//when loadCarPickupCities 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};
	_fromCarWidget = parseInt(fromWhere);
	_carPickupOrDropoff = parseInt( carPickupOrDropoff );
	
	if( CAR_SEARCH_WIDGET == _fromCarWidget ) {
		if( _carPickupOrDropoff == CAR_PICKUP_AT_AIRPORT ) {
			cityNameField = document.getElementById( "pickupAirportTextWidget" );
		}
		else if( _carPickupOrDropoff == CAR_DROPOFF_AT_AIRPORT ) {
			cityNameField = document.getElementById( "dropoffAirportTextWidget" );
		}
		content = "mainContent";
	}
	else if ( CAR_SEARCH_POPUP == _fromCarWidget ) {
		if( _carPickupOrDropoff == CAR_PICKUP_AT_AIRPORT ) {
			cityNameField = document.getElementById( "pickupAirportTextPopup" );
		}
		else if( _carPickupOrDropoff == CAR_DROPOFF_AT_AIRPORT ) {
			cityNameField = document.getElementById( "dropoffAirportTextPopup" );
		}
		content = "searchPopupDivContainer";
	}

	var cityName = cityNameField.value.toUpperCase();
	_cityName = cityName;

	//ESC key pressed
	if( _event.keyCode == 27 ){
		hideSuggestionBox();
		return false;
	}
	
	if(cityName.length < 3) {
	 	airportInfos = null;
	 	hideSuggestionBox();
	}
	else if( cityName.length >= 3 && trim( cityName ) != "") {
		if(airportInfos == null) {
			var queryString = "";
			queryString += "sh=2";
			queryString += '&departureCity=' + cityName;
			makeAjaxCall( 'searchHelper.act', queryString, null, content, 'callbackCarPickupOrDropoffAirports', '' );			
		}
		else {
			callbackCarPickupOrDropoffAirports();		
		}
	}	
}

function callbackCarPickupOrDropoffAirports( airportInfosJson ) {
	if( hasMessage( this ) ) {
		if( CAR_SEARCH_WIDGET == _fromCarWidget  ) {
			showMessage(this.messageType, this.messageCode, this.message, 'dataContent');
		} else if ( CAR_SEARCH_POPUP == _fromCarWidget  ) {
			showMessage(this.messageType, this.messageCode, this.message, 'searchPopupDivContainer');
		}
	} else {
		if( airportInfosJson ) {
			airportInfos = eval(airportInfosJson);
		}
		
		var suggestions = new Array();
		_suggestionCityNames = 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;
					_suggestionCityNames[airportInfos[index].code] = airportInfos[index].cityName;
					_cityNameAndState = airportInfos[index].cityName + ", " + airportInfos[index].state;
				}
				if(airportInfos[index].cityName.toUpperCase().indexOf(_cityName) == 0) {
					suggestions[airportInfos[index].code] = "(" + airportInfos[index].code + ") " + airportInfos[index].name;
					_suggestionCityNames[airportInfos[index].code] = airportInfos[index].cityName;
					_cityNameAndState = airportInfos[index].cityName + ", " + airportInfos[index].state;
				}
				if(airportInfos[index].code.toUpperCase() == _cityName) {
					suggestions[airportInfos[index].code] = "(" + airportInfos[index].code + ") " + airportInfos[index].name;
					_suggestionCityNames[airportInfos[index].code] = airportInfos[index].cityName;
					_cityNameAndState = airportInfos[index].cityName + ", " + airportInfos[index].state;
				}
			}
		}
		
		if( CAR_SEARCH_WIDGET == _fromCarWidget ) {
			if( _carPickupOrDropoff == CAR_PICKUP_AT_AIRPORT ) {
				document.getElementById( "pickupAirportCodeWidget" ).value ="";
				showSuggestionBox( _event, 'pickupAirportTextWidget', suggestions, 'tc04 w295 fs11 h90','No airports found with given criteria' );
			}
			else if( _carPickupOrDropoff == CAR_DROPOFF_AT_AIRPORT ) {
				document.getElementById( "dropoffAirportCodeWidget" ).value ="";
				showSuggestionBox( _event, 'dropoffAirportTextWidget', suggestions, 'tc04 w295 fs11 h90','No airports found with given criteria' );
			} 
		}
		else {
			if( _carPickupOrDropoff == CAR_PICKUP_AT_AIRPORT ) {
				document.getElementById( "pickupAirportCodePopup" ).value ="";
				showSuggestionBox( _event, 'pickupAirportTextPopup', suggestions, 'tc04 w295 fs11 h90','No airports found with given criteria' );
			}
			else if( _carPickupOrDropoff == CAR_DROPOFF_AT_AIRPORT ) {
				document.getElementById( "dropoffAirportCodePopup" ).value ="";
				showSuggestionBox( _event, 'dropoffAirportTextPopup', suggestions, 'tc04 w295 fs11 h90','No airports found with given criteria' );
			}
		}
	}
	return true;
}

function loadCarPickupOrDropoffCities( event, fromWhere, carPickupOrDropoff ) {
	var cityNameField;
	var content = "";
	//Cannot set _event = event because 
	//when loadCarPickupCities 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};
	_fromCarWidget = parseInt(fromWhere);
	_carPickupOrDropoff = parseInt( carPickupOrDropoff );
	
	if( CAR_SEARCH_WIDGET == _fromCarWidget ) {
		if( _carPickupOrDropoff == CAR_PICKUP_AT_CITY ) {
			cityNameField = document.getElementById( "pickupCityTextWidget" );
		}
		else if( _carPickupOrDropoff == CAR_DROPOFF_AT_CITY ) {
			cityNameField = document.getElementById( "dropoffCityTextWidget" );
		}
		content = "mainContent";
	}
	else if ( CAR_SEARCH_POPUP == _fromCarWidget ) {
		if( _carPickupOrDropoff == CAR_PICKUP_AT_CITY ) {
			cityNameField = document.getElementById( "pickupCityTextPopup" );
		}
		else if( _carPickupOrDropoff == CAR_DROPOFF_AT_CITY ) {
			cityNameField = document.getElementById( "dropoffCityTextPopup" );
		}
		content = "searchPopupDivContainer";
	}

	var cityName = cityNameField.value.toUpperCase();
	_cityName = cityName;

	//ESC key pressed
	if( _event.keyCode == 27 ){
		hideSuggestionBox();
		return false;
	}
	
	if(cityName.length < 3) {
		cityInfos = null;
	 	hideSuggestionBox();
	}
	else if( cityName.length >= 3 && trim( cityName ) != "") {
		if(cityInfos == null) {
			var queryString = "";
			queryString += "cs=4";
			queryString += '&pickupCity=' + cityName;
			makeAjaxCall( 'carSearch.act', queryString, null, content, 'callbackLoadCarPickupOrDropoffCities', '' );			
		}
		else {
			callbackLoadCarPickupOrDropoffCities();		
		}
	}	
}

function callbackLoadCarPickupOrDropoffCities( citiesAndStates ) {
	if( hasMessage( this ) ) {
		if( CAR_SEARCH_WIDGET == _fromCarWidget  ) {
			showMessage(this.messageType, this.messageCode, this.message, 'dataContent');
		} else if ( CAR_SEARCH_POPUP == _fromCarWidget  ) {
			showMessage(this.messageType, this.messageCode, this.message, 'searchPopupDivContainer');
		}
	} else {
		var suggestions = new Array();
		if( citiesAndStates ) {
			for(var index = 0; index < citiesAndStates.length; ++index) {
				var cityAndState =  citiesAndStates[ index ].split( "," );
				suggestions[trim( cityAndState[0] ) +"-"+ trim( cityAndState[1] ) ] = trim( cityAndState[0] ) + " - " + trim( cityAndState[1] );
			}
		}
		
		if( CAR_SEARCH_WIDGET == _fromCarWidget ) {
			if( _carPickupOrDropoff == CAR_PICKUP_AT_CITY ) {
				document.getElementById( "pickupCityCodeWidget" ).value ="";
				showSuggestionBox( _event, 'pickupCityTextWidget', suggestions, 'tc04 w295 fs11 h90','No cities found with given criteria' );
			}
			else if( _carPickupOrDropoff == CAR_DROPOFF_AT_CITY ) {
				document.getElementById( "dropoffCityCodeWidget" ).value ="";
				showSuggestionBox( _event, 'dropoffCityTextWidget', suggestions, 'tc04 w295 fs11 h90','No cities found with given criteria' );
			} 
		}
		else {
			if( _carPickupOrDropoff == CAR_PICKUP_AT_CITY ) {
				document.getElementById( "pickupCityCodePopup" ).value ="";
				showSuggestionBox( _event, 'pickupCityTextPopup', suggestions, 'tc04 w215 fs11 h90','No cities found with given criteria' );
			}
			else if( _carPickupOrDropoff == CAR_DROPOFF_AT_CITY ) {
				document.getElementById( "dropoffCityCodePopup" ).value ="";
				showSuggestionBox( _event, 'dropoffCityTextPopup', suggestions, 'tc04 w215 fs11 h90','No cities found with given criteria' );
			}
		}
	}
	return true;
}

function validateZip( fromWhere, isPickup ) {
	clearErrorElements();
	_fromCarWidget = parseInt(fromWhere);
	var zipCode = null;
	var zipField = null;
	var queryString = 'cs=10';

	if( CAR_SEARCH_WIDGET == _fromCarWidget ) {
		if( isPickup ) {
			var pickupLocation = parseInt( document.getElementById( "pickupLocationType" ).value );
			if( pickupLocation == CAR_PICKUP_AT_CITY ) {
				zipCode = document.getElementById( "pickupZipCode" ).value;
				zipField = "pickupZipCode";
				if( zipCode.length == 5 ) {
					queryString += '&pickupCity=' + document.getElementById( "pickupCityCodeWidget" ).value;
					queryString += '&pickupZip=' + zipCode;
				}
			}
		} else {
			var dropoffLocation  = parseInt( document.getElementById( "dropoffLocationType" ).value );
			if( dropoffLocation == CAR_DROPOFF_AT_CITY ) {
				zipCode = document.getElementById( "dropoffZipCode" ).value;
				zipField = "dropoffZipCode";
				if( zipCode.length == 5 ) {
					queryString += '&dropoffCity=' + document.getElementById( "dropoffCityCodeWidget" ).value;
					queryString += '&dropoffZip=' + zipCode;
				}
			}
		}
	} else if( CAR_SEARCH_POPUP == _fromCarWidget ) {
		if( isPickup ) {
			var pickupLocation = parseInt( document.getElementById( "pickupLocationTypePopup" ).value );
			if( pickupLocation == CAR_PICKUP_AT_CITY ) {
				zipCode = document.getElementById( "pickupZipCodePopup" ).value;
				zipField = "pickupZipCodePopup";
				if( zipCode.length == 5 ) {
					queryString += '&pickupCity=' + document.getElementById( "pickupCityCodePopup" ).value;
					queryString += '&pickupZip=' + zipCode;
				}
			}
		} else {
			var dropoffLocation  = parseInt( document.getElementById( "dropoffLocationTypePopup" ).value );
			if( dropoffLocation == CAR_DROPOFF_AT_CITY ) {
				zipCode = document.getElementById( "dropoffZipCodePopup" ).value;
				zipField = "dropoffZipCodePopup";
				if( zipCode.length == 5 ) {
					queryString += '&dropoffCity=' + document.getElementById( "dropoffCityCodePopup" ).value;
					queryString += '&dropoffZip=' + zipCode;
				}
			}
		}
	}

	if( zipCode.length < 5 && trim( zipCode ) != '' ) {
		var msg ="Please enter valid zip code.";
		if( CAR_SEARCH_POPUP == _fromCarWidget ) {
			showErrorMessage( msg, 'searchPopupDivContainer', zipField, '1px solid #7f9db9');
		} else if( CAR_SEARCH_WIDGET == _fromCarWidget ) {
			showErrorMessage( msg, 'dataContent', zipField, '1px solid #7f9db9');
		}
		return false;
	}

	makeAjaxCall( 'carSearch.act', queryString, null, null, 'callbackValidateZip', '' );
}

function callbackValidateZip() {
	if( hasMessage( this ) ) {
		if( CAR_SEARCH_WIDGET == _fromCarWidget  ) {
			showErrorMessage(this.message, 'dataContent');
		} else if ( CAR_SEARCH_POPUP == _fromCarWidget  ) {
			showErrorMessage(this.message, 'searchPopupDivContainer');
		}
	}
	return true;
}

function searchCarAgencies() {
	clearErrorElements();
	var queryString = 'cs=1';
	var trackingText = '';
	_couponCode = '';	
	_carPopupSearch = 'false';

	var pickupAirport = '';
	var pickupCity = '';
	var pickupLocation = parseInt( document.getElementById( "pickupLocationType" ).value );
	if( pickupLocation == CAR_PICKUP_AT_AIRPORT ) {
		pickupAirport = document.getElementById( "pickupAirportCodeWidget" ).value;
		var pickupAirportText = document.getElementById( "pickupAirportTextWidget" ).value;
		if( trim( pickupAirportText ) == '' ) {
			pickupAirport = '';
		}
		if( trim( pickupAirport ) == "" ) {
			var msg ="Please select a pick up airport.";
			showErrorMessage( msg, 'dataContent', 'pickupAirportTextWidget', '1px solid #7f9db9');
			return false;
		}
		queryString += '&pickupCity=' + pickupAirport;
		queryString += '&pickupAsAirport=' + true;
		trackingText = '/rc/booking/searchWidget/carMatrix/ALL';
	}
	else if( pickupLocation == CAR_PICKUP_AT_CITY ) {
		pickupCity = document.getElementById( "pickupCityCodeWidget" ).value;
		var pickupCityText = document.getElementById( "pickupCityTextWidget" ).value;
		if( trim( pickupCityText ) == '' ) {
			pickupCity ='';
		}
		var pickupZip = trim( document.getElementById( "pickupZipCode" ).value );
		if (( trim( pickupCity ) == "" ) && ( pickupZip == "" )) {
			var msg ="Please enter pick up city or pick up zip code.";
			showErrorMessage( msg, 'dataContent', 'pickupCityTextWidget', '1px solid #7f9db9');
			return false;
		}
		queryString += '&pickupCity=' + pickupCity;
		queryString += '&pickupAsAirport=' + false;
		queryString += '&pickupZip=' + pickupZip ;
		queryString += '&pickupCityRadius=' + document.getElementById( "pickupFindCarsWithIn" ).value;
		
		trackingText = '/rc/booking/searchWidget/rentalLocations/ALL';
	}
	
	var dropoffAirport = '';
	var dropoffCity = '';
	var dropoffLocation = parseInt( document.getElementById( "dropoffLocationType" ).value );
	if( dropoffLocation == CAR_DROPOFF_SAME_AS_PICKUP ) {
		if( pickupLocation == CAR_PICKUP_AT_AIRPORT ) {
			dropoffAirport = document.getElementById( "pickupAirportCodeWidget" ).value;
			var dropoffAirportText = document.getElementById( "pickupAirportTextWidget" ).value;
			queryString += '&dropoffCity=' + dropoffAirport;
			queryString += '&dropoffAsAirport=' + true;
		} else if( pickupLocation == CAR_PICKUP_AT_CITY ) {
			dropoffCity = document.getElementById( "pickupCityCodeWidget" ).value; //Since dropoff city is same as pickup city
			var pickupCityText = document.getElementById( "pickupCityTextWidget" ).value;
			if( trim( pickupCityText ) == '' ) {
				dropoffCity ='';
			}
			queryString += '&dropoffCity=' + dropoffCity; 
			queryString += '&dropoffAsAirport=' + false;
			queryString += '&dropoffZip=' + document.getElementById( "pickupZipCode" ).value;
			queryString += '&dropoffCityRadius=' + document.getElementById( "pickupFindCarsWithIn" ).value;
		}
	} else if( dropoffLocation == CAR_DROPOFF_AT_AIRPORT ) {
		dropoffAirport = document.getElementById( "dropoffAirportCodeWidget" ).value;
		var dropoffAirportText = document.getElementById( "dropoffAirportTextWidget" ).value;
		if( trim( dropoffAirportText ) == '' ) {
			dropoffAirport ='';
		}
		if( trim( dropoffAirport ) == "" ) {
			var msg ="Please select a drop off airport.";
			showErrorMessage( msg, 'dataContent', 'dropoffAirportTextWidget', '1px solid #7f9db9');
			return false;
		}
		queryString += '&dropoffCity=' + dropoffAirport;
		queryString += '&dropoffAsAirport=' + true;
	} else if( dropoffLocation == CAR_DROPOFF_AT_CITY ) {
		dropoffCity = document.getElementById( "dropoffCityCodeWidget" ).value;
		var dropoffCityText = document.getElementById( "dropoffCityTextWidget" ).value;
		if( trim( dropoffCityText ) == '' ) {
			dropoffCity = '';
		}
		var dropoffZip =  trim( document.getElementById( "dropoffZipCode" ).value );
		if (( trim( dropoffCity ) == "" ) && ( dropoffZip == "" )) {
			var msg ="Please enter drop off city or zip code.";
			showErrorMessage( msg, 'dataContent', 'dropoffCityTextWidget', '1px solid #7f9db9');
			return false;
		}
		queryString += '&dropoffCity=' + dropoffCity;
		queryString += '&dropoffAsAirport=' + false;
		queryString += '&dropoffZip=' + dropoffZip;
		queryString += '&dropoffCityRadius=' + document.getElementById( "dropoffFindCarsWithIn" ).value;
	}
	
	var pickupDate = document.getElementById( "pickupDate" ).value;
	var dropoffDate = document.getElementById( "dropoffDate" ).value;
	if( pickupDate == '' || pickupDate == "mm/dd/yyyy" ) {
		showErrorMessage( "Please select a pickup date" ,'dataContent', 'pickupDate', '1px solid #7f9db9' );
		return false;
	} else if( !isDate( 'pickupDate', 'dataContent' ) ) {
		document.getElementById( "pickupDate" ).value = 'mm/dd/yyyy';
		document.getElementById( "pickupDate" ).select();
		return false;
	} else if( isPastDate( 'pickupDate' ) ) {
		return false;
	}
	
	if( dropoffDate == '' || dropoffDate == "mm/dd/yyyy" ) {
		showErrorMessage( "Please select a dropoff date" ,'dataContent', 'dropoffDate', '1px solid #7f9db9' );
		return false;
	} else if( !isDate( 'dropoffDate', 'dataContent' ) ) {
		document.getElementById( "dropoffDate" ).value = 'mm/dd/yyyy';
		document.getElementById( "dropoffDate" ).select();
		return false;
	} else if( isPastDate( 'dropoffDate' ) ) {
		return false;
	}
	
	var fromDate = new Date( pickupDate );
	var toDate = new Date( dropoffDate );
	if ( fromDate > toDate ) {
		var msg = "Please select a car drop off date which is greater than car pick up date.";
		showErrorMessage( msg ,'dataContent', 'dropoffDate', '1px solid #7f9db9' );
		return false;
	}
	
	var pickupTime = document.getElementById( "pickupTime" ).value;
	var dropoffTime = document.getElementById( "dropoffTime" ).value;
	
	/* Validation of same day pick up time - drop off time combination, with drop off time later than pick up time.*/
	if( fromDate.getTime() == toDate.getTime() ) {
		var pickupHours = getHoursFromTime( pickupTime );
		var dropoffHours = getHoursFromTime( dropoffTime );
		var numberOfHours = pickupHours - dropoffHours;
		if( numberOfHours >= 0 ) {
			var msg = "Car drop-off time should be after pick-up time.";
			showErrorMessage( msg ,'searchPopupDivContainer', 'dropoffTime', '1px solid #7f9db9' );
			return false;
		}
	}
	var driverAge =  document.getElementById( "driverAge" ).value;
	var carCategory = document.getElementById( "carCategory" ).value;
	
	queryString += '&pickupDate=' + pickupDate;
	queryString += '&dropoffDate=' + dropoffDate;
	queryString += '&pickupTime=' + pickupTime;
	queryString += '&dropoffTime=' + dropoffTime;
	queryString += '&driverAge=' + driverAge;
	queryString += '&carCategory=' + carCategory;
	
	trackEvent("Search Car", "Click", "Car Rental Search");
	
	disableElement ( 'dataContent' , true );
	
	makeAjaxCallWithWaitingDiv( 'carSearch.act', queryString, null, 'rightContent', 'callbackSearchCarAgencies', null, trackingText );
}

function callbackSearchCarAgencies() {
	if ( ! showMessage(this.messageType, this.messageCode, this.message , 'dataContent' ) ) {
		var pickupLocation = document.getElementById( "pickupLocationType" ).value;
		var dropoffLocation = document.getElementById( "dropoffLocationType" ).value;
		if( ( pickupLocation == CAR_PICKUP_AT_CITY ) || ( dropoffLocation == CAR_DROPOFF_AT_CITY ) ) {
			disableElement ( 'dataContent' , false );
		} else {
			loadCarTripSummary( CarTripSummaryDisplayConstants.DISPLAY_CAR_TRIP_SUMMARY_UPTO_AGENCY_LOCATION );
		}
	}
	return true;
}

function loadCarDriverAges( fromWhere ) {
	_fromCarWidget = parseInt(fromWhere);
	var queryString = 'cs=2';
	var cityCode = null;
	var driverAge = null;
	var pickupAsAirport = true; 
	if( CAR_SEARCH_WIDGET == _fromCarWidget ) {
		driverAge = document.getElementById( "driverAge" ).value;
		var pickupLocation = parseInt( document.getElementById( "pickupLocationType" ).value );
		if( pickupLocation == CAR_PICKUP_AT_AIRPORT ) {
			cityCode = document.getElementById( "pickupAirportCodeWidget" ).value;			
		} else if( pickupLocation == CAR_PICKUP_AT_CITY ) {
			pickupAsAirport = false;
			cityCode = document.getElementById( "pickupCityCodeWidget" ).value;
		}	
	} else if( CAR_SEARCH_POPUP == _fromCarWidget ) {
		driverAge = document.getElementById( "driverAgePopup" ).value
		var pickupLocation = parseInt( document.getElementById( "pickupLocationTypePopup" ).value );
		if( pickupLocation == CAR_PICKUP_AT_AIRPORT ) {
			cityCode = document.getElementById( "pickupAirportCodePopup" ).value;
		} else if( pickupLocation == CAR_PICKUP_AT_CITY ) {
			pickupAsAirport = false;
			cityCode = document.getElementById( "pickupCityCodePopup" ).value;
		}
	}
	if( cityCode != null ) {
		queryString += '&pickupCity=' + cityCode;
		queryString += '&pickupAsAirport=' + pickupAsAirport;
	}
	queryString += '&driverAge=' + driverAge;
	makeAjaxCall( 'carSearch.act', queryString, null, null, 'callbackLoadCarDriverAges', '' );
}

function callbackLoadCarDriverAges( carDriverAges ) {
	if( !showMessage(this.messageType, this.messageCode, this.message, 'dataContent' ) ) {
		if( CAR_SEARCH_WIDGET == _fromCarWidget ) {
			document.getElementById( "driverAgeDiv" ).innerHTML = "<select name='driverAge' id='driverAge' class='fs11 mt03 textbox w105'>" + carDriverAges + "</select>";
		} else if( CAR_SEARCH_POPUP == _fromCarWidget ) {
			document.getElementById( "driverAgeDivPopup" ).innerHTML = "<select name='driverAgePopup' id='driverAgePopup' class='fs11 mt03 textbox w105'>" + carDriverAges + "</select>";
		}
	}
	return true;
}

function loadCarSearchPopup( vendorId, couponCode, agencyId, landingPageVendorName ) {
	// create pop up div for car search criteria.
	var trackingText = '/rc/booking/popupWidget/popup/';
	trackingText += (landingPageVendorName == '' ? 'ALL' : landingPageVendorName) ;
	
	if (couponCode == ''){
		trackingText += '/LPF';
	}
	else{
		trackingText += '/' + couponCode;
	}
		
	var searchPopupDivContainer = document.getElementById('searchPopupDivContainer');
	if( isNull( searchPopupDivContainer ) ) {
		searchPopupDivContainer = createPopupDiv('searchPopupDivContainer', 0, 0, 703, -1, 200, false, true,  "");
	}
	
	// create action code to open search pop up.
	var queryString = 'cs=3';
	queryString += '&selectedVendorId=' + vendorId;
	queryString += '&selectedCouponCode=' + couponCode;
	queryString += '&selectedAgencyId=' + agencyId;
	queryString += '&carVendorName=' + landingPageVendorName;
	
	makeAjaxCall( 'carSearch.act', queryString, null, 'searchPopupDivContainer', 'callbackLoadCarSearchPopup', trackingText, '');
}

function callbackLoadCarSearchPopup() {
	if(!showMessage(this.messageType, this.messageCode, this.message, 'dataContent')) {
		var searchPopupDiv = document.getElementById('searchPopupDiv');
		if(searchPopupDiv) {
			showBlock('searchPopupDivContainer');
			positionBlockCentrally('searchPopupDivContainer');	
			disableElement('dataContent', true);
			searchPopupDiv.focus();
		}
		return true;
	}
	return false;
}

function searchCarAgenciesFromPopup( selectedVendorId, selectedCouponCode, selectedAgencyId, landingPageVendorName ) {
	clearErrorElements();
	var queryString = 'cs=1';
	var trackingText = '';
	_couponCode = (selectedCouponCode == '' ? 'LPF' : selectedCouponCode);
	_carPopupSearch = 'true';
	_carCompanyName = (landingPageVendorName == '' ? 'ALL' : landingPageVendorName);
	
	var pickupLocation = parseInt( document.getElementById( "pickupLocationTypePopup" ).value );
	if( pickupLocation == CAR_PICKUP_AT_AIRPORT ) {
		var pickupAirport = document.getElementById( "pickupAirportCodePopup" ).value;
		var pickupAirportText = document.getElementById( "pickupAirportTextPopup" ).value;
		if( trim( pickupAirportText ) == '' ) {
			pickupAirport = '';
		}
		if( trim( pickupAirport ) == "" ) {
			var msg = "Please select a pick up airport.";
			showErrorMessage( msg, 'searchPopupDivContainer', 'pickupAirportTextPopup', '1px solid #7f9db9');
			return false;
		}
		queryString += '&pickupCity=' + pickupAirport;
		queryString += '&pickupAsAirport=' + true;
		trackingText = '/rc/booking/popupWidget/carMatrix/' + _carCompanyName + '/' + _couponCode;
	}
	else if( pickupLocation == CAR_PICKUP_AT_CITY ) {
		var pickupCity = document.getElementById( "pickupCityCodePopup" ).value;
		var pickupCityText = document.getElementById( "pickupCityTextPopup" ).value;
		if( trim( pickupCityText ) == '' ) {
			pickupCity = '';
		}
		var pickupZip = trim( document.getElementById( "pickupZipCodePopup" ).value );
		if( ( trim( pickupCity ) == "" ) && ( pickupZip == "" )) {
			var msg ="Please enter pick up city or pick up zip code.";
			showErrorMessage( msg, 'searchPopupDivContainer', 'pickupCityTextPopup', '1px solid #7f9db9');
			return false;
		}
		queryString += '&pickupCity=' + pickupCity;
		queryString += '&pickupAsAirport=' + false;
		queryString += '&pickupZip=' + pickupZip;
		queryString += '&pickupCityRadius=' + document.getElementById( "pickupFindCarsWithInPopup" ).value;
		trackingText = '/rc/booking/popupWidget/rentalLocations/' + _carCompanyName + '/' + _couponCode;
	}
	
	var dropoffAirport = '';
	var dropoffCity = '';
	var dropoffLocation = parseInt( document.getElementById( "dropoffLocationTypePopup" ).value );
	if( dropoffLocation == CAR_DROPOFF_SAME_AS_PICKUP ) {
		if( pickupLocation == CAR_PICKUP_AT_AIRPORT ) {
			dropoffAirport = document.getElementById( "pickupAirportCodePopup" ).value;
			queryString += '&dropoffCity=' + dropoffAirport;
			queryString += '&dropoffAsAirport=' + true;
		} else if( pickupLocation == CAR_PICKUP_AT_CITY ) {
			dropoffCity = document.getElementById( "pickupCityCodePopup" ).value; //Since dropoff is same as pickup
			var pickupCityText = document.getElementById( "pickupCityTextPopup" ).value;
			if( trim( pickupCityText ) == '' ) {
				dropoffCity = '';
			}
			queryString += '&dropoffCity=' + dropoffCity; 
			queryString += '&dropoffAsAirport=' + false;
			queryString += '&dropoffZip=' + document.getElementById( "pickupZipCodePopup" ).value;
			queryString += '&dropoffCityRadius=' + document.getElementById( "pickupFindCarsWithInPopup" ).value;
		}
	} else if( dropoffLocation == CAR_DROPOFF_AT_AIRPORT ) {
		dropoffAirport = document.getElementById( "dropoffAirportCodePopup" ).value;
		var dropoffAirportText = document.getElementById( "dropoffAirportTextPopup" ).value;
		if( trim( dropoffAirportText ) == '' ) {
			dropoffAirport = '';	
		}
		if( trim( dropoffAirport ) == "" ) {
			var msg ="Please select a drop off airport.";
			showErrorMessage( msg, 'searchPopupDivContainer', 'dropoffAirportTextPopup', '1px solid #7f9db9');
			return false;
		}
		queryString += '&dropoffCity=' + dropoffAirport;
		queryString += '&dropoffAsAirport=' + true;
	} else if( dropoffLocation == CAR_DROPOFF_AT_CITY ) {
		dropoffCity = document.getElementById( "dropoffCityCodePopup" ).value;
		var dropoffCityText = document.getElementById( "dropoffCityTextPopup" ).value;
		if( trim( dropoffCityText ) == '' ) {
			dropoffCity = '';
		}
		var dropoffZip = trim( document.getElementById( "dropoffZipCodePopup" ).value );
		if (( trim( dropoffCity ) == "" ) && ( dropoffZip == "" )) {
			var msg ="Please enter drop off city or zip code.";
			showErrorMessage( msg, 'searchPopupDivContainer', 'dropoffCityTextPopup', '1px solid #7f9db9');
			return false;
		}
		queryString += '&dropoffCity=' + dropoffCity;
		queryString += '&dropoffAsAirport=' + false;
		queryString += '&dropoffZip=' + dropoffZip;
		queryString += '&dropoffCityRadius=' + document.getElementById( "dropoffFindCarsWithInPopup" ).value;
	}

	var pickupDate = document.getElementById( "pickupDatePopup" ).value;
	var dropoffDate = document.getElementById( "dropoffDatePopup" ).value;
	if( pickupDate == '' || pickupDate == "mm/dd/yyyy" ) {
		showErrorMessage( "Please select a pickup date" ,'searchPopupDivContainer', 'pickupDatePopup', '1px solid #7f9db9' );
		return false;
	} else if( !isDate( 'pickupDatePopup', 'searchPopupDivContainer' ) ) {
		document.getElementById( "pickupDatePopup" ).value = 'mm/dd/yyyy';
		document.getElementById( "pickupDatePopup" ).select();
		return false;
	} else if( isPastDate( 'pickupDatePopup' ) ) {
		return false;
	}
	if( dropoffDate == '' || dropoffDate == "mm/dd/yyyy" ) {
		showErrorMessage( "Please select a dropoff date" ,'searchPopupDivContainer', 'dropoffDatePopup', '1px solid #7f9db9' );
		return false;
	} else if( !isDate( 'dropoffDatePopup', 'searchPopupDivContainer' ) ) {
		document.getElementById( "dropoffDatePopup" ).value = 'mm/dd/yyyy';
		document.getElementById( "dropoffDatePopup" ).select();
		return false;
	} else if( isPastDate( 'dropoffDatePopup' ) ) {
		return false;
	}
	
	var fromDate = new Date( pickupDate );
	var toDate = new Date( dropoffDate );
	
	if ( fromDate > toDate ) {
		var msg = "Please select a car drop off date which is greater than car pick up date.";
		showErrorMessage( msg ,'searchPopupDivContainer', 'dropoffDatePopup', '1px solid #7f9db9' );
		return false;
	}
	
	var pickupTime = document.getElementById( "pickupTimePopup" ).value;
	var dropoffTime = document.getElementById( "dropoffTimePopup" ).value;

	/* Validation of same day pick up time - drop off time combination, with drop off time later than pick up time.*/
	if( fromDate.getTime() == toDate.getTime() ) {
		var pickupHours = getHoursFromTime( pickupTime );
		var dropoffHours = getHoursFromTime( dropoffTime );
		var numberOfHours = pickupHours - dropoffHours;
		if( numberOfHours >= 0 ) {
			var msg = "Car drop-off time should be after pick-up time.";
			showErrorMessage( msg ,'searchPopupDivContainer', 'dropoffTimePopup', '1px solid #7f9db9' );
			return false;
		}
	}

	var driverAge =  document.getElementById( "driverAgePopup" ).value;
	var carCategory = document.getElementById( "carCategoryPopup" ).value;
	
	queryString += '&pickupDate=' + pickupDate;
	queryString += '&dropoffDate=' + dropoffDate;
	queryString += '&pickupTime=' + pickupTime;
	queryString += '&dropoffTime=' + dropoffTime;
	queryString += '&driverAge=' + driverAge;
	queryString += '&carCategory=' + carCategory;
	queryString += '&selectedVendorId=' + selectedVendorId;
	queryString += '&selectedCouponCode=' + selectedCouponCode;
	queryString += '&selectedAgencyId=' + selectedAgencyId;
	queryString += '&carVendorName=' + landingPageVendorName;
	queryString += '&fromPopup=true';
	
	trackEvent("Search Car", "Click", "Car Rental Search");
	
	disableElement ( 'dataContent' , true );
	disableElement ( 'searchPopupDivContainer' , true );
	
	makeAjaxCallWithWaitingDiv( 'carSearch.act', queryString, null, 'rightContent', 'callbackSearchCarAgenciesPopup', null, trackingText );
}

function callbackSearchCarAgenciesPopup( errorMessage, actionCode ) {
	if ( !showMessage(this.messageType, this.messageCode, this.message , 'searchPopupDivContainer' ) ) {
		if( isNull( errorMessage) && isNull(actionCode) ) {
			var pickupLocation = parseInt( document.getElementById( "pickupLocationTypePopup" ).value );
			var dropoffLocation = parseInt( document.getElementById( "dropoffLocationTypePopup" ).value );
			if( ( pickupLocation == CAR_PICKUP_AT_CITY ) || ( dropoffLocation == CAR_DROPOFF_AT_CITY ) ) {
				hideBlock( 'searchPopupDivContainer' );
				disableElement ( 'searchPopupDivContainer' , false );
				disableElement ( 'dataContent' , false );
				loadLeftContent('leftContent.act','lc=19&lbc=0' );
			} else {
				loadCarTripSummary( CarTripSummaryDisplayConstants.DISPLAY_CAR_TRIP_SUMMARY_UPTO_AGENCY_LOCATION );
			}
		} else {
			if( isNull(actionCode) ) {
				showErrorMessage( errorMessage ,'searchPopupDivContainer' );
			} else {
				loadCarCouponOverridePopup( errorMessage, actionCode );
			}
		}
	}
	return true;
}

function loadCarTripSummary( displayCarTripSummaryUpto){
	var queryString = 'lc=21&lbc=0';
	queryString += "&displayCarTripSummaryUpto=" + displayCarTripSummaryUpto; 
	disableElement ( 'dataContent' , true );
	makeAjaxCallWithWaitingDiv( 'leftContent.act', queryString, null, 'leftContent', 'callbackLoadCarTripSummary', null, null );
}

function callbackLoadCarTripSummary(){
	if ( ! showMessage(this.messageType, this.messageCode, this.message , 'dataContent' ) ) {
		hideBlock( 'searchPopupDivContainer' );
		disableElement ( 'searchPopupDivContainer' , false );
		disableElement ( 'dataContent' , false );
	}
}

function loadCarSearchWidget(){
	var queryString = 'lc=20';
	disableElement ( 'dataContent' , true );
	makeAjaxCallWithWaitingDiv( 'leftContent.act', queryString, null, 'leftContent', 'callbackLoadCarTripSummary', null, null );
}

function loadCarCouponOverridePopup( errorMessage, actionCode ) {
	var carCouponOverridePopupDivContainer = document.getElementById( 'carCouponOverridePopupDivContainer' );
	if( isNull( carCouponOverridePopupDivContainer ) ) {
		carCouponOverridePopupDivContainer = createPopupDiv('carCouponOverridePopupDivContainer', 0, 0, 450, -1, 300, false, true, "");
		carCouponOverridePopupDivContainer.style.height = toPixels(110);
	}

	var queryString = 'cs=11';
	queryString += '&errorMessage=' + errorMessage;
	queryString += '&actionCode=' + actionCode;
	makeAjaxCall( 'carSearch.act', queryString, null, 'carCouponOverridePopupDivContainer', 'callbackLoadCarCouponOverridePopup', '');
}

function callbackLoadCarCouponOverridePopup() {
	 if( !showMessage(this.messageType, this.messageCode, this.message , 'searchPopupDivContainer' ) ) {
	 	positionBlockCentrally('carCouponOverridePopupDivContainer');
		showBlock('carCouponOverridePopupDivContainer');
		disableElement('searchPopupDivContainer', true);
	 }
	return true;
}

function continueCarCouponSearch( queryString ) {
	disableElement ( 'searchPopupDivContainer' , true );
	makeAjaxCallWithWaitingDiv( 'carSearch.act', queryString, null, 'rightContent', 'callbackContinueCarCouponSearch', null, null );
}

function callbackContinueCarCouponSearch() {
	if ( !hasMessage( this ) ) {
		disableElement('searchPopupDivContainer', false);
		hideBlock('carCouponOverridePopupDivContainer');
		hideBlock('searchPopupDivContainer');
		
		disableElement ( 'dataContent' , false);
		
		/* load left summary section till car matrix page. */
		var pickupLocation = parseInt( document.getElementById( "pickupLocationTypePopup" ).value );
		var dropoffLocation = parseInt( document.getElementById( "dropoffLocationTypePopup" ).value );
		if( ( pickupLocation == CAR_PICKUP_AT_CITY ) || ( dropoffLocation == CAR_DROPOFF_AT_CITY ) ) {
			hideBlock( 'searchPopupDivContainer' );
			disableElement ( 'searchPopupDivContainer' , false );
			disableElement ( 'dataContent' , false );
			loadLeftContent('leftContent.act','lc=19&lbc=0' );
		} else {
			loadCarTripSummary( CarTripSummaryDisplayConstants.DISPLAY_CAR_TRIP_SUMMARY_UPTO_AGENCY_LOCATION );
		}
	} else {
		hideBlock('carCouponOverridePopupDivContainer');
		if( $( 'searchPopupDivContainer' ) && isBlockVisible( 'searchPopupDivContainer' ) ) {
			showErrorMessage( this.message , 'searchPopupDivContainer' )
		} else {
			showErrorMessage( this.message , 'dataContent' )
		}
	}
	return true;
}
function CarVendorAndAgencySelection( vendorId, agencyCodes ) {
	this.vendorId = vendorId;
	this.agencyCodes = agencyCodes;
}

function selectOrDeselectCarAgency( vendorId, agencyCode ) {
	var agencyElement = document.getElementById( vendorId + "_" + agencyCode );
	var carVendorAndAgencySelection = getCarAgencySelectionByVendorId( vendorId );
	if( agencyElement.checked ) {
		if( isNull( carVendorAndAgencySelection ) ) {
			var agencyCodes = new Array();
			agencyCodes[0] = agencyCode;
			addCarSelection( new CarVendorAndAgencySelection( vendorId, agencyCodes ) ); 
		} else {
			carVendorAndAgencySelection.agencyCodes[ carVendorAndAgencySelection.agencyCodes.length ] = agencyCode;
		}
	} else {
		if( ( carVendorAndAgencySelection.agencyCodes.length ) > 1 ) {
			removeAgency( carVendorAndAgencySelection, agencyCode );
		} else {
			removeCarVendor( carVendorAndAgencySelection );
		}
	}
	
}

function getCarAgencySelectionByVendorId( vendorId ) {
	var numberOfVendors = carVendorAndAgencySelections.length;
	for( var index = 0 ; index < numberOfVendors ; index++ ) {
		if( carVendorAndAgencySelections[ index ].vendorId == vendorId ) {
			return carVendorAndAgencySelections[ index ];
		}
	}
	return null;
}

function addCarSelection( carVendorAndAgencySelection ) {
	carVendorAndAgencySelections[ carVendorAndAgencySelections.length ] = carVendorAndAgencySelection;
}

function removeCarVendor( carVendorAndAgencySelection ) {
	var numberOfVendors = carVendorAndAgencySelections.length;
	var vendorIndex = -1;
	for( var index = 0 ; index < numberOfVendors ; index++ ) {
		if( carVendorAndAgencySelections[ index ].vendorId == carVendorAndAgencySelection.vendorId ) {
			vendorIndex = index;
			break;
		}
	}
	if( vendorIndex != -1 ) {
		if( vendorIndex == 0 ) {
			carVendorAndAgencySelections = carVendorAndAgencySelections.splice( 1, numberOfVendors );
		}  else if( vendorIndex == ( numberOfVendors - 1 ) ) {
			carVendorAndAgencySelections = carVendorAndAgencySelections.splice( 0, vendorIndex );
		} else {
			var firstSplice = carVendorAndAgencySelections.splice( 0, vendorIndex );
			var secondSplice = carVendorAndAgencySelections.splice( 1, carVendorAndAgencySelections.length );
			carVendorAndAgencySelections = firstSplice.concat( secondSplice );
		}
	}
}

function removeAgency( carVendorAndAgencySelection, agencyCode ) {
	var agencyCodes = carVendorAndAgencySelection.agencyCodes;
	var numberOfAgencies = agencyCodes.length;
	var agencyIndex = -1;
	for( var index = 0 ; index < numberOfAgencies ; index++ ) {
		if( agencyCodes[ index ] == agencyCode ) {
			agencyIndex = index;
			break;
		}
	}
	if( agencyIndex != -1 ) {
		if( agencyIndex == 0 ) {
			agencyCodes = agencyCodes.splice( 1, numberOfAgencies );
		}  else if( agencyIndex == ( numberOfAgencies - 1 ) ) {
			agencyCodes = agencyCodes.splice( 0, agencyIndex );
		} else {
			var firstSplice = agencyCodes.splice( 0, agencyIndex  );
			var secondSplice = agencyCodes.splice( 1, agencyCodes.length );
			agencyCodes = firstSplice.concat( secondSplice );
		}
		carVendorAndAgencySelection.agencyCodes = agencyCodes;
	}
}

function backNavigationFromAgencyResults(vendorName, isFromPopup, isFromWidget) {
	if( isFromPopup && !isFromWidget && ( trim( vendorName ) != '' ) ){
		loadAncillaryCategory('rentalCars', vendorName);
	} else {
		showSearchCarsTab();
	}
}

function callbackNavigationFromAgencyResults() {
	if ( ! showMessage(this.messageType, this.messageCode, this.message , 'dataContent' ) ) {
		disableElement ( 'dataContent' , false );
	}
	return true;
}

function validateAgencySelection(carVendorName) {
	if( carVendorAndAgencySelections.length == 0 ) {
		var msg ="Please select atleast one car agency location.";
		showErrorMessage( msg, 'dataContent' );
		return false;
	}
	var queryString = "cas=3";
	queryString += "&carAgenciesForVendors=" + carVendorAndAgencySelections.toJSONString();
	disableElement ( 'dataContent' , true );
	
	var trackingText = '';
	if(_carPopupSearch == 'true'){
		trackingText = '/rc/booking/popupWidget/carMatrix/' + (carVendorName != '' ? carVendorName : 'ALL') + '/'+ (_couponCode != '' ? _couponCode : 'NONE'); 
	}
	else{
		trackingText = '/rc/booking/searchWidget/carMatrix/' + (carVendorName != '' ? carVendorName : 'ALL');
	}
	
	
	makeAjaxCallWithWaitingDiv( 'carAgencySelection.act', queryString, null, 'rightContent', 'callbackValidateAgencySelection', null, trackingText );
}
	
function loadCarAgencyResults() {
	disableElement( 'dataContent', true );
	makeAjaxCallWithWaitingDiv( 'carAgencySelection.act', 'cas=0', null, 'rightContent', 'callbackPerformCarAgencySearchAgain', null, null );
}

function callbackValidateAgencySelection() {
	if ( ! showMessage(this.messageType, this.messageCode, this.message , 'dataContent' ) ) {
		//disableElement ( 'dataContent' , false );
		loadCarTripSummary( CarTripSummaryDisplayConstants.DISPLAY_CAR_TRIP_SUMMARY_UPTO_AGENCY_LOCATION );
	}
	return true;
}

function backNavigationFromCarMatrix( isPickuptAirport, isDropoffAirport, vendorName, isFromPopup, isFromWidget ){
	if( isPickuptAirport && isDropoffAirport ){
		if( isFromPopup && !isFromWidget && ( trim( vendorName ) != '' ) ){
			loadAncillaryCategory('rentalCars', vendorName);
		} else {
			showSearchCarsTab();
	    }
	} else {
		performCarAgencySearchAgain();
	}
}

function performCarAgencySearchAgain(){
	var queryString = "cs=6";
	disableElement ( 'dataContent' , true );
	makeAjaxCallWithWaitingDiv( 'carSearch.act', queryString, null, 'rightContent', 'callbackPerformCarAgencySearchAgain', null, null );
}

function callbackPerformCarAgencySearchAgain(){
	if ( ! showMessage(this.messageType, this.messageCode, this.message , 'dataContent' ) ) {
		disableElement ( 'dataContent' , false );
		loadLeftContent('leftContent.act','lc=19&lbc=0' );
	}
	return true;
}

function showHideMoreAgencies( carCompanyCode, totalAgenices, showMore ) {
	if( showMore ) {
		for( var index=2; index <= totalAgenices; index++ ) {
			document.getElementById( carCompanyCode + "_" + index ).style.display = "";
		}
		document.getElementById( carCompanyCode + "_showMore" ).style.display = "none";
		document.getElementById( carCompanyCode + "_showFewer" ).style.display = "";
	} else {
		for( var index=2; index <= totalAgenices; index++ ) {
			document.getElementById( carCompanyCode + "_" + index ).style.display = "none";
		}
		document.getElementById( carCompanyCode + "_showMore" ).style.display = "";
		document.getElementById( carCompanyCode + "_showFewer" ).style.display = "none";
	}
	
	fireContentChanged("scrollablePageContent");
}var ignoreScrollToTop = false;

function selectCarCategoryFromGrid( selectedProductUid, selectedCategoryUid, previousProductUid, isCouponSpecific ) {
	var queryString = "selectedProductUid="+selectedProductUid;
	if( isCouponSpecific ) {
		queryString += "&cms=5";
	} else {
		queryString += "&cms=1";
	}
	queryString += "&selectedCategoryUid=" + selectedCategoryUid + "&previousProductUid="+ previousProductUid;
	disableElement ( 'dataContent' , true );
	ignoreScrollToTop = true;
	makeAjaxCallWithWaitingDiv( 'carMatrixSelection.act', queryString, null, 'rightContent', 'callbackSelectCarCategoryFromGrid', null, null );
}

function callbackSelectCarCategoryFromGrid() {
	if ( ! showMessage(this.messageType, this.messageCode, this.message , 'dataContent' ) ) {
		//disableElement ( 'dataContent' , false );
		loadCarTripSummary( CarTripSummaryDisplayConstants.DISPLAY_CAR_TRIP_SUMMARY_UPTO_AGENCY_LOCATION );
	}
	return true;
}

function showAdditionalInfo( selectedProductUid, selectedCategoryUid ) {
	var additionalInfoPopupDivContainer = document.getElementById( 'additionalInfoPopupDivContainer' );
	if( isNull( additionalInfoPopupDivContainer ) ) {
		additionalInfoPopupDivContainer = createPopupDiv('additionalInfoPopupDivContainer', 0, 0, 450, -1, 200, false, true, 'popupDivSmall tal');
	}
	var queryString = "cms=2";
	queryString += "&selectedProductUid=" + selectedProductUid + "&selectedCategoryUid=" + selectedCategoryUid;
	makeAjaxCall( 'carMatrixSelection.act', queryString , null , 'additionalInfoPopupDivContainer' , 'callbackShowAdditionalInfo' , '' );
}

function callbackShowAdditionalInfo() {
	 if( !showMessage(this.messageType, this.messageCode, this.message , 'dataContent' ) ) {
		showBlock( 'additionalInfoPopupDivContainer' );
		positionBlockCentrally( 'additionalInfoPopupDivContainer' );	
		disableElement( 'dataContent', true );
	 }
}

function performCarRateSearchAgain() {
	clearErrorElements();
	
	var queryString = 'cs=7';
	
	var pickupDate = document.getElementById( "pickupDate" ).value;
	var dropoffDate = document.getElementById( "dropoffDate" ).value;
	if( pickupDate == '' || pickupDate == "mm/dd/yyyy" ) {
		showErrorMessage( "Please select a pickup date" ,'dataContent', 'pickupDate', '1px solid #7f9db9' );
		return false;
	} else if( !isDate( 'pickupDate', 'dataContent' ) ) {
		document.getElementById( "pickupDate" ).value = 'mm/dd/yyyy';
		document.getElementById( "pickupDate" ).select();
		return false;
	} else if( isPastDate( 'pickupDate' ) ) {
		return false;
	}
	
	if( dropoffDate == '' || dropoffDate == "mm/dd/yyyy" ) {
		showErrorMessage( "Please select a dropoff date" ,'dataContent', 'dropoffDate', '1px solid #7f9db9' );
		return false;
	} else if( !isDate( 'dropoffDate', 'dataContent' ) ) {
		document.getElementById( "dropoffDate" ).value = 'mm/dd/yyyy';
		document.getElementById( "dropoffDate" ).select();
		return false;
	} else if( isPastDate( 'dropoffDate' ) ) {
		return false;
	}
	
	var fromDate = new Date( pickupDate );
	var toDate = new Date( dropoffDate );
	if ( fromDate > toDate ) {
		var msg = "Please select a car drop off date which is greater than car pick up date.";
		showErrorMessage( msg ,'dataContent', 'dropoffDate', '1px solid #7f9db9' );
		return false;
	}
	
	var pickupTime = document.getElementById( "pickupTime" ).value;
	var dropoffTime = document.getElementById( "dropoffTime" ).value;
	
	/* Validation of same day pick up time - drop off time combination, with drop off time later than pick up time.*/
	if( fromDate.getTime() == toDate.getTime() ) {
		var pickupHours = getHoursFromTime( pickupTime );
		var dropoffHours = getHoursFromTime( dropoffTime );
		var numberOfHours = pickupHours - dropoffHours;		
		if( numberOfHours >= 0 ) {
			var msg = "Car drop-off time should be after pick-up time.";
			showErrorMessage( msg ,'searchPopupDivContainer', 'dropoffTime', '1px solid #7f9db9' );
			return false;
		}
	}
	
	queryString += '&pickupDate=' + pickupDate;
	queryString += '&dropoffDate=' + dropoffDate;
	queryString += '&pickupTime=' + pickupTime;
	queryString += '&dropoffTime=' + dropoffTime;
	
	trackEvent("Search Car", "Click", "Update Car Rental Search");
	
	disableElement ( 'dataContent' , true );
	
	makeAjaxCallWithWaitingDiv( 'carSearch.act', queryString, null, 'rightContent', 'callbackPerformCarRateSearchAgain', null, null );
}

function callbackPerformCarRateSearchAgain( errorMessage, actionCode ) {
	if ( !showMessage(this.messageType, this.messageCode, this.message , 'dataContent' ) ) {
		if( isNull( errorMessage) && isNull(actionCode) ) {
			disableElement ( 'dataContent' , false );
			loadCarTripSummary( CarTripSummaryDisplayConstants.DISPLAY_CAR_TRIP_SUMMARY_UPTO_AGENCY_LOCATION );
		} else {
			if( isNull(actionCode) ) {
				showErrorMessage( errorMessage ,'dataContent' );
			} else {
				loadCarCouponOverridePopup( errorMessage, actionCode );
			}
		}
	}
	return true;
}

function selectSpecialEquipment( selectedProductUid, selectedCategoryUid ) {
	ignoreScrollToTop = false;
	var queryString = "cs=8";
	queryString += "&selectedProductUid=" + selectedProductUid + "&selectedCategoryUid=" + selectedCategoryUid;
	disableElement ( 'dataContent', true );
	makeAjaxCallWithWaitingDiv( 'carSearch.act', queryString , null , 'rightContent' , 'callbackSelectSpecialEquipment' , null, null );
}

function callbackSelectSpecialEquipment() {
	if ( ! showMessage(this.messageType, this.messageCode, this.message , 'dataContent' ) ) {
		disableElement ( 'dataContent', false );
		loadCarTripSummary( CarTripSummaryDisplayConstants.DISPLAY_CAR_TRIP_SUMMARY_UPTO_CATEGORY );
	}
	return true;
}

function loadCarMatrixResults() {
	disableElement( 'dataContent', true );
	var trackingText = '';
	if (_carPopupSearch == 'true'){
		trackingText = '/rc/booking/popupWidget/carMatrix/' + (_carCompanyName != '' ? _carCompanyName : 'ALL') + '/' + (_couponCode != '' ? _couponCode : 'NONE');
	}
	else{
		trackingText = '/rc/booking/searchWidget/carMatrix/' + (_carCompanyName != '' ? _carCompanyName : 'ALL');
	}
	makeAjaxCallWithWaitingDiv( 'carMatrixSelection.act', 'cms=0' , null , 'rightContent' , 'callbackPerformCarRateSearchAgain' ,  null, trackingText );
}

function loadCarMatrixPage() {
	disableElement( 'dataContent', true );
	makeAjaxCallWithWaitingDiv( 'carMatrixSelection.act', 'cms=3' , null , 'rightContent' , 'callbackPerformCarRateSearchAgain' ,  null, trackingText );
}

function loadCarEndCapOfferPage( selectedProductUid, selectedCategoryUid, previousProductUid ) {
	selectCarCategoryFromGrid( selectedProductUid, selectedCategoryUid, previousProductUid, true );
}

function enableBackGroundForCouponOverridePopup() {
	if( $( 'searchPopupDivContainer' ) && isBlockVisible( 'searchPopupDivContainer' ) ) {
		disableElement( 'searchPopupDivContainer', false );	
	} else {
		disableElement( 'dataContent', false );
	}
}

/*
 * performCarSearchAndLoadCarMatrix() method is called for the browser back history of non airport selection.
 */
function performCarSearchAndLoadCarMatrix() {
	disableElement( 'dataContent', true );
	makeAjaxCallWithWaitingDiv( 'carSearch.act', 'cs=5' , null , 'rightContent' , 'callbackPerformCarRateSearchAgain' ,  null, '' );
}function continueToCarUpsell() {
	var queryString = "cs=9";
	disableElement ( 'dataContent', true );
	makeAjaxCallWithWaitingDiv( 'carSearch.act', queryString , null , 'rightContent' , 'callbackContinueToCarUpsell' , null, null );
}

function callbackContinueToCarUpsell() {
	if ( ! showMessage(this.messageType, this.messageCode, this.message , 'dataContent' ) ) {
		disableElement ( 'dataContent', false );
		loadCarTripSummary( CarTripSummaryDisplayConstants.DISPLAY_CAR_TRIP_SUMMARY_UPTO_OPTIONAL_REQUESTS );
	}
	return true;
}

function selectOrDeselectSpecialEquipment( specialEquipmentUid, currencySymbol ) {
	var specialEquipmentItem = document.getElementById( specialEquipmentUid + "_checkBox" );
	var quantity = 1;
	var checked = false;
	if( specialEquipmentItem.checked ) {
		// add newly selected special equipment
		var quantityField = document.getElementById( specialEquipmentUid + "_quantity" );		
		if( !isNull( quantityField ) && !quantityField.disabled ) {
			quantity = quantityField.value;
		}
		checked = true;
	}
	var queryString = "cse=1";
	queryString += "&specialEquipmentUid=" + specialEquipmentUid;
	queryString += "&checked=" + checked;
	queryString += "&quantity=" + quantity;
	var callbackParams = new Array();
	callbackParams[0] = currencySymbol;
	makeAjaxCall( 'carSpecialEquipmentSelection.act', queryString, null, 'rightContent', 'callbackSelectOrDeselectSpecialEquipment', '', callbackParams );
}

function callbackSelectOrDeselectSpecialEquipment( carRentalPrice, currencySymbol ) {
	document.getElementById( "totalPackagePriceDisplay" ).innerHTML =  currencySymbol + parseFloat( carRentalPrice ).toFixed( 2 );
	document.getElementById( "totalPackagePrice" ).value =  carRentalPrice;
}

function loadCarEquipmentResults(){
	disableElement ( 'dataContent' , true );
	makeAjaxCallWithWaitingDiv( 'carSpecialEquipmentSelection.act', 'cse=0' , null , 'rightContent' , 'callbackLoadCarEquipmentResults' , null, null );
}

function callbackLoadCarEquipmentResults() {
	if ( ! showMessage(this.messageType, this.messageCode, this.message , 'dataContent' ) ) {
		disableElement ( 'dataContent', false );
		loadCarTripSummary( CarTripSummaryDisplayConstants.DISPLAY_CAR_TRIP_SUMMARY_UPTO_CATEGORY );
	}
	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.messageType, this.messageCode, this.message, '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.messageType, this.messageCode, this.message, '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' );
	disableElement ( 'dataContent' , true );
	makeAjaxCallWithWaitingDiv( 'booking.act', queryString, null, 'rightContent', 'callbackLoadBooking' , null, '/vp/booking/itinerary' );
}

function callbackLoadBooking() {
	showMessage(this.messageType, this.messageCode, this.message, 'dataContent' );
	disableElement ( 'dataContent' , false );
	return true;
}

function addTripProtection() {
	var queryString = 'b=9';
	makeAjaxCallWithWaitingDiv( 'booking.act', queryString, null, 'tripProtectionAndPricingSummaryDiv', 'callbackAddTripProtection' );
}

function callbackAddTripProtection() {
	showMessage(this.messageType, this.messageCode, this.message, 'dataContent' );
	return true;
}

function removeTripProtection() {
	var queryString = 'b=10';
	makeAjaxCallWithWaitingDiv( 'booking.act', queryString, null, 'tripProtectionAndPricingSummaryDiv', 'callbackRemoveTripProtection' );
}

function callbackRemoveTripProtection() {
	showMessage(this.messageType, this.messageCode, this.message, 'dataContent' );
	return true;
}
function clearBookingResultObjectFromSession( fromWidget, showPopup, packageId ){
	var queryString;
	_packageId = packageId;
	_fromWidget = fromWidget;
	if( showPopup ) {
		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 ) {
		/*var searchPopupDivContainer = document.getElementById('searchPopupDivContainer');
		if ( searchPopupDivContainer != undefined || searchPopupDivContainer != null ) {
			showHiddenSearchPopup();
		} else {*/
			_fromMenu = !_fromWidget;
			initiatePackageSearch( _packageId , _fromWidget );
		//}
	} else {
		showMessage(this.messageType, this.messageCode, this.message, 'dataContent' );			
	}
}

function createTripProtectionDetailsDiv(disabledBaseElement) {
	var tripProtectionDetailsPopupDiv = document.getElementById('tripProtectionDetailsPopupDiv');
	if(!tripProtectionDetailsPopupDiv){
		tripProtectionDetailsPopupDiv = createPopupDiv('tripProtectionDetailsPopupDiv', 0, 0, 700, -1, 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, -1, 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, -1, 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' );
	window.open(_httpContextRoot + _webLoc + "/booking.act?b=16&booking_id="+bookingId,"_blank","alwaysLowered=true,width=800,height=500,resizable,scrollbars,left=80,top=80");
	//window.open("javascript:w;location = '" + window.location.protocol + window.location.port + "//" + window.location.hostname + _webLoc + "/booking.act?b=16&booking_id="+bookingId+"'","_blank","alwaysLowered=true,width=800,height=500,resizable,scrollbars,left=80,top=80");
}

function callbackPrintItinerary( attachmentName ,attachmentPath ){
	// var popupWindow = window.open("javascript:location = '" + window.location.protocol + window.location.port + "//" + window.location.hostname  + _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, -1, 200, false, true,  "tal popupDivSmall");
		emailItineraryPopupDiv.style.height = toPixels(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.messageType, this.messageCode, this.message, 'dataContent' )) {
		showMessage( null, null, successMessage, 'dataContent');
	}
	return true;
}

function loadMemberLoginScreen(defaultUser)
{
	if(!defaultUser)
	{
		//window.location.href= _secureContextRoot + _webLoc+ "/?h=3&checkMemberInactivity=true&uid=" + UID();
		showMessage(2, true, 'Membership is inactive. Please login again to make a booking.', 'dataContent', callBackLoadMemberLoginScreen,null );
	}
	else
	{
		window.location.href= _secureContextRoot + _webLoc+ "/?h=3&checkMemberInactivity=true&uid=" + UID();
	}
}

function callBackLoadMemberLoginScreen()
{
	hideMessageBox(UID(),'dataContent' );
	window.location.href= _secureContextRoot + _webLoc+ "/?h=3&checkMemberInactivity=true&uid=" + UID();
}

function loadTicketSummary(){
	var queryString = 'b=21';
	queryString += '&summaryPage=true';
	makeAjaxCall( 'booking.act', queryString, null, 'ticketBookingSummaryDiv', 'callbackLoadTicketSummary' );	
}

function callbackLoadTicketSummary(){
}

function loadTakeASurvey( bookingId ) {
	var queryString = 'sm=0';
	queryString += '&bookingId=' + bookingId;	
	disableElement ( 'dataContent' , true );
	makeAjaxCallWithWaitingDiv( 'takeASurvey.act', queryString, null, 'rightContent', 'callbackLoadTakeASurvey', null, '/gi/memberInfo/MemberSurvey');
}

function callbackLoadTakeASurvey() {
	showMessage(this.messageType, this.messageCode, this.message, 'dataContent' , null, '/gi/memberInfo/MemberSurvey');
	disableElement ( 'dataContent' , false );
	scrollWindowTop("scrollablePageContent");
	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.messageType, this.messageCode, this.message, '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.messageType, this.messageCode, this.message, '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.messageType, this.messageCode, this.message, '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.messageCode || this.messageCode ==""){
		document.getElementById("logoutDiv").style.display = "block";
	} else {
		document.getElementById("logoutDiv").style.display = "none";
	} 
	if( this.message != undefined ){
		document.getElementById( "password" ).value = "";
		document.getElementById( "membershipNumber" ).focus();
		showMessage(this.messageType, this.messageCode, this.message, 'dataContent' );		
	}
	else {
		disableElement( 'dataContent', false);
	}
	return true;	
}

function validateMemberNumber( isCruiseFlow,isCarRentalFlow,checkMember ) {
	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;
				} 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+='&checkMemberInactivity='+checkMember;
		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 (isCarRentalFlow == "true"){
			if (_carPopupSearch == 'true'){
				trackingText = '/rc/booking/popupWidget/bookingCheckout/' + _carCompanyName + '/' + (_couponCode != '' ? _couponCode : 'NONE');
			}
			else{
				trackingText = '/rc/booking/searchWidget/bookingCheckout/' + _carCompanyName;		
			}				
		}
		else{ 
			if (isCruiseFlow == "true"){
				if(!isEmpty(_cruisePackageId)) {
					trackingText = '/cr/booking/bookingPackage/passengerDetails/' + _cruisePackageId + '/' + _departureDate;
				} else {
					trackingText = '/cr/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.messageCode || this.messageCode ==""){
		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.message != undefined ){
		document.getElementById( "confirmPassword" ).value == "";
		document.getElementById( "firstTimeUserPassword" ).value == "";
		document.getElementById( "password" ).value == "";
		showMessage(this.messageType, this.messageCode, this.message, '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, carRentalFlow, checkMember ) {
	if( isEnterKey( event ) ) {
		validateMemberNumber( cruiseFlow, carRentalFlow, checkMember );
		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.messageType, this.messageCode, this.message, '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;
		}
		if( !( validateField( 'paxDateOfBirth_' + paxIndex , 'Please enter Date of Birth 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( "landTermsAndConditions").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() {
	disableElement('dataContent', false);
	showMessage(this.messageType, this.messageCode, this.message, '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;
}

function resetPaxAge(paxIndex){
	if (document.getElementById("paxAge_" + paxIndex)){
		document.getElementById("paxAge_" + paxIndex).value = "";	
	}	
	if (document.getElementById("paxDateOfBirth_" + paxIndex)){
		document.getElementById("paxDateOfBirth_" + paxIndex).value = "mm/dd/yyyy";	
	}	
}var _flightSeatMap = new Array();
var _flightSegmentItemUids = new Array();
var _passengerInfoArray = new Array();

var _passengerCount = 0;
var _flightSegmentItemUid= "";
var _seatPreference = 0;


function FlightPassengerSeatInfo(flightSegmentItemUid, passengerIndex, seatNumber){
	this.flightSegmentItemUid = flightSegmentItemUid;
	this.passengerIndex = passengerIndex;
	this.seatNumber = seatNumber;
}

function PassengerSeatInfo(passengerIndex, title, firstName, lastName, middleInitial, suffix, seatNumber){
	this.title = title;
	this.passengerIndex = passengerIndex;
	this.firstName = firstName;
	this.lastName = lastName;
	this.middleInitial = middleInitial;
	this.suffix = suffix;
	this.seatNumber = seatNumber;
}


function getPassengersInfo()
{	
	createPassengerInfoArray();
	return _passengerInfoArray;
}

function getNextPassengerIndex(currentpassengerIndex) {
	nextpassengerIndex = currentpassengerIndex;
	nextpassengerIndex = (nextpassengerIndex + 1) % _passengerCount;	
	return nextpassengerIndex;
}

function selectSeat(passengerSeatInfo) {	
	var passengerIndex = getSelectedPassengerIndex();
	var seatNumber = passengerSeatInfo.seatNumber;
	var seatNumberElement = document.getElementById("passengerSeatNumber" + passengerIndex);
	var selectedFlightSegmentItemUid = document.getElementById("selectedFlightSegmentItemUid").value;
	_passengerInfoArray[passengerSeatInfo.passengerIndex] = passengerSeatInfo;	
	if(seatNumberElement != null) {
	 	setInnerText(seatNumberElement, seatNumber);
	 	setSeatNumber(selectedFlightSegmentItemUid, passengerIndex, seatNumber);	 	
	 }
	 	 
	 var nextPassengerIndex = getNextPassengerIndex(passengerIndex);
	 selectPassenger(nextpassengerIndex);
}

function highlightPassenger(passengerIndex) {
	var passengerNameTrElement = document.getElementById("passengerNameTr"+ passengerIndex);
	passengerNameTrElement.className = "b bgc05";
} 

function deHighlightPassenger(passengerIndex) {
	var passengerNameTrElement = document.getElementById("passengerNameTr"+ passengerIndex);
	passengerNameTrElement.className = "nob";
}

function onSelectPassenger(passengerIndex) {
	var passengerInfo = _passengerInfoArray[passengerIndex];
	var seatMapObj = document.getElementById("seatMap"); 
	if(seatMapObj && seatMapObj.getCurrentPassengerInfo) {
		seatMapObj.getCurrentPassengerInfo(passengerInfo);
	}
	selectPassenger(passengerIndex);
}

function selectPassenger(passengerIndex) {	
	for(var i=0; i<_passengerCount; i++) {
 		if(i != passengerIndex) {
 			deHighlightPassenger(i)
 		}
 		highlightPassenger(passengerIndex);
	} 
	
	var optionElements = document.getElementsByName("radioPassengerName");
	if(optionElements && optionElements.length) {
		for(var i=0; i<_passengerCount; i++) {
			if(i != passengerIndex) {
 				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.passengerIndex, 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, -1, 500, false, true,  "popupDivSmall tal")
	}
	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 getSelectedPassengerIndex() {
	 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 );
	disableElement( "dataContent" , true );
	makeAjaxCallWithWaitingDiv( 'seatMapContent.act' , queryString , null , 'rightContent' , 'callbackAssignSeatsToPassengers' , trackingText , null );
}

function callbackAssignSeatsToPassengers() {
	if ( ! ( showMessage(this.messageType, this.messageCode, this.message , 'dataContent' ) ) ) {
		disableElement( "dataContent" , false );
	}
}

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, -1, 204, false, true,  "tal popupDivBig")
	}
	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, passengerIndex) {
	return _flightSeatMap[flightSegmentItemUid + "_" + passengerIndex];
}

function setSeatNumber(flightSegmentItemUid, passengerIndex, seatNumber) {
	_flightSeatMap[flightSegmentItemUid + "_" + passengerIndex] = 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 jsonSurveyResponse = "";

	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;
			}
			var carScheduledDate = 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 += "'creditCardScheduledDate':" + "'" + carScheduledDate + "',";
			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;
	}
	
	var surveyResponse = document.getElementById( "surveyResponse").value;
	var surveyDefinitionId = document.getElementById( "surveyDefinitionId").value;
	var questionId =document.getElementById( "questionId").value;
	var isUserDefinedResponse = document.getElementById( "isUserDefinedResponse").value;
	if(isUserDefinedResponse== 'true')
	{
		surveyResponse = document.getElementById( "userDefinedResponse").value;
	}
	jsonSurveyResponse += "'SURVEY_RESPONSE':{'surveyResponse':" + "'" + surveyResponse+"'";
	jsonSurveyResponse+= ","+ " 'surveyDefinitionId':" + "'" + surveyDefinitionId + "'";
	jsonSurveyResponse+= ",'questionId':"+ "'" + questionId + "'";
	jsonSurveyResponse+= ",'userDefinedResponse':"+isUserDefinedResponse  ;
	jsonSurveyResponse+= ",'comments': ''" ;
	jsonSurveyResponse+= ",'matrixQuestion': ''" ;
	jsonSurveyResponse+= ",'query_mode':'CREATE'}";
	
	jsonFormattedString = "{'CREDITCARD_INFO':[" + jsonFormattedString.substring( 0, jsonFormattedString.lastIndexOf( "," ) ) + "]," + jsonShippingAddress + ","+jsonSurveyResponse+" }";
	var queryString = 'pm=1';
	queryString += "&paymentDetail=" + jsonFormattedString;
	var trackingText = '';

	if (_isCruiseItemIncluded && _isCruiseItemIncluded == 'true'){
		if(!isEmpty(_cruisePackageId)) {
			trackingText = '/cr/booking/bookingPackage/reviewSubmit/' + _cruisePackageId + '/' + _departureDate;
		} else {
			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() {
	showMessage(this.messageType, this.messageCode, this.message, '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;
		if ( _isCruiseItemIncluded || _isCruiseItemIncluded == 'true'){
			showBlock( "costcoChargeSchedulePaymentMessage" );
			hideBlock( "costcoChargeFullPaymentMessage" );
		}
	} 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);
		if ( _isCruiseItemIncluded || _isCruiseItemIncluded == 'true'){
			hideBlock( "costcoChargeSchedulePaymentMessage" );
			showBlock( "costcoChargeFullPaymentMessage" );
		}
	}
}

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(states ) {
	if(!showMessage(this.messageType, this.messageCode, this.message, 'dataContent')) {
		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;
 	if( selectedPaymentOption ==  'SCHEDULED_PAYMENT' ){
 		_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) ) {
				_depositAmount = document.getElementById( "depositAmount" ).value;
				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( document.getElementById('creditCardAmount_fullPayment_0').value ).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;
			}
 		}
 		if( selectedPaymentOption ==  'SCHEDULED_PAYMENT' ){
 			_previousDepositAmount = newDepositAmount;
 		}
 		clearErrorElements();
	} else {
		_depositAmount = document.getElementById( "depositAmount" ).value;
		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, -1, 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=16"; 
	makeAjaxCall( 'cruiseBooking.act', queryString, null, 'mainContent', 'callbackLoadBookingRecapPage', '' );
}

function callbackLoadBookingRecapPage() {
	if (!showMessage(this.messageType, this.messageCode, this.message , 'dataContent')) {
		disableElement("dataContent" , false);
	}
}

function chooseSurveyOption(questionId,isUserDefinedResponse) {
	
	var optionSelected = getCheckedValue( document.getElementsByName("columnTitle"));
	document.getElementById( "surveyResponse").value = optionSelected;
		
	document.getElementById( "isUserDefinedResponse").value = isUserDefinedResponse;     
	document.getElementById( "questionId").value = questionId;
}var _isCruiseItemIncluded; 

function loadPaymentInformation( ) {
	var queryString = 'pm=0';
	queryString += '&fromBookingConfirmation=true';
	//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() {
	showMessage(this.messageType, this.messageCode, this.message, 'dataContent');
	return true;
}

function loadPaymentConfirmation( ) {
	var queryString = 'cf=0';
	makeAjaxCall( 'paymentConfirm.act', queryString, null, 'rightContent', 'callbackLoadPaymentConfirmation', '' );
}
function callbackLoadPaymentConfirmation() {
	showMessage(this.messageType, this.messageCode, this.message, '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'){
		if(!isEmpty(_cruisePackageId)) {
			trackingText = '/cr/booking/bookingPackage/BookingConfirmation/' + _cruisePackageId + '/' + _departureDate;
		} else {
			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(paymentException) {
	disableElement( 'dataContent', false );
	if(!showMessage(this.messageType, this.messageCode, this.message, 'dataContent')){
		clearErrorElements();
		if( paymentException ) { 
			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(states, index, showAddress) {
	if(!showMessage(this.messageType, this.messageCode, this.message, 'dataContent')){
 		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(states, ccIndex) {
	if(!showMessage(this.messageType, this.messageCode, this.message, 'dataContent')){
		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() {
	showMessage(this.messageType, this.messageCode, this.message, '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() {
	showMessage(this.messageType, this.messageCode, this.message, 'dataContent');
	return true;
}

function loadBalancePaymentConfirmation(balancePaymentDetail) {
	var queryString = 'bpm=3&balancePaymentDetail=' + balancePaymentDetail;
	makeAjaxCall( 'balancePayment.act', queryString, null, 'rightContent', 'callbackLoadBalancePaymentConfirmation', '' );	
}

function callbackLoadBalancePaymentConfirmation() {
	showMessage(this.messageType, this.messageCode, this.message, 'dataContent');
	return true;
}

function onPaymentModeChange() {
	var paymentMode= getCheckedValue(document.getElementsByName("paymentMode"));
	if(paymentMode == 'BALANCE_PAYMENT' && _numberOfBalanceCreditCards == 1) {      
		document.getElementById( "creditCardAmount_balancePayment_0").value = _balanceAmount;      
 	} 
 	if( !isNull(document.getElementById( "disclaimerDiv" ))){
 		if( paymentMode == 'ANOTHER_PAYMENT' ){
			document.getElementById( "disclaimerDiv" ).style.display = "none";
		}else {
			document.getElementById( "disclaimerDiv" ).style.display = "block";
		}
 	}
}

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(paymentException) {
	disableElement( 'dataContent', false );
	if(!showMessage(this.messageType, this.messageCode, this.message, 'dataContent')){
		clearErrorElements();
		if(paymentException) { 
			showErrorMessage( paymentException, 'dataContent' );
			return false;
		}
	}
	return true;
}



function submitSpecialRequests(noOfProducts,isFlightIncluded) {
// 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( !isFlightIncluded && !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( !isFlightIncluded && !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( "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( showTripPopup ) {
	if ( ! ( showMessage(this.messageType, this.messageCode, this.message , 'dataContent' ) ) ) {
		disableElement( "dataContent" , false );
		if( showTripPopup != null && showTripPopup!= undefined){
			if (showTripPopup){
				loadCruiseTripProtectionPopup();
			}
			else{
				loadCruiseBookingRecap();
			}	
		}
	}
}

 // 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" ) ){
		createPopupDiv ( "cruiseInfoPopupDivContainer" , -1 , -1, -1, -1, 200, false , true , "" );
	}
	disableElement( "cruiseInfoPopupDivContainer", true );

	var queryString = "cb=10";
	queryString += "&itemUid=" + cruiseSailingItemUid;
	queryString += "&selectedTab=" + selectedTab;

	makeAjaxCallWithWaitingDiv( "cruiseBooking.act" , queryString , null , "cruiseInfoPopupDivContainer" , "callbackShowCruiseInformationDiv", "" );
}

function callbackShowCruiseInformationDiv( ) {
	if ( !( showMessage(this.messageType, this.messageCode, this.message , "dataContent" ) ) ) {
		showBlock( "cruiseInfoPopupDivContainer" );
		positionBlockCentrally( "cruiseInfoPopupDivContainer" );
		disableElement( "dataContent" , true );
		disableElement( "cruiseInfoPopupDivContainer", false );
	}
}

function loadPaymentInfo() {
	var queryString = "pm=0";

	var trackingText = null;
	if(!isEmpty(_cruisePackageId)) {
		trackingText = "/cr/booking/bookingPackage/paymentDetails/" + _cruisePackageId + "/" + _departureDate;
	} else {
		trackingText = "/cr/booking/bookingWidget/paymentDetails/" + _destinationName + "/" + _cruiseLineName + "/" + _shipName + "/" + _departureDate;
	}
	
	makeAjaxCall( "payment.act", queryString, null, "rightContent", "callbackLoadPaymentInfo", trackingText );
}

function callbackLoadPaymentInfo() {
	if ( !( showMessage(this.messageType, this.messageCode, this.message , "dataContent" ) ) ) {
		disableElement ( "dataContent" , false );
	}
}

function loadCruiseTripProtectionPopup() {	
	var cruiseTripProtectionPopupDivContainer = createPopupDiv ( "cruiseTripProtectionPopupDivContainer", - 1, - 1, -1, -1, 200 , false , true , "" );
	cruiseTripProtectionPopupDivContainer.onkeypress = function( event ) { onKeyDownOnTripProtectionPopup(event) };
	disableElement( "dataContent", true );
	var queryString = "cb=11";
	
	var trackingText = null;
	if(!isEmpty(_cruisePackageId)) {
		trackingText = "/cr/booking/bookingPackage/searchIns/" + _cruisePackageId + _departureDate;
	} else {
		trackingText = "/cr/booking/bookingWidget/searchIns/" + _destinationName + "/" + _cruiseLineName + "/" + _shipName + "/" + _departureDate;
	}

	makeAjaxCallWithWaitingDiv( "cruiseBooking.act", queryString, null, "cruiseTripProtectionPopupDivContainer", "callbackLoadCruiseTripProtectionPopup", null, trackingText );	
}

function callbackLoadCruiseTripProtectionPopup() {
	if ( !( showMessage(this.messageType, this.messageCode, this.message , "dataContent" ) ) ) {
		showBlock( "cruiseTripProtectionPopupDivContainer" );
		positionBlockCentrally( "cruiseTripProtectionPopupDivContainer" );	
	}
}

function loadCruiseBookingRecap(){
	disableElement( "dataContent", true );
	var queryString = "cb=16";
	
	var trackingText = null;
	if(!isEmpty(_cruisePackageId)) {
		trackingText = "/cr/booking/bookingPackage/BookingRecap/" + _cruisePackageId + _departureDate;
	} else {
		trackingText = "/cr/booking/bookingWidget/BookingRecap/" + _destinationName + "/" + _cruiseLineName + "/" + _shipName + "/" + _departureDate;
	}
	
	makeAjaxCallWithWaitingDiv( "cruiseBooking.act", queryString, null, "mainContent", "callbackLoadCruiseBookingRecap", null, trackingText);
}

function callbackLoadCruiseBookingRecap(){
	if ( !( showMessage(this.messageType, this.messageCode, this.message , "dataContent" ) ) ) {
		disableElement ( "dataContent" , false );
	}
}

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 );
	
	var trackingText = null;
	if(!isEmpty(_cruisePackageId)) {
		trackingText = "/cr/booking/bookingPackage/BookingRecap/" + _cruisePackageId + _departureDate;
	} else {
		trackingText = "/cr/booking/bookingWidget/BookingRecap/" + _destinationName + "/" + _cruiseLineName + "/" + _shipName + "/" + _departureDate;
	}
	
	makeAjaxCallWithWaitingDiv( "cruiseBooking.act", queryString, null, "mainContent", "callbackApplyTripProtection", null, trackingText );
}

function callbackApplyTripProtection() {
	if ( !( showMessage(this.messageType, this.messageCode, this.message , "cruiseTripProtectionPopupDivContainer" ) ) ) {
		disableElement( "cruiseTripProtectionPopupDivContainer", false );
		removeElement("cruiseTripProtectionPopupDivContainer")
		disableElement( "dataContent", false );
	}
}

function toggleCruiseTripProtection( 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 = formatCurrency(packagePrice);
		document.getElementById( "totalCruisePackagePrice" ).value = parseFloat( packagePrice ).toFixed( 2 );
		_totalCruiseTripProtectionAmount = 0;
	} 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 showItineraryRemarksPopup(bookingDynamicValueAddDetailIndex) {
	var cruiseTaxesAndFeesPopupDiv = document.getElementById("itineraryRemarksPopupDiv");
	if(!cruiseTaxesAndFeesPopupDiv){
		cruiseTaxesAndFeesPopupDiv = createPopupDiv("itineraryRemarksPopupDiv", 0, 0, 700, -1, 300, false, true,  "tal popupDivBig");
	}
	disableElement("dataContent", true);
	var queryString = "cb=18";
	queryString += "&bookingDynamicValueAddDetailIndex=" + bookingDynamicValueAddDetailIndex;
	makeAjaxCall("cruiseBooking.act", queryString, null, "itineraryRemarksPopupDiv", "callbackShowItineraryRemarksPopup", "");	
}

function callbackShowItineraryRemarksPopup() {
	document.title = "Costco Travel";	
	showBlock("itineraryRemarksPopupDiv"); 
	positionBlockCentrally("itineraryRemarksPopupDiv"); 
}
var _landComponentsIncluded = false;
var _flightOnlyIncluded = false;
var _supportInsurance = false;

function updateCruiseSpecialRequest() {
	var queryString = "crsr=1";
	var passengerCount = document.getElementById("passengerCount").value;
	var medicalRequestsCount = document.getElementById("medicalRequestsCount").value;
	var specialRequestsCount = document.getElementById("specialRequestsCount").value;
	_supportInsurance = document.getElementById("supportInsurance").value == "true";
	
	var diningSeatingElement = document.getElementById("diningSeating");	
	if (diningSeatingElement){
		if(!validateField("diningSeating", "Please select dining seating.")) {
			return false;
		}
	}
	
	var tableSizeElement = document.getElementById("tableSize");
	if (tableSizeElement){
		if(!validateField("tableSize", "Please select a table size.")) {
			return false;
		}
	}
	
	var specialOccasions = [];
	var specialRequests =  [];
	var medicalRequests =  [];
	
	for (var passengerIndex = 1; passengerIndex <= passengerCount; passengerIndex++){
		if (document.getElementById("birthdayDate_" + passengerIndex)) {
			var passengerName = document.getElementById("paxName_" + passengerIndex).innerHTML;
			var birthdayCodeType = document.getElementById("birthdayCodeType").value;
			var birthdayDate = document.getElementById("birthdayDate_" + passengerIndex).value;
			var birthdayYears = document.getElementById("birthdayYears_" + passengerIndex).value;
			
			if (birthdayDate != "") {
				if (trim(birthdayYears) == '' || birthdayYears == '0'){
					message = 'Please enter years celebrating birthday for passenger ' + passengerName;
					showErrorMessage( message, 'dataContent', "birthdayYears_" + passengerIndex, '1px solid #7f9db9' );
					return false;
				}
				
				specialOccasions.push({
					requestCodeType  :birthdayCodeType,
					yearsToCelebrate :birthdayYears,
					passengerIndex   :passengerIndex,
					occasionDate     :birthdayDate
				});
			}
		}
		
		if (document.getElementById("anniversaryDate_" + passengerIndex)) {
			var passengerName = document.getElementById("paxName_" + passengerIndex).innerHTML;
			var anniversaryCodeType = document.getElementById("anniversaryCodeType").value;
			var anniversaryDate = document.getElementById("anniversaryDate_" + passengerIndex).value;
			var anniversaryYears = document.getElementById("anniversaryYears_" + passengerIndex).value;
			
			if (anniversaryDate != "") {
				if (trim(anniversaryYears) == '' || anniversaryYears == '0'){
					message = 'Please enter years celebrating anniversary for passenger ' + passengerName;
					showErrorMessage( message, 'dataContent', "anniversaryYears_" + passengerIndex, '1px solid #7f9db9' );
					return false;
				}
				
				specialOccasions.push({
					requestCodeType  :anniversaryCodeType,
					yearsToCelebrate :anniversaryYears,
					passengerIndex   :passengerIndex,
					occasionDate     :anniversaryDate
				});
			}
		}
		
		if (document.getElementById("honeymoon_" + passengerIndex)) {
			var isHoneymoonSelected = document.getElementById("honeymoon_" + passengerIndex).checked;
			if(isHoneymoonSelected) {
				var honeymoonCodeType = document.getElementById("honeymoonCodeType").value;
				specialOccasions.push({
					requestCodeType  :honeymoonCodeType,
					passengerIndex   :passengerIndex
				});
			}
		}
	}
		
	for (var passengerIndex = 1; passengerIndex <= passengerCount; passengerIndex++){
		for (var specialRequestIndex = 0; specialRequestIndex < specialRequestsCount; specialRequestIndex++ ){
			var specialRequestCheckbox = document.getElementById("specialRequest_" + specialRequestIndex + "_" + passengerIndex);
			if (specialRequestCheckbox && specialRequestCheckbox.checked){
				specialRequests.push({
					requestCodeType: specialRequestCheckbox.value,
					passengerIndex: passengerIndex
				});
			}	
		}
	}

	for (var passengerIndex = 1; passengerIndex <= passengerCount; passengerIndex++){
		for (var medicalRequestIndex = 0; medicalRequestIndex < medicalRequestsCount; medicalRequestIndex++ ){
			var medicalRequestCheckbox = document.getElementById("medicalRequest_" + medicalRequestIndex + "_" + passengerIndex);
			if (medicalRequestCheckbox && medicalRequestCheckbox.checked){
				medicalRequests.push({
					requestCodeType: medicalRequestCheckbox.value,
					passengerIndex: passengerIndex
				});
			}	
		}	
	}

	if(tableSizeElement) {		
		queryString += "&diningTableSize=" + tableSizeElement.value;
	}	
	if(diningSeatingElement) {
		queryString += "&diningSeatingUid=" + diningSeatingElement.value;
	}
	
	queryString += "&specialOccasion=" + specialOccasions.toJSONString(); 
	queryString += "&specialRequest=" + specialRequests.toJSONString(); 
	queryString += "&medicalRequest=" + medicalRequests.toJSONString();
	
	var target = 'cruiseTripProtectionPopupDivContainer';
	if( _supportInsurance){
		if ( !_landComponentsIncluded || _flightOnlyIncluded ){
			//for cruise trip protection
			var cruiseTripProtectionPopupDivContainer = createPopupDiv('cruiseTripProtectionPopupDivContainer', -1, -1, -1, -1, 200, false, true,  "");
		} else {
			//for land component special requests
			target = 'rightContent';
		}
	} else if( !_supportInsurance ){
		if ( !_landComponentsIncluded || _flightOnlyIncluded ){
			//for cruise booking recap page.
			target = 'mainContent';
		} else {
			//for land component special requests
			target = 'rightContent';
		}
	}
		
	disableElement ( 'dataContent' , true );
	
	var trackingText = null;
	if(!isEmpty(_cruisePackageId)) {
		trackingText = "/cr/booking/bookingPackage/searchIns/" + _cruisePackageId + _departureDate;
	} else {
		trackingText = "/cr/booking/bookingWidget/searchIns/" + _destinationName + "/" + _cruiseLineName + "/" + _shipName + "/" + _departureDate;
	}
	
	makeAjaxCallWithWaitingDiv ( 'cruiseSpecialRequests.act' , queryString , null , target , 'callbackUpdateCruiseSpecialRequest', null, trackingText );
}

function callbackUpdateCruiseSpecialRequest () {
	if ( ! ( showMessage(this.messageType, this.messageCode, this.message , 'dataContent' ) ) ) {
		//loadCruiseTripSummary ();
		if( (!_landComponentsIncluded || _flightOnlyIncluded ) && _supportInsurance){
			showBlock( 'cruiseTripProtectionPopupDivContainer' );
			positionBlockCentrally( 'cruiseTripProtectionPopupDivContainer' );
		} else {
			disableElement ( 'dataContent' , false );
		}
	}
}

function reLoadCruiseSpecialRequests () {
	var queryString = "crsr=0";

	disableElement ( 'dataContent' , true );
	makeAjaxCallWithWaitingDiv ( 'cruiseSpecialRequests.act' , queryString , null , 'rightContent' , 'callbackReLoadCruiseSpecialRequests' );
}

function callbackReLoadCruiseSpecialRequests () {
	if ( ! ( showMessage(this.messageType, this.messageCode, this.message , 'dataContent' ) ) ) {
		loadCruiseTripSummary ();
		disableElement ( "dataContent" , false );
	}
}

function diningSeatingOnChange() {
	var diningSeatingList = document.getElementById("diningSeating");
	if (diningSeatingList.selectedIndex != ''){
		var gratuityRequired = getElementValue("gratuityRequired_" + diningSeatingList.selectedIndex, "false");
		if (gratuityRequired == "true") {
			modifyClassName("diningGratuityNote", "+displayBlock -displayNone");
		}
		else{
			modifyClassName("diningGratuityNote", "-displayBlock +displayNone");
		}	
	}
	
	for(var i=1; i< diningSeatingList.options.length; i++) {
		if(i == diningSeatingList.selectedIndex) {			
			modifyClassName("sittingTypeTable_" + i, "+displayBlock -displayNone");
		}else {
			modifyClassName("sittingTypeTable_" + i, "-displayBlock +displayNone");
		}
	}
}

function displayRequestGratuityNote(requestCheckbox, show){
	var requestCodeType = requestCheckbox.value;	
	if (show){
		modifyClassName(document.getElementById("requestGratuityNote"), "+displayBlock -displayNone");
	}else {
		modifyClassName(document.getElementById("requestGratuityNote"), "-displayBlock +displayNone");		
	}	
}
var isCostcoCardAmountModified = false;
function addAnotherCreditCard( ) {
	clearErrorElements();
	var previousCardAmount = 0;
	var creditCardAmount;
	if (  numberOfCreditCardsForFullPayment == maxCreditCards ) {
		showWarningMessage( 'You are allowed only 3 credit cards', 'dataContent' );
	} else {
		var totalCardsAmount = parseFloat( document.getElementById( "creditCardAmount_fullPayment_0" ).value ) + parseFloat( document.getElementById( "creditCardAmount_fullPayment_1" ).value )
		if( parseFloat( totalCardsAmount ) >= 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 = getSuperPNRCreditCardRowAsHTML(numberOfCreditCardsForFullPayment, 0.0);
			var cruiseAmount = parseFloat( _cruiseAmount ) - parseFloat( document.getElementById( "creditCardAmount_fullPayment_1" ).value );
			document.getElementById( "creditCardAmount_fullPayment_"+ numberOfCreditCardsForFullPayment ).value = parseFloat( cruiseAmount ).toFixed( 2 );
			numberOfCreditCardsForFullPayment = 3;	
		}
	}
	return true;
}
function loadDefaultPaymentSuperPnrInfo(){
	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 = getSuperPNRCreditCardRowAsHTML(count, _depositAmount );
			} else {
				document.getElementById( "schedulePaymentDataDiv_" +count).style.display = "block";
			}
		}
		if( !( _cruiseAmount > _cruiseDepositAmount ) ){
			document.getElementById( "schedulePaymentDataDiv_1" ).style.display = "none";
			numberOfCreditCardsForScheduledPayment = 1; 
		}
		
		document.getElementById( "creditCardAmount_schedulePayment_0" ).value =  parseFloat( _costcoAmount - _costcoDeposit ).toFixed(2);
		document.getElementById( "creditCardAmount_schedulePayment_1" ).value = parseFloat( _cruiseAmount - _cruiseDepositAmount ).toFixed(2);
		document.getElementById( "anotherCardDiv" ).style.display = "none";
		document.getElementById( "costcoFullPaymentDesc" ).style.display = "none";
		document.getElementById( "cruiseFullPaymentDesc" ).style.display = "none";
	}
	if ( currentPayment == 'FULL_PAYMENT' ) {
		for( var count = 0; count < numberOfCreditCardsForFullPayment; count++ ) {
			document.getElementById( "currentPaymentDataDiv_" + count ).style.display = "block";
			var cardAmount = document.getElementById( 'creditCardAmount_fullPayment_' + count ).value;
			document.getElementById( 'creditCardAmount_fullPayment_' + count).value = parseFloat( cardAmount ).toFixed(2);
			//document.getElementById( "creditCardAmount_fullPayment_div_"+count ).innerHTML = getSuperPNRCreditCardRowAsHTML(count, 0.0);
		}
		document.getElementById( "schedulePaymentHeaderDiv").style.display="none";
		document.getElementById( "anotherCardDiv" ).style.display = "block";
		document.getElementById( "costcoSchedulePaymentDesc" ).style.display = "none";
		document.getElementById( "cruiseSchedulePaymentDesc" ).style.display = "none";
	}
}
function validateAmountForSuperPNR(){
	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(selectedPaymentOption == 'FULL_PAYMENT') {
 			/*var costcoAmount = document.getElementById('creditCardAmount_fullPayment_0').value;
 			if( parseFloat( costcoAmount ) < parseFloat( _costcoAmount )) {
 				document.getElementById('creditCardAmount_fullPayment_0').focus();
				showErrorMessage('Please enter an amount not less than the costco amount of '+ formatCurrency(_costcoAmount) + '.', 'dataContent', 'creditCardAmount_fullPayment_0', '1px solid #7f9db9');
				return;
			}
			if( parseFloat( costcoAmount ) > parseFloat( _costcoAmount ) ) {
 				document.getElementById('creditCardAmount_fullPayment_0').focus();
				showErrorMessage('Please enter an amount not more than the costco amount of '+ formatCurrency(_costcoAmount) + '.', '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 validatePaymentAmountForSuperPnr( paymentAmountElementName , cardIndex ){
	var paymentAmountElement = document.getElementById(paymentAmountElementName);
	if( paymentAmountElement ) {
		var paymentAmount = paymentAmountElement.value;
		if( isFloat( paymentAmount ) ) {
			paymentAmountElement.value = parseFloat(paymentAmount).toFixed(2);
			var scheduleCard1 = document.getElementById( "creditCardAmount_schedulePayment_0" ).value;
			var scheduleCard2 = document.getElementById( "creditCardAmount_schedulePayment_1" ).value;
			document.getElementById( "creditCardAmount_schedulePayment_0" ).value;
			if( cardIndex = 0 ) {
				if( !isCostcoCardAmountModified && parseFloat( scheduleCard1 ) != ( _costcoAmount - _costcoDeposit ) ) {
					showErrorMessage('Please enter an amount equal to the  costco amount of '+ formatCurrency( _costcoAmount - _costcoDeposit ) + '.', 'dataContent', 'creditCardAmount_schedulePayment_0', '1px solid #7f9db9');
					return;
				}
			} else if( cardIndex = 1 && parseFloat( scheduleCard2 ) != ( _cruiseAmount - _cruiseDepositAmount ) ) {
				showErrorMessage('Please enter an amount equal to the  cruise amount of '+ formatCurrency( _cruiseAmount - _cruiseDepositAmount ) + '.', 'dataContent', 'creditCardAmount_schedulePayment_1', '1px solid #7f9db9');
				return;
			}
		}
		else {
			showErrorMessage('Amount entered is not valid. Please enter a valid amount.', 'dataContent', paymentAmountElementName, '1px solid #7f9db9');
		}
	}
}
function showHideSuperPNRPayment( obj ){
	if ( obj.value == 'SCHEDULED_PAYMENT' ) {
		isSchedulePayment = true;
		for( var count = 0; count < numberOfCreditCardsForScheduledPayment; count++ ) {
			document.getElementById( "schedulePaymentDataDiv_" + count ).style.display = "block";
		}	
		document.getElementById( "creditCardAmount_fullPayment_div_0" ).innerHTML = getSuperPNRCreditCardRowAsHTML(0, document.getElementById( "depositAmount" ).value );
		
		if( numberOfCreditCardsForFullPayment >= 1 ) {
			for( var count = 1; count < numberOfCreditCardsForFullPayment; count++ ) {
				document.getElementById( "currentPaymentDataDiv_"+ count ).style.display = "none";
			}
		}
		document.getElementById( "schedulePaymentHeaderDiv" ).style.display = "block";
		//document.getElementById( "creditCardAmount_schedulePayment_0" ).value = parseFloat( _grossAmount - parseFloat( _depositAmount ) ).toFixed(2);
		document.getElementById( "creditCardAmount_schedulePayment_0" ).value =  parseFloat( _costcoAmount - _costcoDeposit ).toFixed(2);
		document.getElementById( "creditCardAmount_schedulePayment_1" ).value = parseFloat( _cruiseAmount - _cruiseDepositAmount ).toFixed(2);
		numberOfCreditCardsForFullPayment = 2;
		document.getElementById( "anotherCardDiv" ).style.display = "none";
		document.getElementById( "costcoFullPaymentDesc" ).style.display = "none";
		document.getElementById( "cruiseFullPaymentDesc" ).style.display = "none";
		document.getElementById( "costcoSchedulePaymentDesc" ).style.display = "block";
		document.getElementById( "cruiseSchedulePaymentDesc" ).style.display = "block";
		if( !( _cruiseAmount > _cruiseDepositAmount ) ){
			document.getElementById( "schedulePaymentDataDiv_1" ).style.display = "none";
			numberOfCreditCardsForScheduledPayment = 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 = getSuperPNRCreditCardRowAsHTML(count, _grossAmount );
			}
		}
		document.getElementById( "creditCardAmount_fullPayment_0" ).value = parseFloat( _costcoAmount ) .toFixed(2);
		document.getElementById( "creditCardAmount_fullPayment_1" ).value = parseFloat( _cruiseAmount ) .toFixed(2);
		document.getElementById( "anotherCardDiv" ).style.display = "block";
		document.getElementById( "costcoSchedulePaymentDesc" ).style.display = "none";
		document.getElementById( "cruiseSchedulePaymentDesc" ).style.display = "none";
		document.getElementById( "costcoFullPaymentDesc" ).style.display = "block";
		document.getElementById( "cruiseFullPaymentDesc" ).style.display = "block";
	}
}
function removeSuperPNRCreditCard( paymentMode, index ) {
	var previousCardAmount = 0;
	var creditCardAmount;
 	if ( paymentMode == 'FULL_PAYMENT' ) {
		document.getElementById( "currentPaymentDataDiv_" +index ).style.display = "none";
		if(index != 1 )
		document.getElementById( "remove_fullPayment_" +(index-1) ).style.display = "none";
		numberOfCreditCardsForFullPayment--;
		// Re populating the amount
		document.getElementById( "creditCardAmount_fullPayment_1" ).value = parseFloat( _cruiseAmount ) .toFixed(2);
	}
}
function displaySuperPNRCreditCardNumber( 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;
				document.getElementById( "creditCardNumber_schedulePayment_1" ).value = obj.value;
			} else if ( obj == document.getElementById( "creditCardExpirationMonth_fullPayment_0" ) ) {
				document.getElementById( "creditCardExpirationMonth_schedulePayment_0" ).value = obj.value;
				document.getElementById( "creditCardExpirationMonth_schedulePayment_1" ).value = obj.value;
			} else if ( obj == document.getElementById( "creditCardExpirationYear_fullPayment_0" ) ) {
				document.getElementById( "creditCardExpirationYear_schedulePayment_0" ).value = obj.value;
				document.getElementById( "creditCardExpirationYear_schedulePayment_1" ).value = obj.value;
			}
		}
	}
}

function getSuperPNRCreditCardRowAsHTML(index, amount) {
	if( index == 0 ){
		return '<input type="text" name="creditCardAmount_fullPayment_'+index+'" id="creditCardAmount_fullPayment_'+index+'" class="fs11 textbox w70"  value=' + parseFloat( amount ).toFixed(2) + ' disabled="disabled" maxlength="10" onkeypress="return checkDecimal(event);" onblur="formatDecimal( this, 2 ); validateAmountForSuperPNR();"/>';
	}else{
		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 ); validateAmountForSuperPNR();"/>';
	}
}

/**
 * 
 */

function chooseResponse(questionIndex,isUserDefinedResponse) {
	
	var optionSelected = getCheckedValue( document.getElementsByName("radio_" +questionIndex));
	document.getElementById( "surveyResponse_"+ questionIndex).value = optionSelected;
	
	if((isUserDefinedResponse == false ||	isUserDefinedResponse == 'false')	&& document.getElementById( "userDefinedResponse_"+questionIndex)!=undefined)
	{
		document.getElementById( "userDefinedResponse_"+questionIndex).value = "";
	}
	document.getElementById( "isUserDefinedResponse_"+ questionIndex).value = isUserDefinedResponse;     
}

function chooseMatrixResponse(questionIndex,matrixIndex) {
	var optionSelected = getCheckedValue( document.getElementsByName("radio_" +questionIndex+"_"+matrixIndex));
	document.getElementById("response_"+questionIndex+"_"+matrixIndex).value = optionSelected;	
}


function selectStarRating(questionIndex, matrixIndex, rating, boundary)
{
	if(matrixIndex=='')
	{
		document.getElementById( "surveyResponse_"+ questionIndex).value = rating;
		//document.getElementById("star_"+questionIndex+"_"+rating).src= _webLoc + '/shared/images/core/starRating-selected.gif';
		for( var i = 1 ; i <= rating ; i++ ) {
			document.getElementById("star_"+questionIndex+"_"+i).src =_webLoc + '/shared/images/core/starRating-hover.gif';
		}
		for( var j = (++rating) ; j <= boundary; j++ ) {
			document.getElementById("star_"+questionIndex+"_"+j).src =_webLoc + '/shared/images/core/starRating.gif';
		}
	}
	else{
		document.getElementById("response_"+questionIndex+"_"+matrixIndex).value = rating;
		for( var i = 1 ; i <= rating ; i++ ) {
			document.getElementById("star_"+questionIndex+"_"+matrixIndex+"_"+i).src =_webLoc + '/shared/images/core/starRating-hover.gif';
		}
		for( var j = (++rating) ; j <= boundary; j++ ) {
			document.getElementById("star_"+questionIndex+"_"+matrixIndex+"_"+j).src =_webLoc + '/shared/images/core/starRating.gif';
		}
	}
	
}


function highlightStarRating(questionIndex, matrixIndex, rating, boundary)
{
	if(matrixIndex=='')
	{
		//document.getElementById(questionIndex+"_"+rating).src= _webLoc + '/shared/images/core/starRating-hover.gif';
		for( var i = 1 ; i <= rating ; i++ ) {
			document.getElementById("star_"+questionIndex+"_"+i).src =_webLoc + '/shared/images/core/starRating-hover.gif';
		}
		for( var j = (++rating) ; j <= boundary; j++ ) {
			document.getElementById("star_"+questionIndex+"_"+j).src =_webLoc + '/shared/images/core/starRating.gif';
		}
	}
	else{
		for( var i = 1 ; i <= rating ; i++ ) {
			document.getElementById("star_"+questionIndex+"_"+matrixIndex+"_"+i).src =_webLoc + '/shared/images/core/starRating-hover.gif';
		}
		for( var j = (++rating) ; j <= boundary; j++ ) {
			document.getElementById("star_"+questionIndex+"_"+matrixIndex+"_"+j).src =_webLoc + '/shared/images/core/starRating.gif';
		}
		
	}
}

function unHighlightStarRating(questionIndex, matrixIndex, boundary)
{
	if(matrixIndex=='')
	{
		var previousSelection = document.getElementById( "surveyResponse_"+ questionIndex).value;
		if(previousSelection != "") {
			selectStarRating(questionIndex,matrixIndex,previousSelection, boundary);
		} else {
			for( var j=1 ; j <= boundary; j++ ) {
				document.getElementById("star_"+questionIndex+"_"+j).src =_webLoc + '/shared/images/core/starRating.gif';
			}
		}
	}
	else
	{
		var previousSelection = document.getElementById("response_"+questionIndex+"_"+matrixIndex).value;
		if(previousSelection != "") {
			selectStarRating(questionIndex,matrixIndex,previousSelection, boundary);
		} else {
			for( var j=1 ; j <= boundary; j++ ) {
				document.getElementById("star_"+questionIndex+"_"+matrixIndex+"_"+j).src =_webLoc + '/shared/images/core/starRating.gif';
			}
		}
	}
}



function submitSurveyResponse()
{

	var surveyQuestionsLength = document.getElementById( "surveyQuestionsLength").value;
	var jsonSurveyResponse="";
	var jsonSurveyQuestionResponse="";
	var surveyDefinitionId = document.getElementById( "surveyDefinitionId").value;
	for(var i=0;i<surveyQuestionsLength;i++)
	{
		var questionId =document.getElementById( "questionId_"+i).value;
		var surveyResponse = document.getElementById( "surveyResponse_"+i).value;
		var questionTitle = document.getElementById( "questionTitle_"+i).value;
		questionTitle=encodeHTML(questionTitle);
		var isUserDefinedResponse = document.getElementById( "isUserDefinedResponse_"+i).value;
		var userDefinedResponse = "";
		if(document.getElementById( "userDefinedResponse_"+i)!=undefined)
		{
			userDefinedResponse =	document.getElementById( "userDefinedResponse_"+i).value;
		}
		if(userDefinedResponse!=""	&&	isUserDefinedResponse=='false')
		{
			showErrorMessage( 'Please click the appropriate option for your response.', 'dataContent', 'userDefinedResponse_'+i , '1px solid #7f9db9');
			return false;
		}
		if(isUserDefinedResponse== 'true'	&&	userDefinedResponse=="")
		{
			showErrorMessage( 'Please enter a response for the option you have selected.', 'dataContent', 'userDefinedResponse_'+i , '1px solid #7f9db9');
			return false;
		}
		
		if(isUserDefinedResponse== 'true')
		{
			surveyResponse = userDefinedResponse;
		}
		var questionType = document.getElementById( "questionType_"+i).value;
		if(questionType == "1")
		{
			surveyResponse = document.getElementById( "freeForm_"+i).value;
		}
		var matrixQuestionLength = document.getElementById( "matrixQuestionLength_"+i).value;
		var jsonMatrixResponse = "," ;
				
		if(questionType == "2")
		{
			var columnTitlesLength = document.getElementById( "columnTitlesLength_"+i).value;
			var checkBoxResponse="";
			if(matrixQuestionLength == 0)
			{				
				for(var j=0; j< columnTitlesLength;j++)
				{
					if(document.getElementById("checkbox_"+i+"_"+j).checked)
					{
						checkBoxResponse+=document.getElementById("checkbox_"+i+"_"+j).value+"|";
					}
				}
				if(surveyResponse!="")
				{
					checkBoxResponse+= surveyResponse+"|";
				}
				surveyResponse= checkBoxResponse.substring( 0, checkBoxResponse.lastIndexOf( "|" ) );
			}
			else
			{
				for(var j=0; j< matrixQuestionLength;j++)
				{
					checkBoxResponse="";
					for(var k=0; k< columnTitlesLength;k++)
					{
						if(document.getElementById("checkbox_"+i+"_"+j+"_"+k).checked)
						{
							checkBoxResponse+=document.getElementById("checkbox_"+i+"_"+j+"_"+k).value+"|";
						}
					}
					var matrixResponse = checkBoxResponse.substring( 0, checkBoxResponse.lastIndexOf( "|" ) );
					
					jsonMatrixResponse+=  "'matrixResponse_"+j+"':'"+matrixResponse + "',";
				}
				
				jsonMatrixResponse = jsonMatrixResponse.substring( 0, jsonMatrixResponse.lastIndexOf( "," ) );
			}
		}
		else
		{
			for(var j=0; j< matrixQuestionLength;j++)
			{
				var matrixResponse = document.getElementById("response_"+i+"_"+j).value
				
				jsonMatrixResponse+=  "'matrixResponse_"+j+"':'"+matrixResponse + "',";
			}
			
			jsonMatrixResponse = jsonMatrixResponse.substring( 0, jsonMatrixResponse.lastIndexOf( "," ) );
		}
		
		surveyResponse = encodeHTML(surveyResponse);
		//jsonSurveyQuestionResponse += "{'surveyDefinitionId':" + "'" + surveyDefinitionId + "',";
		jsonSurveyQuestionResponse += "{'questionId':" + "'" + questionId + "',";
		jsonSurveyQuestionResponse += "'questionTitle':" + "'" + questionTitle + "',";	
		jsonSurveyQuestionResponse += "'surveyResponse':" + "'" + surveyResponse + "',";
		jsonSurveyQuestionResponse += "'isUserDefinedResponse':" + "'" + isUserDefinedResponse + "'";
		
		
		jsonSurveyQuestionResponse+=jsonMatrixResponse ;
		var includeComment = document.getElementById( "includeComment_"+i).value;
		if(includeComment=='true')
		{
			var comments = document.getElementById( "Comments_"+i).value;
			comments = encodeHTML(comments);
			jsonSurveyQuestionResponse+= ",'comments':" + "'" + comments + "'";
		}	
		jsonSurveyQuestionResponse+="},";
	}
		
	jsonSurveyQuestionResponse = jsonSurveyQuestionResponse.substring( 0, jsonSurveyQuestionResponse.lastIndexOf( "," ) );
	jsonSurveyResponse += "{'SURVEY_DEFINITION_INFO': {'surveyDefinitionId':'"+ surveyDefinitionId + "'}, " + "'SURVEY_QUESTION_RESPONSE':[" + jsonSurveyQuestionResponse+"]}";
	var queryString = 'sm=3';
	queryString += "&surveyDetails=" + jsonSurveyResponse;
	makeAjaxCallWithWaitingDiv( "takeASurvey.act", queryString,  null, 'rightContent', 'callbackSubmitSurveyResponse');
	
}

function callbackSubmitSurveyResponse(message)
{
	if(!showMessage(this.messageType, this.messageCode, this.message, 'dataContent')){
		showMessage(this.messageType, this.messageCode, message, 'dataContent' , null, null);
		disableElement ( 'dataContent' , false );
		loadHomePage();
	}
	
	return true;
}

function continueToSurveyQuestions()
{
	var bookingId = document.getElementById("bookingNumber").value;
	var lastName = document.getElementById("lastName").value;
	if( bookingId == "" ) {
		showErrorMessage('Please enter your Costco Booking Number.', 'dataContent', 'bookingNumber', '1px solid #7f9db9');
		return;
		}
	if( lastName == "" ) {
		showErrorMessage('Please enter your Last Name', 'dataContent', 'lastName', '1px solid #7f9db9');
		return;
	}
	
	var queryParams = "sm=4";
	queryParams+= "&bookingId=" + bookingId;
	queryParams+= "&lastName=" + lastName;
	disableElement ( 'dataContent' , true );
	makeAjaxCallWithWaitingDiv( "takeASurvey.act", queryParams,  null, 'rightContent', 'callbackContinueToSurveyQuestions',null, '/gi/memberInfo/MemberSurvey');
}

function callbackContinueToSurveyQuestions()
{
	showMessage(this.messageType, this.messageCode, this.message, 'dataContent' , null, null);
	disableElement ( 'dataContent' , false );
	return true;
}


function checkSurveyLastNameEnterKey( event ) {
	if( isEnterKey( event ) ) {
		continueToSurveyQuestions();
	}
}
function resetTextArea(textAreaName)
{
	var spaceChar="  ";
	var textAreaValue=document.getElementById(textAreaName).value;
	//alert(textAreaValue);
	if(textAreaValue == '')
	{
		document.getElementById(textAreaName).value = '';
	}
}function upgradeCarCategory( selectedCarProductUid, selectedUpsellCategoryUid, previousSelectedCategoryUid ) {
	var queryString = "cb=1";
	queryString += "&selectedCarProductUid=" + selectedCarProductUid;
	queryString += "&selectedUpsellCategoryUid=" + selectedUpsellCategoryUid;
	queryString += "&previousSelectedCategoryUid=" + previousSelectedCategoryUid;
	disableElement ( 'dataContent', true );
	makeAjaxCallWithWaitingDiv( 'carBooking.act', queryString , null , 'rightContent' , 'callbackUpgradeCarCategory' , null, null );
}

function callbackUpgradeCarCategory() {
	if ( ! showMessage(this.messageType, this.messageCode, this.message , 'dataContent' ) ) {
		disableElement ( 'dataContent', false );
		loadCarTripSummary( CarTripSummaryDisplayConstants.DISPLAY_CAR_TRIP_SUMMARY_UPTO_OPTIONAL_REQUESTS );
	}
	return true;
}
function loadCarBookingRecap() {
	var queryString = "cb=0";
	disableElement ( 'dataContent', true );
	makeAjaxCallWithWaitingDiv( 'carBooking.act', queryString , null , 'rightContent' , 'callbackLoadCarBookingRecap' , null, null );
}

function callbackLoadCarBookingRecap() {
	if ( ! showMessage(this.messageType, this.messageCode, this.message , 'dataContent' ) ) {
		disableElement ( 'dataContent', false );
		loadCarTripSummary( CarTripSummaryDisplayConstants.DISPLAY_CAR_TRIP_SUMMARY_UPTO_OPTIONAL_REQUESTS );
	}
	return true;
}

function loadCarMemberLoginPage( defaultUser ){
	if(!defaultUser){
		//window.location.href= _secureContextRoot + _webLoc+ "/?h=3&checkMemberInactivity=true&uid=" + UID();
		showMessage(2, true, 'Membership is inactive. Please login again to make a booking.', 'dataContent', callBackLoadCarMemberLoginPage,null );
	}
	else{
		window.location.href= _secureContextRoot + _webLoc+ "/?h=7&checkMemberInactivity=true&uid=" + UID();
	}
}

function callBackLoadCarMemberLoginPage() {
	hideMessageBox(UID(),'dataContent' );
	window.location.href= _secureContextRoot + _webLoc+ "/?h=7&checkMemberInactivity=true&uid=" + UID();
}

function loadCarFinalizeBookingRecap(){
	disableElement ( 'dataContent' , true );
	var trackingText = '';
	
	if (_carPopupSearch == 'true'){
		trackingText = '/rc/booking/popupWidget/bookingCheckout/' + _carCompanyName + '/' + (_couponCode != '' ? _couponCode : 'NONE');
	}
	else{
		trackingText = '/rc/booking/searchWidget/bookingCheckout/' + _carCompanyName;		
	}	
	makeAjaxCallWithWaitingDiv( 'carBooking.act', 'cb=2' , null , 'rightContent' , 'callbackLoadCarFinalizeBookingRecap' , null, trackingText );	
}

function callbackLoadCarFinalizeBookingRecap(){
	if ( ! showMessage(this.messageType, this.messageCode, this.message , 'dataContent' ) ) {
		disableElement( 'dataContent', false );
	}
	return true;
}

function loadCarBookingRecapPage(){
	disableElement ( 'dataContent' , true );
	makeAjaxCallWithWaitingDiv( 'carBooking.act', 'cb=0', null, 'rightContent', 'callbackLoadCarFinalizeBookingRecap', null, null );
}
function displayAdditionalInformation() {
	var additionalInfoPopupDivContainer = document.getElementById( 'additionalInfoPopupDivContainer' );
	if( isNull( additionalInfoPopupDivContainer ) ) {
		additionalInfoPopupDivContainer = createPopupDiv('additionalInfoPopupDivContainer', 0, 0, 450, -1, 200, false, true, 'popupDivSmall tal');
	}
	var queryString = "cb=5";
	makeAjaxCall( 'carBooking.act', queryString , null , 'additionalInfoPopupDivContainer' , 'callbackDisplayAdditionalInformation' , '' );
}

function callbackDisplayAdditionalInformation() {
	 if( !showMessage(this.messageType, this.messageCode, this.message , 'dataContent' ) ) {
		showBlock( 'additionalInfoPopupDivContainer' );
		positionBlockCentrally( 'additionalInfoPopupDivContainer' );	
		disableElement( 'dataContent', true );
	 }
	 return true;
}

function confirmCarRentalBooking() {
	clearErrorElements();
	if( !( validateField( 'firstName' , 'Please enter a first name' ) ) ) {
		return false;
	}
	if( !( validateField( 'lastName' , 'Please enter a last name' ) ) ) {
		return false;
	}
	if( !( validateField( 'dayTimePhoneStateCode' , 'Please enter valid day time phone.' ) ) ) {
		return false;
	}
	if( !( validateField( 'dayTimePhoneCityCode' , 'Please enter valid day time phone.' ) ) ) {
		return false;
	}
	if( !( validateField( 'dayTimePhone' , 'Please enter valid day time phone.' ) ) ) {
		return false;
	}
	if( !( validatePhoneNumber( 'dayTimePhoneStateCode', 'dayTimePhoneCityCode', 'dayTimePhone', 'Please enter a valid ten digits day time phone number' ) ) ) {
		return false;
	}
	/*if( !isEmpty( trim( document.getElementById( "dayTimePhoneExtension" ).value ) ) && ( ( document.getElementById( "dayTimePhoneExtension" ).value ).length < 4 ) ) {
		showErrorMessage( 'Please enter a valid dat time phone extension', 'dataContent', 'dayTimePhoneExtension', '1px solid #7f9db9' );		
		return false;
	}*/
	if( !document.getElementById( "carTermsAndConditions").checked ) {
		showErrorMessage('To proceed with booking, you must read and accept the Terms and Conditions', 'dataContent', 'carTermsAndConditions', '1px solid #7f9db9');
		return false;
	}
	
	var alternateEmailId = document.getElementById( "alternateEmail" ).value;
	// alternate email id is optional field.
	if( !isEmpty( trim( alternateEmailId ) ) ) {
		if( !( validateEmail( 'alternateEmail') ) ) {
			return false;
		}
	} else {
		alternateEmailId = document.getElementById( "registeredEmailId" ).value
	}
	
	var queryString = "cb=3"
	queryString += "&firstName=" + document.getElementById( "firstName").value;
	queryString += "&lastName=" + document.getElementById( "lastName").value;
	queryString += "&dayTimePhone=" + document.getElementById( "dayTimePhoneStateCode").value + document.getElementById( "dayTimePhoneCityCode").value + document.getElementById( "dayTimePhone").value;
	queryString += "&dayTimePhoneExtn=" + document.getElementById( "dayTimePhoneExtension").value;
	queryString += "&alternateEmailId=" + alternateEmailId;
	queryString += "&carRentalLoyaltyNumber=" + document.getElementById( "carRentalLoyaltyNumber").value;
	disableElement ( 'dataContent' , true );
	
	var trackingText = '';
	if (_carPopupSearch == 'true'){
		trackingText = '/rc/booking/popupWidget/bookingConfirmation/' + _carCompanyName + '/' + (_couponCode != '' ? _couponCode : 'NONE');
	}
	else{
		trackingText = '/rc/booking/searchWidget/bookingConfirmation/' + _carCompanyName;		
	}	

	makeAjaxCallWithWaitingDiv( 'carBooking.act', queryString , null , 'rightContent' , 'callbackConfirmCarRentalBooking' , null, trackingText );	
}

function callbackConfirmCarRentalBooking() {
	 if( !showMessage(this.messageType, this.messageCode, this.message , 'dataContent' ) ) {
		disableElement( 'dataContent', false );
	 }
	 return true;
}

function loadCarBookingSummary(){
	var queryString = 'lc=22&lbc=0';
	disableElement ( 'dataContent' , true );
	makeAjaxCallWithWaitingDiv( 'leftContent.act', queryString, null, 'leftContent', 'callbackLoadCarBookingSummary', null, null );
}

function callbackLoadCarBookingSummary(){
	if ( ! showMessage(this.messageType, this.messageCode, this.message , 'dataContent' ) ) {
		disableElement ( 'dataContent' , false );
	}
}

function loadFinalizeCarBookingDetails() {
	disableElement ( 'dataContent' , true );
	makeAjaxCallWithWaitingDiv( 'carBooking.act', 'cb=2', null, 'rightContent', 'callbackLoadCarBookingSummary', null, null );
}var CAR_RETRIEVE_CANCELLED_BOOKING_ERROR = 8205;
function loadCancelBookingConfirmationPopup( bookingId){
	var cancelBookingPopupDivContainer = document.getElementById( 'cancelBookingPopupDivContainer' );
	if( isNull( cancelBookingPopupDivContainer ) ) {
		cancelBookingPopupDivContainer = createPopupDiv('cancelBookingPopupDivContainer', 0, 0, 400, -1, 200, false, true,  "tal popupDivSmall");
		cancelBookingPopupDivContainer.style.height = toPixels(100); 
	}
	var queryString = 'cb=7&bookingId=' + bookingId;
	makeAjaxCall( 'carBooking.act', queryString, null, 'cancelBookingPopupDivContainer', 'callbackLoadCancelBookingConfirmationPopup', '');
}

function callbackLoadCancelBookingConfirmationPopup() {
	 if( !showMessage(this.messageType, this.messageCode, this.message , 'dataContent' ) ) {
	 	positionBlockCentrally('cancelBookingPopupDivContainer');
		showBlock('cancelBookingPopupDivContainer');
		disableElement('dataContent', true);
	 }
	return true;
}

function cancelCarBooking( bookingId ) {
	var queryString = 'cb=8&bookingId=' + bookingId;
	disableElement ( 'cancelBookingPopupDivContainer' , true );
	
	makeAjaxCallWithWaitingDiv( 'carBooking.act', queryString, null, null, 'callbackCancelCarBooking', null, null );
}

function callbackCancelCarBooking() {
	if ( !showMessage(this.messageType, this.messageCode, this.message , 'cancelBookingPopupDivContainer' ) ) {
		disableElement ( 'cancelBookingPopupDivContainer', false );
		hideBlock('cancelBookingPopupDivContainer');
		var splashScreenRequest = new SplashScreenRequest();
		splashScreenRequest.splashScreenText = "Please Wait...";
		displaySearchingPopup(splashScreenRequest)
		window.location.href= _secureContextRoot + _webLoc+ "/?h=8&uid=" + UID();
	}
	return true;
}

function loadCarBooking( bookingId ) {
	var queryString = 'cb=9&bookingId=' + bookingId;
	disableElement ( 'dataContent' , true );
	makeAjaxCallWithWaitingDiv( 'carBooking.act', queryString, null, 'rightContent', 'callbackLoadCarBooking', null, null );
}

function callbackLoadCarBooking() {
	if( this.messageCode == CAR_RETRIEVE_CANCELLED_BOOKING_ERROR ) {
		showMessage(this.messageType, this.messageCode, this.message , 'dataContent', 'loadMemberPage' );
	} else if( !showMessage(this.messageType, this.messageCode, this.message , 'dataContent' ) ) {
		disableElement ( 'dataContent' , false );
	}
	return true;
}

function loadMemberPage() {
	var splashScreenRequest = new SplashScreenRequest();
	splashScreenRequest.splashScreenText = "Please Wait...";
	displaySearchingPopup(splashScreenRequest);
	window.location.href= _secureContextRoot + _webLoc+ "/?h=2&uid=" + UID()
}
