/* ******************** begin core js for booking ******************** */
/* dwrloading.js */
var showLoading = true;
var loadingMsg = null;

DWRUtil.useLoadingMessage = function()
{
DWREngine.setPreHook(function() { 

    var msgbox = document.getElementById('loadingbox');
    if (showLoading 
           && msgbox != null) {
        if (loadingMsg == null) { 
           loadingMsg = 'Loading';
        }
        msgbox.innerHTML=loadingMsg + '.<br><span class="oneMoment">One moment, please...</span>';

 		DeltaOverlayUtil.centerElement("", msgbox, 0, 0);
		msgbox.style.display = 'block';
    }
});
DWREngine.setPostHook(function() {
   hideLoadingMsg();
 });
};


function hideLoadingMsg() {
   var msgbox = document.getElementById('loadingbox');
   if (msgbox != null) {
       msgbox.innerHTML = '';
       msgbox.style.display = 'none';
	   msgbox.style.visibility = "hidden";
   }

}
function init() {
    DWRUtil.useLoadingMessage();
}
  
function setLoadingMsg(msg) {
    showLoading = true; 
    loadingMsg = msg;
}
      



/* common.js */
/* begin /booking/javascripts/common.js */

var isPaymentEligibleForTripProtector = true;
var isTripProtectorSelected = false;
function showMessage(e, msgTest) {
	var cursor = getPosition(e);
	var dtlBox = get('message');
	if (dtlBox != null) {
		setInnerHTML('message', msgTest);
		dtlBox.style.left  = cursor.x + "px";
		dtlBox.style.top   = cursor.y + "px";
		dtlBox.style.display = 'block';
	}
}
function getMessageHref(text, alt){
	var str = '';
	str = str +    '<a href="javascript:void(0)" onMouseOver="javascript:showMessage(event, \'' + alt + '\')" onMouseOut="javascript:hideMessage()">'+ text +'</a>';
	return str;
}
function hideMessage(){
	var dtlBox = get('message');
	if (dtlBox != null) {
		setInnerHTML('message', '');
		dtlBox.style.display = 'none';
	}
}    
function ccActions(cardType) { 
	ccNumberDisplay(cardType);
	updateProfileCheck();
}
function setVerifyIcon(type) {
	try {
		get("visaVerify").style.display = "none";
		get("mcSecure").style.display = "none";
		get("payPal").style.display = "none"; 
	} catch(e) {};
	switch(type){
		case "AX": break;
		case "VI": get("visaVerify").style.display = "block"; break;
		case "CA": get("mcSecure").style.display = "block"; break;
		case "PP": get("payPal").style.display = "block"; break;
		case "DS": break;
		case "DC": break;
		default: break;
	}
}
function ccNumberDisplay(cardType) {
	setVerifyIcon(cardType);
	if(cardType== "AX"||cardType== "VI"||cardType== "CA"||cardType== "DS"||cardType== "DC"||cardType== "JC") {
		get("ccNmbr").style.display = "block";
	} else {
		get("ccNmbr").style.display = "none";
	}
	if(cardType=="AX") {
		get("ccNumberField").maxLength =4;
		try {
			get("ccNumber").maxLength = 15;
			if (get("ccNumber").value.length > 15) {
				get("ccNumber").value = get("ccNumber").value.substring(0,15);
			}
		} catch (error) {}
	} else if(cardType=="MO"||cardType=="PP") {
	} else {
		get("ccNumberField").maxLength =3;
		try {
			get("ccNumber").maxLength = 20;
		} catch (error) {}
	}
	if(cardType!="MO"&&cardType!="PP") {
		if(exists(get("ccNumber"))) { get("ccNumber").style.display = "block"; }
		if(exists(get("ccExp"))) { get("ccExp").style.visibility = "visible"; }
		if(exists(get("exp"))) { get("exp").style.visibility = "visible"; }
		if(exists(get("nmbr"))) { get("nmbr").style.visibility = "visible"; }
		if(exists(get("eCreditCheckbox"))) { get("eCreditCheckbox").style.display = "block"; }
		if(exists(get("eCreditNotAvail"))){ get("eCreditNotAvail").style.display = "none"; }
	} else {
		if(exists(get("ccNumber"))) { get("ccNumber").style.display = "none"; }
		if(exists(get("ccExp"))) { get("ccExp").style.visibility = "hidden"; }
		if(exists(get("exp"))) { get("exp").style.visibility = "hidden"; }
		if(exists(get("nmbr"))) { get("nmbr").style.visibility = "hidden"; }
		if(exists(get("eCreditCheckbox"))) { get("eCreditCheckbox").style.display = "none"; }
		if(exists(get("eCreditNotAvail"))){ get("eCreditNotAvail").style.display = "block"; }
	}
	if(cardType!="AX") { try { if (ccDenied) { get("pwmAlert").style.display = "block"; } else { get("pwmAlert").style.display = "none"; } } catch(e) {} }
	if( cardType != "TP" && cardType != "DL" && cardType != "MO" && cardType != "PP" && cardType != "JC" ) {
		if(exists(get("fopAlert"))){ get("fopAlert").style.display = "none"; } // AX
	} else { 
		if(exists(get("fopAlert"))) { get("fopAlert").style.display = "block"; } // TP
	}
	if(exists(get("ccCompanyName"))){ get("ccCompanyName").style.display = "none"; }
	switch(cardType){
		case "AX": try { get("pwmAlert").style.display = "none"; } catch(e) {} break;
		case "VI": break;
		case "CA": break;
		case "PP": break;
		case "DS": break;
		case "DC": break;
		case "JC": break;
		default:
			get("ccNmbr").style.display = "none";
			/*
			if(get("ccExpiry")){
				get("ccExpiryMonth").style.display = "block";
				get("ccExpiryYear").style.display = "block";
			}*/
	}
	isTripProtectorSelected = updateTotalHandler.getInsuranceSelected()
	if (cardType!="MO"&&cardType!="PP"&&cardType!="TP"&&cardType!="JC"){
		updateTotalHandler.doPopulate();
		isPaymentEligibleForTripProtector = true;
		if(exists(get("trip_protector"))) { get("trip_protector").style.display = "block"; }
		if(exists(get("trip_protectorNotAvail"))){ get("trip_protectorNotAvail").style.display = "none"; }
	} else {
		isPaymentEligibleForTripProtector = false;
		updateTotalHandler.setInsuranceData(updateTotalHandler.getInsuranceCost(false), updateTotalHandler.getInsuranceCost(true), false);
		updateTotalHandler.doPopulate();
		updateTotalHandler.setInsuranceData(updateTotalHandler.getInsuranceCost(false), updateTotalHandler.getInsuranceCost(true), isTripProtectorSelected);
		if(exists(get("trip_protector"))) { get("trip_protector").style.display = "none"; }
		if(exists(get("trip_protectorNotAvail"))){ get("trip_protectorNotAvail").style.display = "block"; }
	}
	

}
function setCCType() {
	var paxInfo_ccType = get('ccType').value;
	ccNumberDisplay(paxInfo_ccType);
}

function runPaxInfoScripts(){	
	//merchandising component onload script
	if(document.getElementById('tripAdditionsPresent')){
		addPaxInfoInputListeners();
		document.getElementById('sendETicketEmail').disabled = true;	
	}
	var selectedCard = document.getElementById('ccType').value;	
	ccActions(selectedCard);
	if(exists(get('countryCode'))){
		try {
			addressMap.addressFields('countryCode');
		} catch(e) {
		
		}
	}
}

function postVerifyPurchaseForm(url){
	try{
		document["VerifyPurchaseForm"].action = url;
		document["VerifyPurchaseForm"].submit();
	} catch (error) { /* silent ignore test */ }
}
function showMoreContactOptions() {
	hide("show_more_contact_options");
	show("contact_option_1");
	show("contact_option_2");
}
function createHiddenInputElement(nme, id1, value){
	var inp = document.createElement("input");
	inp.type = "hidden";
	inp.id = id1;
	inp.name = nme;
	inp.value = value;
	return inp;
}
/*
function toggleSSRs(numPax) {
	for(var i=0;i<numPax;i++) {
		toggle("pax"+i+"_ssr");
	}
}
*/
function showPWM(){
	if(fromPaxInfo){		
		setClassName("summary_control","summary_ctl_open");
		hide("itinerary_summary");
		hide("summary_total_due");
		show("summary");
		setStyleAttr("summary","width","704px");
		show("paxinfo-price-per-pax");
		setStyleAttr("paxinfo-price-per-pax","width","704px");
	}
}

function expandItinerary(){
	setClassName("summary_control","summary_ctl_open");
	hide("itinerary_summary");
	hide("summary_total_due");
	show("selected_flights");
	show("selected_flights_price");
	show('review_itinerary_footer');
	resizeItineraryIframe();
}
function closeItinerary() {
	setClassName("summary_control","summary_ctl_closed");
	hide("selected_flights");
	hide("selected_flights_price");
	show("summary_total_due");
	show("itinerary_summary");
	hide('review_itinerary_footer');
	resizeItineraryIframe();
}
function ageCheck(e){
	var t = window.event ? window.event.srcElement : e ? e.target : null;
	if(t.id == "under14"){
		if(t.checked && !get('over18Label')){
			openWin('/planning_reservations/special_travel_needs/services_for_children/children_traveling_alone/index.jsp', 'UnaccompaniedMinor', 770, 500, 'yes');
			return true;
			
		} else {
			if(get('over18Label')){
				var el = get('over18');
				el.style.display = (el.style.display != "block" ? "block" : "none");
				var el = get('over18Label');
				el.style.display = (el.style.display != "block" ? "block" : "none");
				get('over18').checked = false;
			}
			return;
		}
	} else if (t.id == "over18"){
		if(t.checked && get('under14').checked){
			openWin('/planning_reservations/special_travel_needs/services_for_children/children_traveling_alone/index.jsp', 'UnaccompaniedMinor', 770, 500, 'yes');
			return true;
			
		} else {
			return;
		}
	
	}
};
function disableExpressPurchasing(id) {
	switch(id) {
		case "ecreditSelection":
			if(get(id).checked) { get('purchase_button').value="Continue" } else { get('purchase_button').value="Purchase Now"; }
			if(get(id).checked) { setInnerHTML('purchase_button_label',"Go to last step") } else { setInnerHTML('purchase_button_label',"Your payment type will be charged now."); }
	}
}

function hideTripProtector(elem){
	var payButton = get('purchase_button');
	try {
		if(exists(get('trip_protector'))) {
			if(elem.checked){
				hide('trip_protector');
				hide('tripTotalsTable');
				hide('purchaseTix_copy');
				isPaymentEligibleForTripProtector = false;
				payButton.value = 'Continue';
			
			} else {
				show('trip_protector');
				show('tripTotalsTable');
				show('purchaseTix_copy');
				isPaymentEligibleForTripProtector = true;
				payButton.value = 'Purchase Now';
			}
		}
	} catch(e) {}

}
var element = get('ccDropDownValue');
function checkCCID(element) {
	try {
		if(get('ccType[' + element.options.selectedIndex + ']').value != "American Exp") {
			get("ccNumberField").maxLength =3;
		} else {
			get("ccNumberField").maxLength =4;
		}
	} catch (error) {}
}
function toggleUseStoredCard(){
	show('stored-credit-cards'); 
	show('billing_stored-address');
	hide('billing_payment'); 
}

function toggleUseNewCard(){
	hide('stored-credit-cards'); 
	hide('billing_stored-address');
	show('billing_payment'); 
}

function toggleUseStoredAddress(){
	show('billing_address-fields');
	hide('billing_country');
	hide('billing_streets');
	hide('billing_municipal');
}

function toggleUseNewAddress(){
	hide('billing_address-fields');
	show('billing_country');
	show('billing_streets');
	show('billing_municipal');
}


/* end /booking/javascripts/common.js */


/* ssrutility.js */


/* ************************************************************

	/shared_content/components/js/apps/ssrutility.jsp	

************************************************************ */
<!-- mp_trans_urljs_disable_start -->

/*
	Validation Object
	Version 1.1
	last updated: 4/28/2008
*/
function ValidationObj() {
	this.oProps = new GenObj();
	this.forms = new Array();
	this.today = new Date();
	this.months = {Jan:0,Feb:1,Mar:2,Apr:3,Apr:4,Jun:5,Jul:6,Aug:7,Sep:8,Oct:9,Nov:10,Dec:11};
	this.monthsFullName = {"January":0,"February":1,"March":2,"April":3,"May":4,"June":5,"July":6,"August":7,"September":8,"October":9,"November":10,"December":11};
	this.curField = "";
	this.labels = null;
	this.numLabels = 0;
	this.numForms = 0;
	this.errorCollection = { }; /*this is a collection of errors based on LABEL, eg: { first_name : { count:2, errorRegionDivId : "name_fname_pax1_req_e", allElementIds:{ name_fname_pax1_req : "first_name", name_fname_pax2_req : "first_name"} } }*/
}
ValidationObj.prototype.setProp = function(prop,value) { this.oProps.setProp(prop,value); };
ValidationObj.prototype.getProp = function(prop) { var rtn = this.oProps.getProp(prop); if(rtn===undefined) {} return rtn; };
ValidationObj.prototype.disableFeatures = function(types) {
	//console.log("disableFeatures");
	/* supported values: disabled_buttons, init */
	this.setProp("disable",types);
};
/* function to allow the disabling of specific features, passed as a string array */
ValidationObj.prototype.isDisabled = function(val) {
	//console.log("isDisabled");
	var disabledFeatures = this.getProp("disable");
	if(exists(disabledFeatures)) {
		j = disabledFeatures.length;
		for (var i=0;i<j;i++) {
			if(disabledFeatures[i] == val) { return true; }
		}
	}
	return false;
};

ValidationObj.prototype.doesCCNumPassesLuhn = function(ccNum) {
	var sum = 0, digit = 0, addend = 0, timesTwo = false;
	for (i = ccNum.length - 1; i >= 0; i--) {
		digit = parseInt(ccNum.substring (i, i + 1));
		if (timesTwo) {
			addend = digit * 2;
			if (addend > 9) {
				addend -= 9;
			}
		} else {
			addend = digit;
		}
		sum += addend;
		timesTwo = !timesTwo;
	}
	return (sum % 10) === 0;
};
ValidationObj.prototype.getMonthNum = function(month) { 
	//console.log("getMonthNum");
	return this.months[month];
};
ValidationObj.prototype.deltamaticNames = function(t) {
	return t.replace(/['-]/g," "); /* replace ' with space, for names in deltamatic */
};
ValidationObj.prototype.removeSpaces = function(t) {
	return t.replace(/\s*/g,"");
};
ValidationObj.prototype.replaceMultipleSpaces = function(t) {
	return t.replace(/[\s]{2,}/g," "); 
};
ValidationObj.prototype.stripWhiteSpace = function(t) {
	return t.replace(/^\s*/,"").replace(/\s*$/,"");
};
ValidationObj.prototype.stripBadChars = function(t) {
	//console.log("stripBadChars");
	return this.stripWhiteSpace(this.replaceMultipleSpaces(t.replace(/[/\\]/g,""))).replace(/['-]/g," ");
};
ValidationObj.prototype.isNumber = function(id, length) {
	//console.log("isNumber");
	//Lucas added length parameter for number validation
	var t = get(id).value.replace(/,/g, "");
	if(arguments.length > 1){
		length = parseInt(length);	
		if(isNaN(t)){
			this.markError(id); return false;
		} else if(t.length == length){
			this.removeError(id);return true;
		} else {
			this.markError(id); return false;
		}		
	} else {
		if(isNaN(t) || this.stripWhiteSpace(t) === "") { this.markError(id); return false; }
		else { this.removeError(id);return true; }
	}
};
ValidationObj.prototype.isDataMMSlashDDSlashYYYY = function(id) {
	var t = get(id).value;
	if(/\d{1,2}\/\d{1,2}\/\d{2,4}/.test(t)) { this.removeError(id);return true; }
	else { this.markError(id); return false; }
}
ValidationObj.prototype.areEqual = function(id1, id2) {
	if(get(id1).value != get(id2).value) { 
		this.markError(id2); return false; }
}
ValidationObj.prototype.requiresCCID = function(type) {
	return (type == "AX" || type == "VI" || type == "CA" || type == "DS" || type == "DC");
};
ValidationObj.prototype.findParentForm = function(id) {
	//console.log("findParentForm");
	var curField = get(id);
	while(curField.parentNode) {
		if(exists(curField.parentNode.nodeName) && curField.parentNode.nodeName.toLowerCase() === "form") {
			return curField.parentNode.id;
		}
		curField = curField.parentNode;
	}
};
ValidationObj.prototype.copyFieldData = function(id,fromContainerId,toContainerId) {
	//console.log("copyFieldData");
	var tFrom = [];
	var tTo = [];
	var tmpCollection;
	var tmpType;
	if(get(id).checked) {
		tmpCollection = get(fromContainerId).getElementsByTagName("*");
		for(var i=0;i<tmpCollection.length;i++) {
			if(tmpCollection[i].id!="") {
				if(exists(get(tmpCollection[i].id))) {
					tmpType = tmpCollection[i].type;
					if(tmpType=="text"||tmpType=="textarea"||tmpType=="select-one"||tmpType=="select-multiple"||tmpType=="radio"||tmpType=="checkbox") {
						if(!tmpCollection[i].id.match(/_replicate/) && (!tmpCollection[i].id.match(/_exclude/))) { tFrom.push(tmpCollection[i]);}
					}
				}
			}
		}
	}
	tmpCollection = get(toContainerId).getElementsByTagName("*");
	for(var i=0;i<tmpCollection.length;i++) {
		if(tmpCollection[i].id!="") { 
			if(exists(get(tmpCollection[i].id))) {
				tmpType = tmpCollection[i].type;
				if(tmpType=="text"||tmpType=="textarea"||tmpType=="select-one"||tmpType=="select-multiple"||tmpType=="radio"||tmpType=="checkbox") {
					if(!tmpCollection[i].id.match(/_replicate/) && (!tmpCollection[i].id.match(/_exclude/))) { tTo.push(tmpCollection[i]);}
				}
			}
		}
	}
	if(get(id).checked) {
		for(var i=0;i<tFrom.length;i++) {
			tmpType = get(tFrom[i].id).type;
			switch(tmpType) {
				case "radio": get(tTo[i].id).selected = (get(tFrom[i].id).selected) ? "selected" : false; break;
				case "checkbox": get(tTo[i].id).checked = get(tFrom[i].id).checked; break;
				default: get(tTo[i].id).value = get(tFrom[i].id).value; break;
			}
			//get(tTo[i].id).disabled="disabled";
		}
	} else {
		for(var i=0;i<tTo.length;i++) { 
			tmpType = get(tTo[i].id).type;
			if(tmpType!="radio" && tmpType!="checkbox") { get(tTo[i].id).value=""; }
			//get(tTo[i].id).disabled="";
		}
	}
};


ValidationObj.prototype.copyHiddenFieldData = function(id,fromContainerId,toContainerId) {
	//number of fields must match in fromContainerId and toContainerId any other fields that are not to be copied should have a reference of _exclude in the ID
	//console.log("copyHiddenFieldData");
	var tFrom = [];
	var tTo = [];
	var tmpCollection;
	var tmpType;
	if(get(id).checked) {
		tmpCollection = get(fromContainerId).getElementsByTagName("input");
		for(var i=0;i<tmpCollection.length;i++) {
			if(tmpCollection[i].id!="") {
				if(exists(get(tmpCollection[i].id))) {
					tmpType = tmpCollection[i].type;
					if(tmpType=="hidden") {
						if(!tmpCollection[i].id.match(/_exclude/)) { tFrom.push(tmpCollection[i]); }
					}
				}
			}
		}
	}
	tmpCollection = get(toContainerId).getElementsByTagName("input");
	for(var i=0;i<tmpCollection.length;i++) {
		if(tmpCollection[i].id!="") { 
			if(exists(get(tmpCollection[i].id))) {
				tmpType = tmpCollection[i].type;
				if(tmpType=="hidden") {
					if(!tmpCollection[i].id.match(/_exclude/)) { tTo.push(tmpCollection[i]); }
				}
			}
		}
	}
	if(get(id).checked) {
		for(var i=0;i<tFrom.length;i++) {
			tmpType = get(tFrom[i].id).type;
			tmpValue = get(tFrom[i].id).value;
			get(tTo[i].id).value = get(tFrom[i].id).value; break;
		}
	} else {
		for(var i=0;i<tTo.length;i++) { 
		get(tTo[i].id).value=""; 
		}
	}
};

/* support for custom error messages */
ValidationObj.prototype.getCustomErrorMsg = function(id,label,whichCustom) {
	var formId = this.findParentForm(id);
	var customMessage = this.getProp("customMessages")[formId];
	var patterns = customMessage.patterns;
	for( var patternIdx=0, patternCheck=patterns.length; patternIdx<patternCheck; patternIdx++) {
		var patternTest = new RegExp(patterns[patternIdx].pattern);
		if(patterns[patternIdx].whichCustom.toLowerCase() === whichCustom.toLowerCase() && patternTest.test(id)) {
			return patterns[patternIdx].message;
		}
	}
	return ""; 
};

/* error marking */
ValidationObj.prototype.notificationExists = function(id) {
	//console.log("notificationExists");
	var t = get(id);
	return (exists(get("alerts_errors")) && exists(t))
};
ValidationObj.prototype.findErrorRegionDivIdByCollectionProp = function(errorCollectionProp, notFoundReturnValue) {
	var errorDetail = this.errorCollection[errorCollectionProp];
	if(exists(errorDetail)) {
		return errorDetail.errorRegionDivId
	}
	return notFoundReturnValue;
};
ValidationObj.prototype.createEmptyErrorElement = function(errorCollectionProp, currentErrorRegionDivId) {
	return this.errorCollection[errorCollectionProp] = { count : 0, errorRegionDivId : currentErrorRegionDivId, allIncludedElementIds : {} };
};
ValidationObj.prototype.addNotification = function(type,id,label,whichCustom) {	
	//console.log("addNotification");
	// supported types are alert, error, info, and success
	var errorCollectionProp = label.replace(/\W/g, "_");
	var errorDetail = this.errorCollection[errorCollectionProp];
	var currentErrorRegionDivId = this.findErrorRegionDivIdByCollectionProp(errorCollectionProp, id.toString() + '_e');
	if(!exists(errorDetail)) {
		errorDetail = this.createEmptyErrorElement(errorCollectionProp, currentErrorRegionDivId);
	}
	if(!exists(errorDetail.allIncludedElementIds[id])) {
		errorDetail.allIncludedElementIds[id] = errorCollectionProp;
		errorDetail.count ++;
	}
	if(!this.notificationExists(currentErrorRegionDivId)) {
		label = label.replace(/\*/g,"");
		var errorType = id.split("_")[0];
		   if(id.match("ffNum") || id.match("SMNum")) { errorType="loyaltyNum"; }
           if(id.match("ffPrgm")){ errorType="loyaltyProg"; }
		var msgs = getInnerHTML("alerts_errors");
		var customMsg = "";
		if(exists(this.getProp("customMessages"))) {
			customMsg = this.getCustomErrorMsg(id,label, ( exists(whichCustom) ? whichCustom : "" ) );
		}
		var message = "<div class=\""+type+"\" id=\"" + currentErrorRegionDivId + "\">";
		if(customMsg == "") {
			message += "The information entered for "+label+" below is not valid.";
			message += " ";
			switch(errorType) {
				case "name":
					message += "Please ensure it has at least 2 characters and contains only letters and spaces.";
					break;
				case "cc":
					message += "";
					break;
				case "birth":
					message += "Please enter a date in the past for the date of birth.";
					break;
				case "exp":
					message += "Please enter a date in the future for the expiration.";
					break;
				case "gender":
					message += "Please select one of the options for gender.";
					break;
				case "passport":
					message += "";
					break;
			    case "loyaltyNum":
					message += "Frequent flyer numbers must contain between 5 to 20 numbers.";
                    break;
                 case "loyaltyProg":
	                 message += "Please select an airline program from the list provided.";
                   break;
                 case "email":
	                 message += "Please make sure your email addresses match.";
                   break;
				default:
					break;
			}
		} else {
			message += customMsg;
		}
		message += "</div>";
		msgs += message;
		setInnerHTML("alerts_errors",msgs);
	}
};
ValidationObj.prototype.getErrorCollectionPropByElementId = function(id) {
	for(var errorProp in this.errorCollection) {
		var errorDetail = this.errorCollection[errorProp];
		for(var errorElementId in errorDetail.allIncludedElementIds) {
			if(errorElementId === id) {
				return errorDetail.allIncludedElementIds[errorElementId];
			}
		}
	}
	return null;

};
ValidationObj.prototype.removeNotification = function(id) {
	//console.log("removeNotification");
	setClassName(id,"");
	var removeErrorMessage = false;
	var errorRegionDivId = id + "_e";
	var errorCollectionProp = this.getErrorCollectionPropByElementId(id);
	var errorDetail = this.errorCollection[errorCollectionProp];
	if( exists(errorDetail) ) {
		if(exists(errorDetail.allIncludedElementIds[id])) {
			errorDetail.count --;
		}
		errorRegionDivId = errorDetail.errorRegionDivId;
		if(errorDetail.count === 0) { removeErrorMessage = true; }
		errorDetail.allIncludedElementIds[id] = null;
	}
	if(removeErrorMessage) {
		var msgNodes = get("alerts_errors").getElementsByTagName("div");
		for(var i=0;i<msgNodes.length;i++){
			if( msgNodes[i].id === errorRegionDivId ) { get("alerts_errors").removeChild(msgNodes[i]);}
		}
	}
};
ValidationObj.prototype.addFormAndLabelData = function(id) {
	var tmpId;
	this.labels = getByTagName("label");
	var fieldLabels = this.labels;
	this.forms = document.forms;
	this.numLabels = this.labels.length;
	this.numForms = this.forms.length;
	
}
ValidationObj.prototype.markError = function(id,whichCustom) {
	//console.log("markError");
	get(id).setAttribute('class','error');
	get(id).setAttribute('className','error'); /* for ie */

	if(!exists(this.labels)) { this.addFormAndLabelData(id); }
	var fieldLabels = this.labels;
	for(var i=0;i<fieldLabels.length;i++) {
		if(fieldLabels[i].getAttribute('for')==id || fieldLabels[i].getAttribute('htmlFor')==id) {
			fieldLabels[i].setAttribute('class','error');
			fieldLabels[i].setAttribute('className','error'); /* for ie */
			this.addNotification("error",id,fieldLabels[i].innerHTML,whichCustom);
		}
	}
};
ValidationObj.prototype.removeError = function(id) {
	//console.log("removeError");
	get(id).setAttribute('class','');
	get(id).setAttribute('className',''); /* for ie */
	if(!exists(this.labels)) { this.addFormAndLabelData(); }
	var fieldLabels = this.labels;
	for(var i=0;i<fieldLabels.length;i++) {
		if(fieldLabels[i].getAttribute('for')==id || fieldLabels[i].getAttribute('htmlFor')==id) {
			fieldLabels[i].setAttribute('class','');
			fieldLabels[i].setAttribute('className',''); /* for ie */
		}
	}
	this.removeNotification(id);
};

/* data validation functions */
ValidationObj.prototype.validateSelectField = function(id) {
	//console.log("validateSelectField");
	if(get(id).selectedIndex==0) { this.markError(id); return false; }
	else { this.removeError(id); return true; }
};
ValidationObj.prototype.validateName = function(id) {
	//console.log("validateName");
	var t = get(id);
	if(t.value == "" || t.value.length < 2 || t.value.match(/^([a-zA-Z][a-zA-Z\&\-\'\s]*|)$/) == null ) { this.markError(id); return false; }
	else { this.removeError(id);return true; }
};
ValidationObj.prototype.validateFirstname = this.validateName; /* alias for itineraries app */
ValidationObj.prototype.validateLastname = this.validateName; /* alias for itineraries app */

ValidationObj.prototype.validatePassportNum = function(id) {
	//console.log("validatePassportNum");
	var t = get(id).value;
	if(!t.value.match(/^[a-z0-9]+$/i)) { this.markError(id); return false; }
	else { this.removeError(id); return true; }
};

/*D9208617 start added validateDate function */

ValidationObj.prototype.validateDate = function(id) {
	var t = get(id);
	t.value = t.value.replace(/\s*/g,"");
	if(!t.value.match(/^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/)) { this.markError(id); return false; }
	else { this.removeError(id);return true; }
};

/*D9208617 end added validateDate function */

ValidationObj.prototype.validateBirthDate = function(id) {
	//console.log("validateBirthDate");
	var custDate;
	var dayField_Id; var monthField_Id; var yearField_Id; 
	var dayField; var monthField; var yearField;
	if(id.match(/day/) != null) {
		dayField_Id = id;
		monthField_Id = id.replace(/day/,"month");
		yearField_Id = id.replace(/day/,"year");
	} else if(id.match(/month/) != null) {
		dayField_Id = id.replace(/month/,"day");
		monthField_Id = id;
		yearField_Id = id.replace(/month/,"year");
	} else if (id.match(/year/) != null) {
		dayField_Id = id.replace(/year/,"day");
		monthField_Id = id.replace(/year/,"month");
		yearField_Id = id;
	} else {}
	dayField = get(dayField_Id).value;
	monthField = this.getMonthNum(get(monthField_Id).value);
	yearField = get(yearField_Id).value;

	if(this.curField == yearField_Id || (this.dayField !="" && this.monthField != "" && this.yearField != "")) { 
		if( this.validateSelectField(dayField) 
		&& this.validateSelectField(monthField) 
		&& this.validateSelectField(id) ) {
			var custDate = new Date();
			custDate.setYear(get(id).value);
			custDate.setDate(get(dayField).value);
			custDate.setMonth(this.getMonthNum(get(monthField).value));
			if(this.today<custDate) { 
				this.markError(dayField_Id); 
				this.markError(monthField_Id);
				this.markError(yearField_Id);
				return false;
			} else { 
				this.removeError(dayField_Id); 
				this.removeError(monthField_Id);
				this.removeError(yearField_Id);
				return true;
			}
		}
		return this.validateSelectField(id);
	}
	return true;
};
ValidationObj.prototype.validateExpirationDate = function(id) {
	//console.log("validateExpirationDate");
	var custDate;
	var dayField_Id; var monthField_Id; var yearField_Id; 
	var dayField; var monthField; var yearField;
	var maxDays;
	if(id.match(/day/) != null) {
		dayField_Id = id;
		monthField_Id = id.replace(/day/,"month");
		yearField_Id = id.replace(/day/,"year");
	} else if(id.match(/month/) != null) {
		dayField_Id = id.replace(/month/,"day");
		monthField_Id = id;
		yearField_Id = id.replace(/month/,"year");
	} else if (id.match(/year/) != null) {
		dayField_Id = id.replace(/year/,"day");
		monthField_Id = id.replace(/year/,"month");
		yearField_Id = id;
	} else {}
	if(exists(get(dayField_Id))) { dayField = get(dayField_Id).value; }
	monthField = this.getMonthNum(get(monthField_Id).value);
	yearField = get(yearField_Id).value;
	maxDays = 32 - new Date(yearField,monthField, 32).getDate();

	if (exists(get(dayField_Id))) {
		if( this.validateSelectField(dayField_Id) 
		&& this.validateSelectField(monthField_Id) 
		&& this.validateSelectField(yearField_Id) ) {
			custDate = new Date(yearField,monthField,dayField);
			if(this.today>custDate) { 
				this.markError(dayField_Id);
				this.markError(monthField_Id);
				this.markError(yearField_Id);
				return false;
			}
			else { 
				this.removeError(dayField_Id);
				this.removeError(monthField_Id);
				this.removeError(yearField_Id);
				return true;
			}
		} else { /* not all date fields have selections */ }
	} else {
		if(this.curField == yearField_Id || (this.curField == monthField_Id && yearField != "")) { 
			if( this.validateSelectField(monthField_Id) 
			&& this.validateSelectField(yearField_Id) ) {
				custDate = new Date(get(id).value, this.getMonthNum(get(monthField_Id).value),maxDays);
				if(this.today>custDate) { 
					this.markError(monthField_Id);
					this.markError(yearField_Id);
					return false;
				} else { 
					this.removeError(monthField_Id);
					this.removeError(yearField_Id);
					return true;
				}
			}
		} else {
			return this.validateSelectField(monthField_Id);
		}
	}
	return this.validateSelectField(id);
};

// this will likely be migrated to an aliased function as it does not support validating the ccid
ValidationObj.prototype.validateCCExpDateMulti = function(monthId,yearId,i) {
	var theMonth = get(monthId).value;
	var theYear = get(yearId).value;
	var expLabel = "month_exp_pax" + i + "_req";
	//alert(theYear + " " + this.today.getFullYear() + " " + parseInt(theMonth, 10) + " " + (this.today.getMonth()+1));
	if (theMonth == "" || theYear == "") {
		this.markError(monthId);
		this.markError(yearId);
		this.markError(expLabel);
		return false;
	} else if ( ( theYear <= this.today.getFullYear() ) && ( parseInt(theMonth, 10) < this.today.getMonth()+1 ) ) {
		this.markError(monthId);
		this.markError(yearId);
		this.markError(expLabel);
		return false;
	} else {
		this.removeError(monthId);
		this.removeError(yearId);
		this.removeError(expLabel);
		return true;
	}
};


ValidationObj.prototype.validateCCExpDate = function(monthId,yearId,expLabel) {
	//console.log("validateCCExpDate");
	var theMonth = get(monthId).selectedIndex+1;
	var theYear = get(yearId).value;
	var expLabel = expLabel;
	//alert(theYear + " " + this.today.getFullYear() + " " + (theMonth) + " " + (this.today.getMonth()+1));
	if (theMonth == "" || theYear == "") {
		this.markError(monthId);
		this.markError(yearId);
		this.markError(expLabel);
		return false;
	} else if ( ( theYear <= this.today.getFullYear() ) && ((theMonth) < this.today.getMonth()+1 ) ) {
		this.markError(monthId);
		this.markError(yearId);
		this.markError(expLabel);
		return false;
	} else {
		this.removeError(monthId);
		this.removeError(yearId);
		this.removeError(expLabel);
		return true;
	}
};

ValidationObj.prototype.validateBoolean =function(id) {
	//console.log("validateBoolean");
	if(get(id).checked) {
		this.removeError(id); return true;
	} else {
		this.markError(id); return false;
	}
};

ValidationObj.prototype.validateGender = function(id) {
	//console.log("validateGender");
	if(get(id).value=="") { this.markError(id);return false; }
	else { this.removeError(id); return true; }
};
ValidationObj.prototype.validateRadioButton =function(id) {
	/* the ids are the same on radio inputs. needs more work or grouping. */
};

ValidationObj.prototype.validateGlobalPhone = function(reqPhoneObj) {
		
	var error = false;
	
	if(reqPhoneObj.phoneList.primaryPhone){
		if(!this.validatePhoneCC("primaryCountryCode")){
			error = true;
		}
		if(!this.validatePhoneArea("primaryAreaCode")){
			error = true;
		}
		if(!this.validatePhoneNumber("primaryNumber")){
			error = true;
		}
		if(reqPhoneObj.phoneList.primaryPhone.primExt != ""){
			if(!this.validatePhoneExt("primaryExt")){
				error = true;
			}
		}
	}
	
	if(reqPhoneObj.phoneList.alternatePhone){
		if(reqPhoneObj.phoneList.alternatePhone.altCC != ""){
			if(!this.validatePhoneCC("altCountryCode")){
				error = true;
			}
		}
		if(reqPhoneObj.phoneList.alternatePhone.altArea != ""){
			if(!this.validatePhoneArea("altAreaCode")){
				error = true;
			}
		}
		if(reqPhoneObj.phoneList.alternatePhone.altPhone != ""){
			if(!this.validatePhoneNumber("altNumber")){
				error = true;
			}
		}
		if(reqPhoneObj.phoneList.alternatePhone.altExt != ""){
			if(!this.validatePhoneExt("altExt")){
				error = true;
			}
		}
		
	}
	
	return error;
	
};


ValidationObj.prototype.validateGlobalAddress = function(reqAddrObj){

	var error = false;
	
	if(reqAddrObj.addrLine1StreetName) {
		if(!this.validateStreet("addr1")) {
			error = true;
		}
	}
	if(reqAddrObj.addrLine2RoomApartment) {
		if(!this.validateStreet("addr2")) { 
			error = true;
		}
	}
	if(reqAddrObj.cityCountyWard) {
		if(!this.validateCity("cityCountyWard")) { 
			error = true;
		}
	}
	if(reqAddrObj.stateProvCode) {
		if(!this.validateCity("stateProv")) {
			error = true;	
		}
	}	
	if(reqAddrObj.districtTownVillage) {
		if(!this.validateCity("districtTownVillage")) {
			error = true;	
		}
	}
	if(reqAddrObj.areaTerritoryPrefecture) {
		if(!this.validateStreet("areaTerritoryPrefecture")) {
			error = true;	
		}
	}
	if(reqAddrObj.postalCode) {
		if(!this.validatePostalCode("postal")) {
			error = true;	
		}
	}
	
	return error;		
};
/******* Global Phone Validation Methods ***************/
ValidationObj.prototype.validatePhoneNumber = function(id) {
	//console.log("validatePhoneNumber");
	var t = get(id);
	//t.value.replace("+","");
	//if(!t.value.match(/[\d\-\.]{10,}/)) { this.markError(id); return false; } 
	if(!t.value.match(/^[0-9- ]{7,20}$/))
	{ this.markError(id); return false; }
	else { this.removeError(id);return true; }
};
ValidationObj.prototype.validatePhoneCC = function(id){
	var t = get(id);
	if(t.value != "" && t.value.match(/[0-9\+]{1,10}/)) { this.removeError(id);return true;} 
	else { this.markError(id); return false; }
};
ValidationObj.prototype.validatePhoneArea = function(id){
	var t = get(id);
	if(t.value != "" && t.value.match(/[0-9]{3,5}/)) { this.removeError(id);return true; } 
	else { this.markError(id); return false; }
};
ValidationObj.prototype.validatePhoneExt = function(id){
	var t = get(id);
	if(t.value != "" && t.value.match(/[0-9\+]{0,5}/)) { this.removeError(id);return true; } 
	else { this.markError(id); return false; }
};


/******* Global Address Validation Methods ************/
ValidationObj.prototype.validateCity = function(id) {
	//console.log("validateCity");
	var t = get(id);
	if(t.value == "" || t.value.match(/[^-||\d||\w||\s]/)!=null) { this.markError(id); return false; } 
	else { this.removeError(id);return true; }
};
ValidationObj.prototype.validateStreet = function(id) {
	//console.log("validateStreet");
	var t = get(id);
	if(t.value == "" || t.value.match(/[^-||,||\d||\w||\s]\#/)!=null) { this.markError(id); return false; } 
	else { this.removeError(id); return true; }
};
ValidationObj.prototype.validatePostalCode = function(id) {
	//console.log("validateStreet");
	var t = get(id);
	if(t.value == "" || t.value.match(/[\d\w\-\s\.]{4,12}/)==null) { this.markError(id); return false; } 
	else { this.removeError(id); return true; }
};
ValidationObj.prototype.validateEmail = function(id) {
	//console.log("validateEmail");
	var t = get(id);
	if(t.value == "" || (t.value.match(/\w+@[a-zA-Z_]+?\.[a-zA-Z]{1}[a-zA-Z0-9]+/)==null) ) { this.markError(id); return false; }
	else { this.removeError(id); return true; }
};
ValidationObj.prototype.validateSMNum = function(id) {
	//console.log("validateSMNum");
	var t = get(id);
	if(this.isNumber(id)) {
		if(t.value == "" || t.value.match(/\d{10}/)==null) { this.markError(id); return false; }
		else { this.removeError(id); return true; }
	}
	return false;
};
ValidationObj.prototype.validatePinFormat = function(id) {
	//console.log("validatePinFormat");
	var t = get(id);
	if(this.isNumber(id)) {
		if(t.value.length!=4) { this.markError(id); return false; }
		else { this.removeError(id); return true; }
	}
	return false;
};
ValidationObj.prototype.validateCCID = function(id) {
	//console.log("validateCCID");
	var t = get(id);
	if(t.value.match(/[^\d]/) == null  && t.value.match(/\d{3,4}/) != null ) { 
		this.removeError(id); 
		return true; 
	} else { 
		this.markError(id); return false;
	}
};
ValidationObj.prototype.isCCNumMasked = function(ccNum, ccType) {
	ccNum = ccNum.replace(/^\s+/,"");
	switch(ccType) {
		case "AX": return ccNum.match(/^\*{11}\d{4}$/); // American Express: length 15
		case "VI":  // VI length 16
		case "CA": // CA: length 16
		case "DS": // Diners: length 16
		case "XS": // XS: length 16
		case "BB": // BB: length 16
		case "EC": // EC : length 16
		case "JC": // JC : length 16
		case "BF": // BF: length 16
		case "CG": // CG: length 16
		case "MD": // MD: length 16
		case "DL": // DL : length 16
			return ccNum.match(/^\*{12}\d{4}$/);
		case "TP": return ccNum.match(/^\*{11,12}\d{4}$/); // TP : length 16, 15
		case "ER": // ER : length 14
		case "DC": // Discover: length 14
		case "CB": // CB : length 14
			return ccNum.match(/^\*{10}\d{4}$/);
		default: return false;
	}
}
ValidationObj.prototype.validateCCNum = function(id, ccType) {
	//console.log("validateCCNum");
	var ccNum = get(id).value;
	if(ccNum === "") { this.markError(id); return false;}
	if(ccType == "AI" || ccType == "PA" || ccType == "UA") { ccType= "TP"; }
	if(ccType == "AT" || ccType == "TC") { ccType= "DC"; }
	if(ccType == "BR") { ccType= "DS"; }
	if(ccType == "CD") { ccType= "CA"; }
	if(this.isCCNumMasked(ccNum, ccType)) {
		this.removeError(id);
		return true;
	}
	ccNum = ccNum.replace(/\D/g, "");
	if (this.doesCCNumPassesLuhn(ccNum) ) {
		switch(ccType) {
			case "AX": if (ccNum.match(/^3[4,7]\d{13}$/)== null) { this.markError(id); return false;  } else { this.removeError(id); return true; }// American Express: length 15, prefix 34 or 37.
			case "VI": if (ccNum.match(/^4\d{15}$/) == null) { this.markError(id); return false;  } else { this.removeError(id); return true; } // VI length 16, prefix 4.
			case "CA": if (ccNum.match(/^5[1-5]\d{14}$/) == null) { this.markError(id); return false;  } else { this.removeError(id); return true; } // CA: length 16, prefix 51-55.
			case "DS":  if (ccNum.match(/^6[0,5]\d{14}$/) == null) { this.markError(id); return false;  } else { this.removeError(id); return true; } // Diners: length 16, prefix 60, 65
			case "DC": if (ccNum.match(/^3[0,6]\d{12}$/) == null) { this.markError(id); return false;  } else { this.removeError(id); return true; } // Discover: length 14, prefix 30, 36.
			case "CB": if (ccNum.match(/^3\d{13}$/) == null) { this.markError(id); return false;  } else { this.removeError(id); return true; } // CB : length 14, prefix 3
			case "TP": if (ccNum.match(/\d{15,16}$/) == null) { this.markError(id); return false; } else { this.removeError(id); return true; } // TP : length 16, no prefix
			case "XS": if (ccNum.match(/^5[1-5]\d{14}$/) == null) { this.markError(id); return false;  } else { this.removeError(id); return true; } // XS: length 16, prefix 51-55.
			case "BB": if (ccNum.match(/^4\d{15}$/) == null) { this.markError(id); return false;  } else { this.removeError(id); return true; } // BB: length 16, prefix 4.
			case "BF": if (ccNum.match(/^4\d{15}$/) == null) { this.markError(id); return false;  } else { this.removeError(id); return true; } // BF: length 16, prefix 4.
			case "CG": if (ccNum.match(/^4\d{15}$/) == null) { this.markError(id); return false;  } else { this.removeError(id); return true; } // CG: length 16, prefix 4.
			case "MD": if (ccNum.match(/^5[1-5]\d{14}$/) == null) { this.markError(id); return false;  } else { this.removeError(id); return true; } // MD: length 16, prefix 51-55.
			case "DL": if (ccNum.match(/^2006\d{12}$/) == null) { this.markError(id); return false;  } else { this.removeError(id); return true; } // DL : length 16, prefix 2006
			case "ER": if (ccNum.match(/\d{14}$/) == null) { this.markError(id); return false;  } else { this.removeError(id); return true; } // ER : length 14, no prefix
			case "EC": if (ccNum.match(/\d{16}$/) == null) { this.markError(id); return false;  }	else { this.removeError(id); return true; } // EC : length 16, no prefix
			case "JC": if (ccNum.match(/^3\d{15}$/) == null) { this.markError(id); return false;  } else { this.removeError(id); return true; } // JC : length 16, prefix 3
			default: this.removeError(id); return true;
		}
	} else {
		this.markError(id); return false;
	}
};
ValidationObj.prototype.validateCreditCard = function(id) {
	//console.log("validateCreditCard "+ id);
	var rtn = false;
	var valType;
	var ccType_Id; var ccNum_Id; var ccCCID_Id; // field ids
	var ccType; var ccNum; var ccCCID; // field values
	if(id.match(/num/) != null || id.match(/ccid/) != null || id.match(/type/) != null) {
		if(id.match(/type/) != null) {
			valType = "type";
			ccType_Id = id;
			ccCCID_Id = id.replace(/type/,"ccid");
			ccNum_Id = id.replace(/type/,"num");
		} else if(id.match(/num/) != null) { //if the id is for the cc number
			valType = "num";
			ccNum_Id = id;
			ccType_Id = id.replace(/num/,"type");
			ccCCID_Id = id.replace(/num/,"ccid");
		} else if (id.match(/ccid/) != null) { // else the id is for the ccid
			valType = "ccid";
			ccType_Id = id.replace(/ccid/,"type") + "_req";
			ccNum_Id = id.replace(/ccid/,"num") + "_req";
		} else {}
		// the assumption is that the credit card number is provided with the above naming
		// conventions, the field exists that provides the credit card type
		ccType = get(ccType_Id).options[parseInt(get(ccType_Id).selectedIndex)].value;
		ccNum = get(ccNum_Id).value;
		switch(valType) {
			case "type":
				if(ccType != "" && ccNum != "") { 
					rtn = this.validateCCNum(ccNum_Id, ccType);
					if(rtn) { 
						this.removeError(ccType_Id);
						this.removeError(ccNum_Id);
						return rtn;
					} else {
					}
				} else if (ccType == "" && ccNum != "") { 
					this.markError(ccType_Id);
					return false;
				} else {
				}
				break;
			case "num":
				if(ccType != "" && ccNum != "") { 
					rtn = this.validateCCNum(ccNum_Id, ccType);
					if(rtn) { 
						this.removeError(ccType_Id);
						this.removeError(ccNum_Id);
						return rtn;
					}
				} else if (ccType != "" && ccNum == "") { 
					this.markError(ccType_Id);
					this.markError(ccNum_Id);
					return false;
				} else {}
				break;
			case "ccid":
				if(this.curField == id  && exists(get(ccCCID_Id))) {
					if(this.requiresCCID(ccType)) { 
						return this.validateCCID(id);
					} else {
						return this.isNumber(id);
					}
				}
				break;
			default:
				break;
		}
	}  else { 
		//console.log("the field id "+ id +" does not contain num, ccid, or type");
		return false;
	}
};
ValidationObj.prototype.validateETicketNum = function(id) {
	//console.log("validateETicketNum");
	var t = get(id);
	t.value = this.removeSpaces(t.value);
	
//	if(
//		t.value = t.value.replace(/\s*/g,"");
//		if(t.value != ""&&t.value.match(/^006\d{10}$/)) { get('eTicketNumLabel').innerHTML = '&nbsp;eTicket #'; return true; }
//			 if(t.value != ""&&t.value.match(/\d{10}$/)) { get('eTicketNumLabel').innerHTML = '&nbsp;eTicket #'; return true; }
//	}
//	get('eTicketNumLabel').innerHTML = '<img src="/images/icons/error_x.gif" width="19" height="19" alt="" border="0" align="absmiddle" /> <span class="cpyError">eTicket #</span>';
//	showDiv('validationFormError');
//	get('validationFormError').innerHTML = '<p class="cpyError" style="padding-top:5px;padding-bottom:5px;"><img src="/images/icons/error_x.gif" width="19" height="19" alt="" border="0" align="absmiddle" />You have entered invalid information in one or more fields below.</p>';
//	return false;
};
ValidationObj.prototype.validateRedressNumber = function(id) {
	//console.log("validateETicketNum");
	var t = get(id);
	t.value = this.removeSpaces(t.value);
	t.value = this.stripBadChars(t.value);
	if(t.value.length > 0 && t.value.length < 14 && t.value.match(/^[a-z0-9]+$/i)){
		this.removeError(id); return true; 
	} else { 
		this.markError(id); return false; 
	}
};
ValidationObj.prototype.validateSecureName = function(id) {
	var t = get(id);
	if(t.value.match(/^[a-z]+[a-z\'\-\s]+$/i)){
		this.removeError(id); return true; 
	} else { 
		this.markError(id); return false; 
	}
}

/*

ValidationObj.prototype.validateFields = function(fieldArray) {
	//console.log("validateFields");
	var submitForm = true;
	submitForm = true;
	for(i=0;i<fieldArray.length;i++){
		var tempProp = fieldArray[i].toString();
		var tempArray = tempProp.split(',');
		for(j=0;j<tempArray.length;j++){
			if(tempArray[j + 1] == "CCType"){
				var tempString = this.validateCCType(tempArray[j], tempArray[j+2]);
				if(!tempString){ submitForm = false; }
			} else if(tempArray[j+1]) {
				var tempString = this.validateField(tempArray[j], tempArray[j+1]);
				if(!tempString){ submitForm = false; }
			} else {}
		}	
	}
	if(submitForm){ formName.submit(); }
}

/*
	match two values
	get ie working.
*/

ValidationObj.prototype.validateField = function(id, type) { 
	//console.log("validateField "+id+", data type of "+type);
	var validationType = type;
	if(validationType=="day"||validationType=="month"|| validationType=="year") { validationType = id.split("_")[1]; }
	else if(validationType=="genderm"||validationType=="genderf") { validationType = "gender"; }
	else if(validationType=="booleant"||validationType=="booleanf") { validationType = "boolean"; }
	else if(validationType=="fname"||validationType=="lname") { validationType = "name"; }
	else if(validationType=="ETicketNum") {validationType = "eticket"; }
	else { /* doNothing() */ }
	if(exists(id)) {
		switch(validationType.toLowerCase()) {
			// name, cc, day, month, year, gender, passport 
			case "name": get(id).value = this.stripBadChars(get(id).value);return this.validateName(id);
			case "cc": if(get(id).type == "text" || get(id).type == "textarea" ) { get(id).value = this.stripBadChars(get(id).value); } return this.validateCreditCard(id);
			case "gender": return this.validateGender(id);
			case "boolean": return this.validateBoolean(id); 
			case "passport": get(id).value = this.stripBadChars(get(id).value);return this.validatePassportNum(id);
			case "birth": return this.validateBirthDate(id);
			case "exp": return this.validateExpirationDate(id);
			case "num": get(id).value = this.stripBadChars(get(id).value);return this.isNumber(id);
			case "pin": return this.validatePinFormat(id);
			case "country": return this.validateSelectField(id);
			case "state":  return this.validateSelectField(id);
			case "phone":  get(id).value = this.stripBadChars(get(id).value);return this.validatePhoneNumber(id);
			case "city":  get(id).value = this.stripBadChars(get(id).value);return this.validateCity(id);
			case "street":  get(id).value = this.stripBadChars(get(id).value);return this.validateStreet(id);
			case "freeform": get(id).value = this.stripBadChars(get(id).value);return true; /* update if needed */
			case "validateRadioButton": return this.validateRadioButton(id); /* function needs writing */
			case "mmslashddslashyyyydate": return this.isDataMMSlashDDSlashYYYY(id) ;
			case "email": return this.validateEmail(id);
			case "smnum": return this.validateSMNum(id);
			case "eticket": return this.validateETicketNum(id); break;
			//case "PINNum": return this.validatePINNum(id); break;
			//case "ConfirmNum": return this.validateConfirmNum(id); break;
			default: return true;
		}
	}
};
ValidationObj.prototype.validateForm = function(id) { /* validates that all fields with data are correct */
	//console.log("validateForm");
	var oForm = document.forms[id];
	for(var i=0;i<oForm.length;i++) {
		if(!this.validateField(oForm[i].id,oForm[i].id.split("_")[0])) { 
			//console.log(oForm[i].id + " failed to validate as datatype "+ oForm[i].id.split("_")[0]);
			return false; 
		}
	}
	return true;
};
ValidationObj.prototype.checkForm = function(id) {
	//console.log("checkForm");
	this.curField = id;
	var rtn = true;
	var parentFormId = this.findParentForm(id);
	var oForm = document.forms[parentFormId];
	for(var i=0;i<oForm.length;i++) {
		if(oForm.elements[i].id.match(/_req/)) { /* check if field is required */
			switch(oForm.elements[i].type) {
				case "text":  if(oForm[i].value=="") { rtn=false; }; break; /* catches only empty fields without a value */
				case "textarea":  if(oForm[i].value=="") { rtn=false; }; break;  /* catches only empty fields without a value */
				case "select-one": if(oForm[i].selectedIndex==0) { rtn=false; }; break; /* catches if left at index of 0 */
				//case "select-multiple": if(oForm[i].selectedIndex==0) { rtn=false; }; break;  /* catches if left at index of 0 */
				case "radio": if(!oForm[i].checked) { rtn=false; }; break;
				case "checkbox": if(!oForm[i].checked) { rtn=false; }; break;
				case "password": break;
				case "hidden": if(oForm[i].value=="") { rtn=false; }; break;
				default: break;
			}
		} else { /* handle non-required fields */
			switch(oForm.elements[i].type) {
				case "text":  if(oForm[i].value=="") { rtn=true; } else; break; /* catches only empty fields without a value */
				case "textarea":  if(oForm[i].value=="") { rtn=true; }; break;  /* catches only empty fields without a value */
				case "select-one": if(oForm[i].selectedIndex==0) { rtn=true; }; break; /* catches if left at index of 0 */
				//case "select-multiple": if(oForm[i].selectedIndex==0) { rtn=false; }; break;  /* catches if left at index of 0 */
				case "radio": if(!oForm[i].checked) { rtn=true; }; break;
				case "checkbox": if(!oForm[i].checked) { rtn=true; }; break;
				case "password": break;
				case "hidden": if(oForm[i].value=="") { rtn=true; }; break;
				default: break;
			}
			if(oForm.elements[i].id.match(/replicate/)) {
				/* put code here to copy fields from one to another */
			}
		}
		if(!rtn) { break; }
	}
	if(!rtn) {
		this.validateField(id,id.split("_")[0]);
	} else {
		if(this.validateForm(parentFormId)) { this.enableForm(parentFormId); /*this.submitForm(parentFormId);*/}
	}
	return rtn;
};

ValidationObj.prototype.enableForm = function(id) {
	//console.log("enableForm");
	var oForms = document.forms;
	for(var i=0;i<oForms.length;i++) {
		if(exists(oForms[i].id) && oForms[i].id == id) {
			for(var j=0;j<oForms[i].length;j++) {
				if(oForms[i][j].type=="submit" && oForms[i][j].value != "Start Over") { 
					oForms[i][j].disabled="";
					setClassName(oForms[i][j].id,getClassName(oForms[i][j].id).split("_")[0]);
					oForms[i].action = this.getProp(id+"_action");
					return true;
				}
			}
		}
	}
};
ValidationObj.prototype.submitForm = function(id) {
	//console.log("submitForm");
	var oForm = document.forms[id];
	oForm.submit();
};

/* .init() disables the continue button and adds "handleField()" as the onchange handler */
ValidationObj.prototype.init = function() { 
	//console.log("init");
	var hasButton = false;
	this.addFormAndLabelData();
	var oForms = document.forms;
	if (exists(this.getProp("disable")) && this.isDisabled("init")) { return; }
	for(var i=0;i<oForms.length;i++) {
		hasButton = false;
		if(exists(oForms[i]) && exists(oForms[i].id) && oForms[i].id !="") { 
			for(var j=0;j<oForms[i].length;j++) {
				if(exists(oForms[i][j].id) && oForms[i][j].type=="submit" && oForms[i][j].value != "Start Over" && oForms[i][j].value != "Back") { 
					/* if the desire is to not disable buttons for form submissions */
					if (!this.isDisabled("disabled_buttons")) {
						oForms[i][j].disabled="disabled";
						setClassName(oForms[i][j].id,getClassName(oForms[i][j].id)+"_disabled");
						hasButton = true;
					}
				} else { 
					oForms[i][j].onchange = handleField;
				}
			}
			if(hasButton) { /* in order to properly disable the buttons we remove the form action as well */
				this.setProp(oForms[i].id+"_action",oForms[i].action);
				oForms[i].action = "";
			}
		}
	}
};

// create instance of Object
var valObj = new ValidationObj();


// inline handlers for events and initialization
function handleField() { 
	//console.log("handleField: " + this.id);
	valObj.checkForm(this.id);
};
function addClientSideValidation() { 
	//console.log("addClientSideValidation");
	valObj.init();
};

// add form processing to page on load
//addEvent(window,"load",addClientSideValidation,false);




function syncFields(id) { 
	var code = document.getElementById("ssrCode_"+id);
	var text = document.getElementById("ssrDisplay_"+id);
	text.value = "";
	if (-1 != code.value.indexOf("DEAF")) text.value += "Deaf, ";
	if (-1 != code.value.indexOf("BLND")) text.value += "Blind, ";
	if (-1 != code.value.indexOf("WCHS") ||
		-1 != code.value.indexOf("WCHR") ||
		-1 != code.value.indexOf("WCHC")) text.value += "Wheelchair, ";
	if (-1 != code.value.indexOf("AVML")) text.value += "Asian Vegetarian Meal, ";
	else if (-1 != code.value.indexOf("BBML")) text.value += "Baby Meal, ";
	else if (-1 != code.value.indexOf("BLML")) text.value += "Bland Meal, ";
	else if (-1 != code.value.indexOf("CHML")) text.value += "Child Meal, ";
	else if (-1 != code.value.indexOf("DBML")) text.value += "Diabetic Meal, ";
	else if (-1 != code.value.indexOf("GFML")) text.value += "Gluten Free Meal, ";
	else if (-1 != code.value.indexOf("KSML")) text.value += "Kosher Meal, ";
	else if (-1 != code.value.indexOf("LSML")) text.value += "Low Sodium Meal, ";
	else if (-1 != code.value.indexOf("MOML")) text.value += "Muslim Meal, ";
	else if (-1 != code.value.indexOf("SFML")) text.value += "Seafood Meal, ";
	else if (-1 != code.value.indexOf("VGML")) text.value += "Vegetarian Meal, ";

	if (text.value.length >4){  // Remove trailing ", "
		text.value = text.value.substring(0, text.value.length-2);
	}
	var displayText = document.getElementById("disp_ssrDisplay_"+id);
	displayText.innerHTML = text.value;
}
function submitForm(code) {
	codesArray.push(code);
}
function updateSSRs(dummy) {
	dummy=null;
	if (codesArray.length > 0) {
		var code = codesArray.pop();
		var spinner = document.getElementById("spinner"+code.substring("SSRForwarder".length));
		if (document.getElementById(code) != null 
		 && document.getElementById(code).contentWindow.document.forms[0] != null)
			document.getElementById(code).contentWindow.document.forms[0].submit();
		if (spinner != null) 
			spinner.style.display="none";
	}
}
function submitForms() {
	if (codesArray.length == 0) {
		var iframes = document.getElementsByTagName('iframe');
		for(var i=0;i<iframes.length;i++) {
			codesArray.push(iframes[i].id);
		}
	}
	updateSSRs("kickitoff");
}
var codesArray = new Array();

var secureFlightsObj = {
	errorText:'You must review the Passenger Information Verification statement and check the checkbox to update your Secure Flight Passenger Data.',
	formObj:null,
	errorsObj:null,
	formAction:"",
	formRequiredCheck:null,
	paxCount:null,
	formValidation:null,
	isValidationInit:false,
	formButton:null,
			
	init:function(passengerCount){
		if(passengerCount != null){
			this.paxCount = parseInt(passengerCount);
		} else {
			this.paxCount = get('totalPax').value;
		}
		this.formObj = get('secure_flight_form');
		this.errorsObj = get('alerts_errors');
		this.formAction = this.formObj.action != "" ? this.formObj.action : this.formAction;
		this.formObj.action = "javascript:void[0]";
		addEvent(this.formObj, 'keypress', this.voidEnterSubmit, false);
		this.formRequiredCheck = get('user_agreement_req');
		this.enableFormButton();
	},
	enableFormButton:function(){
		if(this.formButton == null){
			this.formButton = get('secure_form_submit');
		}
		var showFormButton = secureFlightsObj.formRequiredCheck.checked ? true : false;
		
		if (showFormButton){
			return true;
		} else {
			return false;
		}
		
	},
	voidEnterSubmit:function(e){
		var checkForm = secureFlightsObj.enableFormButton();
		var key;

		if(window.event){
			key = window.event.keyCode;     //IE
		} else {
			key = e.which;     //firefox
		}
		if(key != 13){
			return;
		}
		if(key == 13 && checkForm != true){
			return false;
		} else {
			return true;			
		}
	},
	formValidation:function(){
		
		var checkForm = secureFlightsObj.enableFormButton();

		if(!checkForm){
			var customMsg = '<div class="error">' + this.errorText + '</div>';
			this.errorsObj.innerHTML += customMsg;
			try{
				get('req_check_label').className = "error";
			} catch(e){
				get('user_agreement_req_l').className = "error";
			}
			return false;
		} else {
			try{
				get('req_check_label').className = "";
			} catch(e){
				try{
					get('user_agreement_req_l').className = "";
				} catch(e){
					get('user_agreement_req').className = "";
				}
			}
		}
		try{
			this.errorsObj.innerHTML = "";
		} catch(e){
			this.init();
			this.errorsObj.innerHTML = "";
		}
		var j = 1;
		if(this.paxCount == 1){
			var middleName = get('mname_paxMiddleName[1]');
			if(middleName.value != ''){
				secureFlightsValObj.validateSecureName('mname_paxMiddleName[1]');
			}
			var redressNumber = get('paxRedressNo[1]');
			if(redressNumber.value != ''){
				secureFlightsValObj.validateRedressNumber('paxRedressNo[1]');
			}
			secureFlightsValObj.validateSecureName('fname_paxFirstName[1]_req');
			secureFlightsValObj.validateSecureName('lname_paxLastName[1]_req');
			secureFlightsValObj.validateSelectField('gender_pax[1]_req');
			secureFlightsValObj.validateSelectField('day_birth_pax[1]_req');
			secureFlightsValObj.validateSelectField('month_birth_pax[1]_req');
			secureFlightsValObj.isNumber('year_birth_pax[1]_req', '4');

		} else {

			while(j < this.paxCount + 1){
				var middleName = get('mname_paxMiddleName[' + j + ']');
				if(middleName.value != ''){
					//secureFlightsValObj.removeSpaces(middleName.value);
					secureFlightsValObj.validateSecureName('mname_paxMiddleName[' + j + ']');
				}
				var redressNumber = get('paxRedressNo[' + j + ']');
				if(redressNumber.value != ''){
					//secureFlightsValObj.removeSpaces(redressNumber.value);
					secureFlightsValObj.validateRedressNumber('paxRedressNo[' + j + ']');
				}
				secureFlightsValObj.validateSecureName('fname_paxFirstName[' + j + ']_req');
				secureFlightsValObj.validateSecureName('lname_paxLastName[' + j + ']_req');
				secureFlightsValObj.validateSelectField('gender_pax[' + j + ']_req');
				secureFlightsValObj.validateSelectField('day_birth_pax[' + j + ']_req');
				secureFlightsValObj.validateSelectField('month_birth_pax[' + j + ']_req');
				secureFlightsValObj.isNumber('year_birth_pax[' + j + ']_req', '4');
	
				j++
			}
		}
		
		var errorsPresent = this.errorsObj.getElementsByTagName('div');
		errorsPresent = parseInt(errorsPresent.length);
			
		if (errorsPresent > 0) {
			return false;
		} else {
			hide('secure_flight-content');
			var waitMsgText = '<h1>Please wait while we update your passenger information...</h1>'
			get('waitMsg').innerHTML = waitMsgText;
			show('waitMsg');
			this.formObj.action = this.formAction;
			return true;
		}
		
	}	

};
<!-- mp_trans_urljs_disable_end -->


/* changeflights.jsp */

function scheduleSearchVal(form){
var flag = 0;
var form = form;
var isComplete = true;
var formComplete = true;
for (var i = 0; i< 6; i++) {
	if(get('flight_select_' + i).checked){
	flag ++;
	}
}
	if (flag == 0) {
	valObj.addNotification('error','flight_select_0','', 'selectSearch');
	formComplete = false;
	} else {valObj.removeNotification('flight_select_0');}
var schedSearchArray = document.getElementsByTagName('input');
	for (var i=0; i < schedSearchArray.length;i++){
		if (schedSearchArray[i].type.match('checkbox')) {
			var schedSearchObject = schedSearchArray[i].id;
			if(schedSearchObject.match('flight_select')){
			var tempChecked = true;
					var tempTargetFlight = schedSearchObject.split("_");
					var tempFlightNumber = tempTargetFlight[2];
					var tempDepCity = 'dep_city_' + tempFlightNumber;
					var tempDestCity = 'dest_city_' + tempFlightNumber;
					var tempDepDate = 'dep_date_' + tempFlightNumber;
					var tempDepCityData = get(tempDepCity).value ;
					var tempDestCityData = get(tempDestCity).value ;
				if (schedSearchArray[i].checked == true) {
					
					if (!valObj.validateCity(tempDepCity)) { formComplete = false; }
					if (!valObj.validateCity(tempDestCity)) { formComplete = false; }
					if ((tempDepCityData) == (tempDestCityData) && (tempDepCityData && tempDestCityData !="")){
						formComplete = false;
						valObj.addNotification('error', tempDepCity, '', 'duplicateCity');
						valObj.markError(tempDepCity);
						valObj.markError(tempDestCity);
						hide(tempDestCity + "_e");
					} 
					if (!valObj.validateDate(tempDepDate)) { formComplete = false; }
					
				}  else {
					valObj.removeError(tempDepCity);
					valObj.removeError(tempDestCity);
					valObj.removeError(tempDepDate);
				}
					if(!formComplete) {
					isComplete = false;
					} 
			}
			
		}
	}
	return isComplete;
};


function addFlightsDisplay (currentId, dispId, targetId){
	if(currentId == "add_flights_button"){
		show(dispId);
		hide(currentId);
		show(targetId);
	} else {
		hide(dispId);
		show(targetId);
		hide(currentId);
		self.scrollTo(0,0);
	}
};

function autoCheckSearch(id, targetId){
	var targetNum = id.split("_")[2];
	var targetCheckbox = targetId + targetNum;
	if(exists(targetCheckbox)){
	get(targetCheckbox).checked = 'true';
	}

};

/* city_detail_dwr.js */
/******* Begin booking/javascripts/dwr/dity_detail_dwr.js ***********/

var cities = new Array();
function hideCityDetail(){
	var dtlBox = document.getElementById('cityDetails');
	if (dtlBox != null) {
		setInnerHTML('cityDetails', '');
		dtlBox.style.display = 'none';
	}
}
function showCityDetail(e, cityCode){
	var cursor = getPosition(e);
	var dtlBox = document.getElementById('cityDetails');
	if (dtlBox != null) {
		setInnerHTML('cityDetails', 'Getting City Info...');
		dtlBox.style.position = "absolute";
		dtlBox.style.left  = cursor.x + "px";
		dtlBox.style.top   = cursor.y + "px";
		dtlBox.style.display = 'block';
		getCity(cityCode);
	}
}

function getCity(cityCode){
	var city = eval('cities["' + cityCode + '"]');
	if (city != null) { updateCity(city); } 
	else { 
		showLoading = false;
		CityCache.getCityByAirportCode(cityCode, addCity);
		showLoading = true;
	}
}
function addCity(city){
	cities[city.airportCode] = city;
	cities[city.cityName] = city;
	updateCity(city);
}
function updateCity(city){
	if (city != null) {
		var dtlBox = document.getElementById('cityDetails');
		if (dtlBox != null) {
			var airportCode = city.airportCode;
			var cityName = city.cityName;
			var airportName = ''; 
			if (city.airportName != null) { airportName = city.airportName; } 
			if (city.region != null) { cityName = cityName + ', ' + city.region; } 
			if (city.countryCode != null) { cityName = cityName + ', ' + city.countryCode; }
			//setInnerHTML('ctDetailCityCode', airportCode);
			var text = cityName;
			if (airportName != null && airportName != '') { text = text + ' - ' + airportName; }
			setInnerHTML('cityDetails', text);
		}
	}
}
function fltSummary(event, fltNum, depCiy, arrCity, stops, duration, depMonth, depDay, depTm, arrMonth, arrDay, arrTm) {
	var text = '<div class="leftside_label">' + fltNum + ':<br />';
	text += 'Departs:<br />';
	text += 'Arrives:<br />';
	text += 'Flight Duration:';
	if (stops != null && stops != '0' && stops != 'null') {
		text += '<br />Stops:';   
	}
	text += '</div>'; 
	text += '<div class="rightside_label">' + depCiy + ' to '  + arrCity + '<br />';
	text += depMonth + '  ' +  depDay + ', ' + depTm + '<br />';
	text += arrMonth + '  ' +  arrDay + ', ' + arrTm + '<br />';
	text += formatFlightDuration(duration);
	if (stops != null && stops != '0' && stops != 'null') {
		text += '<br />' + getFlightStopsText(stops);   
	}
	text += '</div>'
	showMessage(event, text);      
}
function getFlightStopsText(stops){
	if (stops == '0') { return 'Nonstop'; } 
	else if (stops == '1') { return '1-stop'; } 
	else { return 'Multi-stop'; }
}

function formatFlightDuration(dur) {
	if (dur.length == 4) {
		try {
			th = dur.substr(0,2);
			tm = dur.substr(2,2);
			if (th.substr(0,1) == 0) { th = th.substr(1,1); } 
			if (tm.substr(0,1) == 0) { tm = tm.substr(1,1); } 
			h = parseInt(th);
			m = parseInt(tm);
			f = "";
			if(h > 0 && m > 0) { f = h+" hr "+m+" min"; }
			else if (h > 0) { f = h+" hr"; } 
			else if (m > 0) { f = m+" min"; }
		} catch (e) { f = dur; }
		return f;
	} else {
		return dur;
	}
}
function showCurrencyToolTip(event)
{
	var cursor = getPosition(event);
	var oDiv = document.getElementById("currencyToolTip");
	oDiv.style.display='block';
	oDiv.style.position = "absolute";
	oDiv.style.left = cursor.x + 'px';
	oDiv.style.top = cursor.y + 'px';
}
function hideCurrencyToolTip(event) { get("currencyToolTip").style.display='none'; }

/******* End booking/javascripts/dwr/dity_detail_dwr.js ***********/

/* populateNTRSummary.js, removed for merchandising isolation */
/* pitinsDWR.js */
/******* Begin booking/javascripts/dwr/pitins/pitinsDWR.js ***********/

DWREngine.setErrorHandler(handleError);
var shopping_pollCount = 0;
var shopping_tid;
var nonAjax_tid;
var shoppingLoaded = false;
var shoppingtimeout_tid;

function refreshShoppingTimeout() {
	try{
		clearInterval(shoppingtimeout_tid);
		shoppingtimeout_tid = setInterval("shoppingTimeout()", 1500000);
	} catch (e) {}
}

function shoppingTimeout() {
	timeoutURL = startOver + '&alerts=100526';
	if( timeoutURL != null ) {
		window.location.replace(timeoutURL);
	}
}

function handleError() {
	hideLoadingMsg();
	if( url != null ) {
		window.location.replace(url);
	}
}
function handlePollError() {
	//Call timeout just in 6 secs
	nonAjax_tid = setInterval("callNonAjaxRetrieve()", 5000);
}
function callNonAjaxRetrieve() {
	clearInterval(nonAjax_tid);
	if (retrieveFlightsUrl != null) {
		window.location.replace(retrieveFlightsUrl);
	}
}
function startShoppingPoll() {
	if( !shoppingLoaded ) {
		shoppingLoaded = true;
		hide('pitins_content');
		show('wait');
		shopping_tid = setInterval( "poll()", 100 );
		//Call timeout in 25 secs as backup if DWR poll fails
		nonAjax_tid = setInterval("callNonAjaxRetrieve()", 25000);
	}
}
function smloginRefresh() {
	if( !shoppingLoaded ) {
		shoppingLoaded = true;
		FromScreenProcessor.retrieveFlights(hiddenFieldsId, checksum, cacheKey, currentSegment, lastSelectedSegmentId, -1, sortByColumn, null, displayShoppingScreen);
	}
}
function poll() {
	try {
		clearInterval(shopping_tid);
		shopping_pollCount = shopping_pollCount +1;
		FromScreenProcessor.isPricingDone(hiddenFieldsId, checksum, tSessionId, shopping_pollCount, {callback:processPoll,
                                                                                                      errorHandler:handlePollError,
                                                                                                      timeout:25000
                                                                                                      });
	} catch (e) {
		handlePollError();
	}
}
function processPoll(data) {
	try {
		if( data.redirectURL != null ) {
			if( data.redirectURL == 'poll' ) {
				if( shopping_pollCount < 15 ) {
					shopping_tid = setInterval( "poll()", 500 );
				} else if( shopping_pollCount < 25 ) {
					shopping_tid = setInterval( "poll()", 1000 );
				} else {
					shopping_tid = setInterval( "poll()", 3000 );
				}
				return;
			} else {
				window.location.replace(data.redirectURL);
				return;
			}
		}
		displayShoppingScreen(data);
		clearInterval(nonAjax_tid);
	} catch (e) {
		handlePollError();
	}
}

function selectFlight(legNbr, selectedSegmentId, itinSequenceNbr) {
	try {
		setLoadingMsg('Retrieving Flights');
		retrieveFlights(legNbr, selectedSegmentId, itinSequenceNbr);
	} catch (e) {
		handleError();
	}
}

function getFlights(legNbr) {
	try {
		setLoadingMsg('Retrieving Flights');
		retrieveFlights(legNbr, null, -1);
	} catch (e) {
		handleError();
	}
}

function filterFlights() {
	try {
		setLoadingMsg('Filtering Flights');
		updateFlights(currentSegment, sortByColumn)
	} catch (e) {
		handleError();
	}
}

function goBack() {
	if( currentSegment == 0 ) {
		history.go(-1);
	} else {
		getFlights(currentSegment-1);
	}
}

function showLowest() {
	resetAllFilters();
	sortFlights(6);
}

function sortFlights(sortColumn) {
	setLoadingMsg('Sorting Flights');
	updateFlights(currentSegment, sortColumn);
}                

function updateFlights(legNbr, sortColumn) {
	var stopFilter = getFilter('stops');
	var depArptFilter = null;
	var arrArptFilter = null;
	if( hasFilters ) {
		if( hasDepAirportsFilter ) {
			depArptFilter = getFilter('depAirports');
		}
		if( hasArrAirportsFilter ) {
			arrArptFilter = getFilter('arrAirports');
		}
	}
	FromScreenProcessor.updateFlights(hiddenFieldsId, checksum, cacheKey, legNbr, sortColumn, stopFilter, depArptFilter, arrArptFilter, processResponse);
	url = getURL('updatePricedItineraries', legNbr, null, sortColumn, stopFilter, depArptFilter, arrArptFilter);
}

function retrieveFlights(legNbr, selectedSegmentId, itinSequnceNbr) {
	var stopFilter = getFilter('stops');
	FromScreenProcessor.retrieveFlights(hiddenFieldsId, checksum, cacheKey, legNbr, selectedSegmentId, itinSequnceNbr, sortByColumn, stopFilter, processResponse);
	lastSelectedSegmentId =  selectedSegmentId;
	url = getURL('retrievePricedItineraries', legNbr, selectedSegmentId, sortByColumn, stopFilter, null, null);
	var  dashURL = getURL('smloginRefresh', legNbr, selectedSegmentId, sortByColumn, stopFilter, null, null);
	setDashboardURL(dashURL);
}


var upsellCallinProgress = false;
var ignoreUpsellResponse = false;
var upsellCount = 1;
function priceFirstClass(upsellhiddenFieldsId, upsellchecksum, upsellcacheKey) {
        showLoading = false;
   upsellExists = false;
   if (!upsellCallinProgress
             && upsellCount < 4) {
      upsellCallinProgress = true;
      upsellCount = upsellCount +1;
      try {
              FromScreenProcessor.priceFirstClass(upsellhiddenFieldsId, upsellchecksum, upsellcacheKey,
                                                               {callback:processUpsellResponse,
                                                                errorHandler:handleUpsellError,
                                                                timeout:120000});
      } catch (e) {
         handleUpsellError();
      }
   } else {
     ignoreUpsellResponse = true;
   }
   showLoading = true;
}


function selectFirstClassItin(firstClassPriceSelected) {
  try {
   FromScreenProcessor.selectFirstClassItin(hiddenFieldsId, checksum, cacheKey, firstClassPriceSelected, 
                                            {callback:processSelectUpsellResponse,
                                                          errorHandler:handleUpsellError,
                                                          timeout:30000});
  } catch (e) { 
    handleUpsellError();
  }
}

function setDashboardURL(dashURL) {
	try {
		//Set page refresh value for dashboard login
		if( document.smlogin_login && document.smlogin_login.refreshURL ) {
			DWRUtil.setValue('refreshURL', dashURL);
		}
   } catch (e) { }
}

function getURL(dispatchMethod, legNbr, selectedSegmentId, sortColumn, stopFilter, depArptFilter, arrArptFilter) {
	var url = '/booking/pricedItineraries.do?dispatchMethod=' + dispatchMethod
				+ '&hiddenFieldsId=' + hiddenFieldsId + '&checksum=' + checksum
				+ '&cacheKey=' + cacheKey
				+ '&selectedLeg=' + legNbr
				+ '&selectedSegmentId=' + selectedSegmentId
				+ '&sortBy=' + sortColumn
				+ '&stopsFilter=' + stopFilter
				+ '&deptAirportFilter=' + depArptFilter
				+ '&arrAirportFilter=' +  arrArptFilter;
	return url;
}

function displayShoppingScreen(data) {
	try {
		initStopsFilter(data);
		setLowestFareBadges(data);
		setAdvisoryMessages(data);
		processResponse(data);
		reInitSegmentData(data);
		resetPWM();
		hide('wait');
		show('pitins_content');
		show('pitins_footer');
		window.location.replace('#top');
	} catch (e) {
		handlePollError();
	}
}

function processResponse(data) {
	var goTop =false;
	try {
		if( data.redirectURL != null ) {
			window.location.replace(data.redirectURL);
			return;
		}
		if( data.reviewItinScreen ) {
         try {
            if (!data.upsellRefresh) {
               hideUpsellChoice();
               if (data.itinDWR.upsellEligible) {
                  priceFirstClass(hiddenFieldsId, checksum, cacheKey);
               }
            }
         } catch (e) {
            //alert(e);
         }

			displayReviewItinData(data);
			show('merchandisingMessage');
			show('booking_fees');
			show('merchandisingContent');
			show('returnTopBackButton');
			show('flightSummary');
			hide('returnBottomBackButton');
			hide('outboundTopBackButton');
			hide('outboundBottomBackButton');
			show('continueButton');
		} else {
			displaySelectFlightsScreen(data);
       }
		if( currentSegment != data.currentSegment ) {
			currentSegment = data.currentSegment;
			goTop = true;
		}
		try {
			if( data.reviewItinScreen ) {
				loadNTRs(data);
			} else {
				hideNTRs();
			}
		} catch (e) {}
		try {
			omnitureShoppingStats(data);
		} catch (e) {}
		try {
			//Optimost Start
			if( data.reviewItinScreen && typeof(renderOptimost) == 'function' ) {
				renderOptimost();
			}
			//Optimost End
			refreshShoppingTimeout();
		} catch (e) {}
	} catch (e) {
		handleError();
	}
	if( goTop ) {
		window.location.replace('#top');
	}
}

function hasOAFlight(segmentDWRs) {
	var segmentCount = segmentDWRs.length;
	while( segmentCount-- ) {
		if( segmentDWRs[segmentCount].oaFlight ) {
			return true;
		}
	}
	return false;
}
function displayReviewItinData(data) {
	populateFlightSummary(data);
	hide('lowestFareContainer');
	hide('reviseFlights');
	hide('resultsContainer');
	if( !hasOAFlight(data.itinDWR.segmentDWRs) ) {
		show('express_purchase');
	}
}

function displaySelectFlightsScreen(data) {
	show('backButton');
	hide('continueButton');
	hide('flightSummary');
	hide('merchandisingMessage');
	hide('booking_fees');
	hide('merchandisingContent');
	hide('mixedSegmentMessage');
	show('resultsContainer');
	if( data.currentSegment == 0 ) {
		show('reviseFlights');
		show('searchByScheduleLink');
		hide('flightSummary');
		show('lowestFareContainer');
		hide('returnTopBackButton');
		hide('returnBottomBackButton');
		show('outboundTopBackButton');
		show('outboundBottomBackButton');
		hide('continueButton');
		hide('express_purchase');
		show('nextPrev');
	} else {
		hide('searchByScheduleLink');
		hide('lowestFareContainer');
		hide('reviseFlights');
		show('returnTopBackButton');
		show('returnBottomBackButton');
		hide('outboundTopBackButton');
		hide('outboundBottomBackButton');
		hide('continueButton');
		hide('nextPrev');
	}
	if( currentSegment != data.currentSegment ) {
		reInitSegmentData(data);
	}
	setFlightCount(data);
	populateFlightResultsTable(data);
	if( sortByColumn != data.sortByColumn ) {
		sortByColumn = data.sortByColumn;
		resetSortHeaders(data);
	}
}

function reInitSegmentData(data) {
	setRqstdSegmentInfo(data);
	setFilters(data);
	setSelectFlightsText(data);
	if( data.currentSegment > 0 ) {
		populateFlightSummary(data);
	}
}

function populateChoices(data) {
	var total = data.itinDWR.fareDWR.total;
	var nbrPax = data.itinRQDWR.nbrPassenger;
	var smBalance = data.skymilesDWR.balance;
	var miles = new Array();
	var prices = new Array();
	var decimalPrices = new Array();
	var commaMiles = new Array();
	var sourceData = data.itinDWR.pwmChoicesDWR;
	miles = sourceData.milesPerPassenger;
	prices = sourceData.dollarsOffAmount;
	decimalPrices = sourceData.fractionalDollarsOffAmount;
	commaMiles = sourceData.formattedMilesPerPassenger;
	setInnerHTML('pwm_balance',smBalance);
	smBalance = parseInt(smBalance);
	smBalance = formatNumber(smBalance,0,',','','','','');
	setInnerHTML('current_miles_display',smBalance);
	setInnerHTML('pwm_md',data.itinDWR.formatedMaxDiscount);
	setInnerHTML('pwm_ppp', total);
	setInnerHTML('pwm_tpp', total);
	setInnerHTML('pwm_noPax',nbrPax);
	setInnerHTML('pwm_tp',data.itinDWR.formatedFinalTotal);
	DWRUtil.removeAllOptions('pwm_select');
	var PWM_DropDown = get('pwm_select');
	PWM_DropDown.options[0] = new Option("Select amount", "0_0.0", false);
	PWM_DropDown.options[0].selected = true;
	for( i=0,j=1; i<miles.length; i++,j++ ) {
		var tempMPP = miles[i];
		var tempDOA = prices[i];
		var tempFDOA = decimalPrices[i];
		var tempFMPP = commaMiles[i];
		var PWM_Option_text = "$" + tempFDOA + " off ("+ tempFMPP+" miles)";
		var PWM_Option_value = tempMPP + "_" + tempDOA;
		PWM_DropDown.options[j] = new Option(PWM_Option_text, PWM_Option_value, false);
	}
	// calling pwm_js.js for method below
	updateScreenView('pwm_select', '', '','','','','','','','');
}

function populateFlightSummary(data) {
	hide('pwmOption');
	setFlightSummarySelectedText(data);
	fareRuleURL = data.itinDWR.fareRuleURL;
	if( data.reviewItinScreen ) {
		show('tripSummaryHeader');
		populateFlightSummaryTable(data);
		hide('summaryFromPricePWM');
		if( data.itinDWR.mixedPWMSegmentsInItin ) {
			showDiv('mixedSegmentMessage');
		}
		if( data.itinDWR.itinPWMEligible ) {
			show('pwmOption');
			get('passenger_flight_total').style.display = "none";
			if( exists(get('total_flight_price')) ) {
				get('total_flight_price').style.display = "block";
			}
			try {
				populateChoices(data);
			} catch (e) {
				hideDiv('pwmOption');
			}
		} else { // Not PWM Eligible
			try {
				get('passenger_flight_total').style.display = "table-row";
			} catch(e) {
				get('passenger_flight_total').style.display = "block";
			}
			if( exists(get('total_flight_price')) ) {
				get('total_flight_price').style.display = "none";
			}
		}
		// set review itinerary prices below (flightSummaryTable.jsp)
		setInnerHTML('summaryBaseFare', data.itinDWR.fareDWR.baseFare);
		setInnerHTML('summaryTaxes', data.itinDWR.fareDWR.taxesFees);
		setInnerHTML('summaryTotal', data.itinDWR.fareDWR.total);
		setInnerHTML('displayNoPax',data.itinRQDWR.nbrPassenger);
		setInnerHTML('displayFinalTotal',data.itinDWR.formatedFinalTotal);

		// set currency calculator link
		setCurrencyCalculatorLink(data);

		//FFA - Amex companion Certificates
		setInnerHTML('summaryCompanionBaseFare', data.itinDWR.fareDWR.baseFareCompanion);
		setInnerHTML('summaryCompanionTaxes', data.itinDWR.fareDWR.taxesFeesCompanion);

		if( data.itinDWR.fareDWR.refundable ) {
			hide('nonRefundableFareMsg');
			show('refundableFareMsg');
		} else {
			hide('refundableFareMsg');
			show('nonRefundableFareMsg');
		}
		if( data.itinDWR.lowestFare ) {
			show('summaryLowPrice');
		} else {
			hide('summaryLowPrice');
		}
	} else { // Not Review Itin
		if( data.itinDWR.itinPWMEligible ) {
			show
		}
	}
	if( data.itinDWR.fareDWR.ECouponFare || data.itinDWR.fareDWR.negotiatedFare ) {
		show('summaryFareIcon');
	} else {
		hideDiv('summaryFareIcon');
	}
}

function setCurrencyCalculatorLink(data){
	if(exists(get('convertAmount'))){
		var formattedFinalTotal = data.itinDWR.formatedFinalTotal;
		var segmentDWRs = data.itinDWR.segmentDWRs;
		var legDWRs = segmentDWRs[0].legDWRs;
		var destinationCountryCode = legDWRs[legDWRs.length - 1].arrivalCurrencyCode;
		if(formattedFinalTotal.indexOf('</span>') > 0){
			formattedFinalTotal = formattedFinalTotal.split('</span>')[1]; 
		}
				
		if(formattedFinalTotal.indexOf(';') > 0){
			formattedFinalTotal = formattedFinalTotal.split(';')[1];
		}
				
		if(formattedFinalTotal.indexOf(' ') > 0){
			//formattedFinalTotal = formattedFinalTotal.split(' ').join(''); 
			formattedFinalTotal = formattedFinalTotal.split(' ')[2]; 
		}
		get('convertAmount').value = formattedFinalTotal;
		get('destinationCurrencyCode').value = destinationCountryCode;
		try {
			createCalculatorLink(); /** function in /delta/shared_content/components/apps/currency_calculator_link.jsp **/

		} catch(e) {	}
	}	
}

function setFlightSummarySelectedText(data) {
	var text;
	if( data.roundTrip && data.currentSegment == 1 ) {
		text = 'You selected this outbound flight:';
	} else if( data.currentSegment == 1 ) {
		text = 'You selected this flight:';
	} else {
		text = 'You selected these flights:';
	}
	setInnerHTML('flightSummarySelectedText', text);
}

function setSelectFlightsText(data) {
	var text;
	if( data.roundTrip && data.currentSegment == 0 ) {
		text = 'Select an Outbound Flight';
	} else if( data.roundTrip && data.currentSegment == 1 ) {
		text = 'Select a Return Flight';
	} else {
		text = 'Select a Flight for Leg ' + (data.currentSegment+1);
	}
	setInnerHTML('selectFlightText', text);
}

function setRqstdSegmentInfo(data) {
	setInnerHTML('rqstdSegmentInfo', '\n<!-- mp_trans_disable_start -->\n' + data.itinRQDWR.departureCities[data.currentSegment] + '\n<!-- mp_trans_disable_end -->\n&nbsp;to&nbsp;\n<!-- mp_trans_disable_start -->\n' + data.itinRQDWR.arrivalCities[data.currentSegment] + '\n<!-- mp_trans_disable_end -->\n&nbsp;on&nbsp;' + data.itinRQDWR.departureDates[data.currentSegment]);
}

function getFilter(filterType) {
	var filterValues = null;
	for( var i=0; i < 3; i++ ) {
		var box = eval(document.getElementById(filterType + '[' + i + ']'));
		if( box != null ) {
			if( filterValues != null && filterValues != '' ) {
				filterValues = filterValues + ',';
			} else {
				filterValues = '';
			}
			if( box.checked == true ) {
				filterValues = filterValues +  box.value;
			} else {
				filterValues = filterValues +  ''  ;
			}
		}
	}
	return filterValues;
}

function resetAllFilters() {
	if( hasFilters ) {
		if( hasStopsFilter ) {
			resetFilter('stops');
		}
		if( hasDepAirportsFilter ) {
			resetFilter('depAirports');
		}
		if( hasArrAirportsFilter ) {
			resetFilter('arrAirports');
		}
	}
}

function resetFilter(filterType) {
	var filterValues = null;
	for( var i=0; i < 3; i++ ) {
		var box = eval(document.getElementById(filterType + '[' + i + ']'));
		if( box != null ) {
			box.checked = true;;
		}
	}
	return filterValues;
}


function setCheckedFilters(filterType, checkedValues) {
   try {
	   var filterValue = null;
	   for( var i=0; i < 3; i++ ) {
	   	var box = eval(document.getElementById(filterType + '[' + i + ']'));
	   	if( box != null ) {
	   		box.checked = false;
            filterValue = box.value;
            var checkValFound = false;
            if (checkedValues != null) {
               for(var k=0; k < checkedValues.length && checkValFound == false;k++ ) {
                  if (filterValue != null
                         && filterValue == checkedValues[k]) {
                     checkValFound = true;
                     box.checked = true;
                  }
               }
            }
	   	}
	   }
	} catch (e) {}
}

function getStopsText(stops) {
	if( stops == '0' ) {
		return 'Nonstop';
	} else if( stops == '1' ) {
		return '1-stop';
	} else {
		return 'Multi-stop';
	}
}

function setFilters(data) {
   try {
   	hasFilters	 = data.filtersDWR.hasFilters;
   	hasStopsFilter	 = data.filtersDWR.hasStopsFilter;
   	hasDepAirportsFilter	 = data.filtersDWR.hasDepAirportsFilter;
   	hasArrAirportsFilter	 = data.filtersDWR.hasArrAirportsFilter;
   	if( !hasFilters ) {
   		hide('filters');
   		return;
   	} else {
   		show('filters');
   	}
   	if( hasStopsFilter ) {
   		show('stopsFilter');
   	} else {
   		hide('stopsFilter');
   	}
   	if( hasDepAirportsFilter ) {
   		setFilterOptions('depAirports', data.filtersDWR.depAirportsFilterValues, data.filtersDWR.depAirportsFilterTexts);
         try {
            setCheckedFilters('depAirports', data.filtersDWR.filteredDepArpts);
         } catch (e) {}
   	} else {
   		setInnerHTML('depAirportsOptions', '');
   		hide('depAirportsFilter');
   	}
   	if( hasArrAirportsFilter ) {
   		setFilterOptions('arrAirports', data.filtersDWR.arrAirportsFilterValues, data.filtersDWR.arrAirportsFilterTexts);
         try {
            setCheckedFilters('arrAirports', data.filtersDWR.filteredArrArpts);
         } catch (e) {}
   	} else {
   		setInnerHTML('arrAirportsOptions', '');
   		hide('arrAirportsFilter');
   	}
   } catch (e) {}
}

function setLowestFareBadges(data) {
	show('lowestFareContainer');
	if( data.shoppingRsDWR == null ) {
		return;
	}
	if( data.shoppingRsDWR.nonStopFareIsLowest ) {
		setInnerHTML('lowFareBadge_1_fare', data.shoppingRsDWR.nonStopLowFareStr);
		setInnerHTML('lowFareBadge_1_tripType', 'Nonstop Itineraries');
	} else if( data.shoppingRsDWR.oneStopFareIsLowest ) {
		setInnerHTML('lowFareBadge_1_fare', data.shoppingRsDWR.oneStopLowFareStr);
		setInnerHTML('lowFareBadge_1_tripType', '1-stop Itineraries');
	} else if( data.shoppingRsDWR.multiStopFareIsLowest ) {
		setInnerHTML('lowFareBadge_1_fare', data.shoppingRsDWR.multiStopLowFareStr);
		setInnerHTML('lowFareBadge_1_tripType', 'Multi-stop Itineraries');
	}
	show('lowFareBadge_1');
	if( data.shoppingRsDWR.nonStopFareIsLowest ) {
		if( data.shoppingRsDWR.oneStopLowFareStr != null ) {
			setInnerHTML('lowFareBadge_2_fare', data.shoppingRsDWR.oneStopLowFareStr);
			setInnerHTML('lowFareBadge_2_tripType', '1-stop Itineraries');
			show('lowFareBadge_2');
		} else if( data.shoppingRsDWR.multiStopLowFareStr != null ) {
			setInnerHTML('lowFareBadge_2_fare', data.shoppingRsDWR.multiStopLowFareStr);
			setInnerHTML('lowFareBadge_2_tripType', 'Multi-stop Itineraries');
			show('lowFareBadge_2');
		}
	} else if( data.shoppingRsDWR.oneStopFareIsLowest ) {
		if( data.shoppingRsDWR.nonStopLowFareStr != null ) {
			setInnerHTML('lowFareBadge_2_fare', data.shoppingRsDWR.nonStopLowFareStr);
			setInnerHTML('lowFareBadge_2_tripType', 'Nonstop Itineraries');
			show('lowFareBadge_2');
		} else if( data.shoppingRsDWR.multiStopLowFareStr != null ) {
			setInnerHTML('lowFareBadge_2_fare', data.shoppingRsDWR.multiStopLowFareStr);
			setInnerHTML('lowFareBadge_2_tripType', 'Multi-stop Itineraries');
			show('lowFareBadge_2');
		}
	} else if( data.shoppingRsDWR.multiStopFareIsLowest ) {
		if( data.shoppingRsDWR.nonStopLowFareStr != null ) {
			setInnerHTML('lowFareBadge_2_fare', data.shoppingRsDWR.nonStopLowFareStr);
			setInnerHTML('lowFareBadge_2_tripType', 'Nonstop Itineraries');
			show('lowFareBadge_2');
		} else if( data.shoppingRsDWR.oneStopLowFareStr != null ) {
			setInnerHTML('lowFareBadge_2_fare', data.shoppingRsDWR.oneStopLowFareStr);
			setInnerHTML('lowFareBadge_2_tripType', '1-stop Itineraries');
			show('lowFareBadge_2');
		}
	}
}

function initStopsFilter(data) {
	var stopsFilterValues = new Array();
	var stopsFilterTexts = new Array();
	var stopsFilterOptionsCnt = 0;
	if( data.shoppingRsDWR.nonStopLowFareStr != null ) {
		stopsFilterValues[stopsFilterOptionsCnt] = '0';
		stopsFilterTexts[stopsFilterOptionsCnt] = getStopsText('0');
		stopsFilterOptionsCnt = stopsFilterOptionsCnt + 1;
	}
	if( data.shoppingRsDWR.oneStopLowFareStr != null ) {
		stopsFilterValues[stopsFilterOptionsCnt] = '1';
		stopsFilterTexts[stopsFilterOptionsCnt] = getStopsText('1');
		stopsFilterOptionsCnt = stopsFilterOptionsCnt + 1;
	}
	if( data.shoppingRsDWR.multiStopLowFareStr != null ) {
		stopsFilterValues[stopsFilterOptionsCnt] = '2';
		stopsFilterTexts[stopsFilterOptionsCnt] = getStopsText('2');
		stopsFilterOptionsCnt = stopsFilterOptionsCnt + 1;
	}
	if( stopsFilterOptionsCnt > 1 ) {
		for( var i=0; i < stopsFilterTexts.length;i++ ) {
			var stopsTxt = stopsFilterTexts[i];
			stopsFilterTexts[i] = '<a href="javascript:void(0)" onClick="openHelp2(\'/components/help/apps/booking/stops_filter.jsp\',event,260); return false;">'
										+ stopsTxt
										+ ' Itineraries</a>';
		}
		setFilterOptions('stops', stopsFilterValues, stopsFilterTexts);
	}
}

function setFilterOptions(filterName, filterValues, filterTexts) {
	var htmlTxt = [];
	for( var i=0; i < filterValues.length;i++ ) {
		if( filterValues[i] != null && filterValues[i] != '' ) {
			htmlTxt[htmlTxt.length] = '<nobr><input type="checkbox" name="' + filterName + '[' + i + ']" id="' + filterName + '[' + i + ']" value="' + filterValues[i] + '" checked onclick="javascript:filterFlights()">&nbsp;' + filterTexts[i] + '&nbsp;&nbsp;</nobr>';
		}
	}
	show(filterName + 'Filter');
	setInnerHTML(filterName + 'Options', htmlTxt.join(''));
}

function setFlightCount(data) {
	setInnerHTML('displayedFlightCnt', data.displayedFlightCnt);
	setInnerHTML('totalFlightCnt', data.totalFlightCnt);
}
var headerTitles = [];
headerTitles[1]="departs";
headerTitles[2]="arrives";
headerTitles[3]="stops";
headerTitles[4]="time";
headerTitles[6]="price";

function resetSortHeaders(data) {
	for( var i=1; i < 7;i++ ) {
		if( i != 5 ) {
			if( data.sortByColumn == i ) {
				setClassName(headerTitles[i] + 'RowHdr', 'active');
				setClassName(headerTitles[i] + 'RowTitle', 'active');
				show(headerTitles[i] + 'RowHdrText');
				hide(headerTitles[i] + 'RowSortURL');
				show(headerTitles[i] + 'RowHdrSorted');
			} else {
				setClassName(headerTitles[i] + 'RowHdr', 'inactive');
				setClassName(headerTitles[i] + 'RowTitle', 'inactive');
				hide(headerTitles[i] + 'RowHdrText');
				show(headerTitles[i] + 'RowSortURL');
				hide(headerTitles[i] + 'RowHdrSorted');
			}
		}
	}
}

function resetPWM() {
	try {
		if( exists(get("hidden_pwm_price")) ) {
			get("hidden_pwm_price").value = null;
		}
		if( exists(get("hidden_pwm_miles")) ) {
			document.getElementById("hidden_pwm_miles").value = null;
		}
	} catch (e) {}
}

function setAdvisoryMessages(data) {
	if( data.messagesDWR.flexFromFareDiff ) {
		show('flexFromFareDiffMsg');
   }
   setCabinAdvisoryMessages(data);
}

function setCabinAdvisoryMessages(data) {
	var dspldCabinTypes = data.cabinTypes;
	if( rqstdCabin == null || dspldCabinTypes == null) {
		return;
	}
	var text = null;
	if( rqstdCabin == 'Coach' && dspldCabinTypes == 'mixed' ) {
		text = 'On certain flights, First/Business Class seats may be available as our lowest fares of the day.';
	} else if( rqstdCabin == 'Coach' && dspldCabinTypes == 'allFirst' ) {
		text = 'First/Business seats are available as our lowest fares of the day.';
	} else if( rqstdCabin == 'First' && dspldCabinTypes == 'mixed') {
		text = 'Certain flights only have seats available in Coach Class.';
	} else if( rqstdCabin == 'First' && dspldCabinTypes == 'allCoach') {
		text = 'Only Coach Class seats are available.';
	}
	if( text != null ) {
		setInnerHTML('preferred_cabin_advisoryMsgTxt', text);
		show('preferred_cabin_advisoryMsg');
	}
}

function updateMilesBalanceDisplay() {
	if( get('pwm_balance').innerHTML != "" ) {
		var rawBalance = parseInt(get('pwm_balance').innerHTML);
		var displayBalance = get('current_miles_display');
		displayBalance.innerHTML = formatNumber(rawBalance,0,',','','','','');
	}
}

function refreshOptimost(){

}

//Omniture functions for booking DWR
	
function omnitureShoppingStats(data) {
	try {
		s.pageName="";
		s.prop2="";
		s.prop3="";
		s.prop4="";
		s.prop5="";
		s.prop6="";
		s.prop7="";
		s.prop8="";
		s.prop9="";
		s.prop10="";
		s.prop11="";
		s.prop12="";
		s.prop13="";
		s.prop14="";
		s.prop15="";
		s.prop16="";
		s.prop17="";
		s.prop18="";
		s.prop19="";
		s.prop20="";
		s.prop21="";
		s.prop22="";
		s.prop38="";
		s.prop44="";
		eVar18="";
		s.events="";
		s.eVar3="";
		s.eVar4="";
		s.eVar5="";
		s.eVar6="";
		s.eVar7="";
		s.eVar8="";
		s.eVar9="";
		s.eVar10="";
		s.eVar11="";
		s.eVar12="";
		s.eVar13="";
		s.eVar14="";
		s.eVar15="";
		s.eVar30="";
		s.eVar31="";
		s.products="";
		
		if (data.reviewItinScreen) {
			if(exists(get('purchase_now'))){
				OMTR_pageName = "Review Itinerary with One-Click";
				var expressControl = get('purchase_now');
				addEvent(expressControl, 'click', oneClickSelect, false);
				if (isUpsellSelected()) {
					OMTR_pageName = "Review Itinerary with One-Click and Upsell";	
				}
			} else  if (isUpsellSelected()){
				OMTR_pageName = "Review Itinerary with Upsell Selected";
				var upsellCabin =  get("upsell_cabin2").innerHTML; 
				s.prop44 = upsellCabin;
			} else {
				OMTR_pageName="Booking View Itinerary Flights";
			}
            var OMTR_flightTotalPrice = data.itinDWR.fareDWR.baseFare;
			if (OMTR_flightTotalPrice.indexOf(';') > 0) {
				OMTR_flightTotalPrice = OMTR_flightTotalPrice.substring(OMTR_flightTotalPrice.indexOf(';')+1);
			} else {
				OMTR_flightTotalPrice = OMTR_flightTotalPrice.substring(1);
			}
			while (true) {
				if (OMTR_flightTotalPrice.indexOf(',') > 0)
					OMTR_flightTotalPrice = OMTR_flightTotalPrice.substring(0, OMTR_flightTotalPrice.indexOf(',')) + OMTR_flightTotalPrice.substring(OMTR_flightTotalPrice.indexOf(',')+1);
				else
                   	break;
			}
			OMTR_flightTotalPrice = parseFloat(OMTR_flightTotalPrice);
			if (isNaN (OMTR_flightTotalPrice)) {
				OMTR_flightTotalPrice = data.itinDWR.fareDWR.baseFare;
                OMTR_flightTotalPrice=OMTR_flightTotalPrice.match(/[^>]*$/);
                OMTR_flightTotalPrice= OMTR_flightTotalPrice.toString();
                OMTR_flightTotalPrice= OMTR_flightTotalPrice.replace(/,/g, "");
			}
			
			s.pageName=OMTR_pageName;
			s.events= "scAdd,event25,event26"
			s.currencyCode= OMTR_currencyCode;
			if (OMTR_tripType =="multicity") {
				products= ";" + "Revenue" + "-" + OMTR_tripType + "-" +(OMTR_cityPairs.toUpperCase())+ ";" + ";" + ";" + "event25=" + (OMTR_flightTotalPrice*OMTR_paxCount) + "|" +  "event26=" + OMTR_paxCount;
				s.products=products;
			} else {
				products= ";" + "Revenue" + "-" + OMTR_tripType + "-" +(OMTR_departureCity[0].toUpperCase())+"-"+(OMTR_destinationCity[0].toUpperCase())+ ";" + ";" + ";" + "event25=" + (OMTR_flightTotalPrice*OMTR_paxCount) + "|" +  "event26=" + OMTR_paxCount;
				s.products=products;
			}
			void(s.t());
		} else if (data.currentSegment > 0) {
			OMTR_pageName = 'Select Return Flight';
			s.pageName=OMTR_pageName;
			s.prop20= countFlightRows();
			void(s.t());
		}
	} catch (e) { }
}

function oneClickSelect(){
		s.events="scCheckout";
}

//end Omniture functions for booking DWR
/******* End booking/javascripts/dwr/pitins/pitinsDWR.js ***********/


/* populatePricingTable.js */
/******* Begin booking/javascripts/dwr/populatePricingTable.js ***********/
function getDepartureColumn(segmentDWR) {
	var arpt = segmentDWR.legDWRs[0].departureCity.airportCode;
	var text = [];
	text[text.length] = '<span class="segmentDepArrTime">' + segmentDWR.legDWRs[0].departureTm + '</span><br /><!-- mp_trans_disable_start -->' + getCityHref(arpt) + '<!-- mp_trans_disable_end -->';
	if (segmentDWR.lastFlightArrivalCity != null) {
		text[text.length] = '<br /><br />The flight selected for the previous leg arrives at <!-- mp_trans_disable_start -->' + getCityHref(segmentDWR.lastFlightArrivalCity) + '<!-- mp_trans_disable_end -->';
	}
	return text.join('');
}

function getArrivalColumn(segmentDWR) {
	var lastIndex = segmentDWR.legDWRs.length - 1;
	var arpt = segmentDWR.legDWRs[lastIndex].arrivalCity.airportCode;
	var text = [];
	text[text.length] = '<span class="segmentDepArrTime">' + segmentDWR.legDWRs[lastIndex].arrivalTm + '</span><br/><!-- mp_trans_disable_start -->' + getCityHref(arpt) + '<!-- mp_trans_disable_end -->';
	if( segmentDWR.legDWRs[lastIndex].dayChange != null ) {
		text[text.length] = '<br /><br />Arrives ' + segmentDWR.legDWRs[lastIndex].arrivalDay + '&nbsp;' + segmentDWR.legDWRs[lastIndex].arrivalMonth;
	}
	if( segmentDWR.outboundFlightDepartureCity != null ) {
		text[text.length] =  '<br /><br />Outbound flight departs from <!-- mp_trans_disable_start -->' + getCityHref(segmentDWR.outboundFlightDepartureCity) + '<!-- mp_trans_disable_end -->';
    }
	return text.join('');
}

function getCityHref(arpt) {
	return '<a href="javascript:void(0)" onMouseOver="javascript:showCityDetail(event, \'' + arpt + '\')" onMouseOut="javascript:hideCityDetail()"><!-- mp_trans_disable_start -->'+arpt+'<!-- mp_trans_disable_end --></a>';
}

function getSummaryStopsColumn(segmentDWR) {
	var lastIndex = segmentDWR.legDWRs.length - 1;
	var text = [];
	text[text.length] =  getStopsText(segmentDWR.tripCategory);
	text[text.length] =  getConnentingCities(segmentDWR);
	return text.join('');
}

function getResultsStopsColumn(segmentDWR) {
	var lastIndex = segmentDWR.legDWRs.length - 1;
	var text = [];
	var stopsTxt =  getStopsText(segmentDWR.tripCategory);
	if( segmentDWR.itinCategory != 0 && segmentDWR.tripCategory == 0 ) {
		text[text.length] =  getMessageHref(stopsTxt, 'Stops may be on other flights in the itinerary');
    } else {
		text[text.length] =  stopsTxt;
    }
	text[text.length] = getConnentingCities(segmentDWR);
	return text.join('');
}

function getConnentingCities(segmentDWR) {
	var lastIndex = segmentDWR.legDWRs.length - 1;
	var text = [];
	for( var j=0, k=lastIndex-1; j <= k; j++ ) {
		if( segmentDWR.legDWRs[j+1].interCityConnection ) {
			text[text.length] = '<div class="connections">Airport Change:';
            text[text.length] = '<br />arrives:<br />';
			text[text.length] = '<a href="javascript:void(0)" onMouseOver="javascript:showCityDetail(event, \'' + segmentDWR.legDWRs[j].arrivalCity.airportCode + '\')" onMouseOut="javascript:hideCityDetail()"><!-- mp_trans_disable_start -->'+segmentDWR.connectingCities[j]+'<!-- mp_trans_disable_end --></a>';
			text[text.length] = '<br />departs:<br />';
			text[text.length] = '<a href="javascript:void(0)" onMouseOver="javascript:showCityDetail(event, \'' + segmentDWR.legDWRs[j+1].departureCity.airportCode + '\')" onMouseOut="javascript:hideCityDetail()"><!-- mp_trans_disable_start -->'+segmentDWR.legDWRs[j+1].departureCity.cityName+'<!-- mp_trans_disable_end --></a>';
			text[text.length] = '<br />(' + formatDuration(segmentDWR.connectingTimes[j]) + ' layover)</div>';
       } else {
          text[text.length] = '<div class="connections">'
          text[text.length] = '<a href="javascript:void(0)" onMouseOver="javascript:showCityDetail(event, \'' + segmentDWR.legDWRs[j].arrivalCity.airportCode + '\')" onMouseOut="javascript:hideCityDetail()"><!-- mp_trans_disable_start -->'+segmentDWR.connectingCities[j]+'<!-- mp_trans_disable_end --></a>';
          text[text.length] = '<br />(' + formatDuration(segmentDWR.connectingTimes[j]) + ' layover)';
          text[text.length] = '</div>';
       }
    }
	return text.join('');
}

function getTimeColumn(segmentDWR) {
	return formatDuration(segmentDWR.totalTripTime);
}

function getBanner(bannerText) {
	return bannerText;
}

function getFlightsColumn(segmentDWR) {
	var text = [];
	var legDWRs = segmentDWR.legDWRs;
	for( var legNbr=0, legCount=legDWRs.length; legNbr < legCount; legNbr++ ) {
		var legDWR = legDWRs[legNbr];
		text[text.length] = '<div class="flightGroupContainer">';
		text[text.length] = '<div class="flightCabin';
		if( legDWR.upgradeDWR != null && hasUpgradeEligible ) {
			text[text.length] = 'Upgrade';
		}
		text[text.length] = '_Flight">';
		var fltSummary = 'javascript:fltSummary(event, \'' + legDWR.displayAirlineName + ' '  + legDWR.flightNbr + '\', \'' + segmentDWR.legDWRs[legNbr].departureCity.airportCode +'\', \'' + segmentDWR.legDWRs[legNbr].arrivalCity.airportCode + '\', \''
						   + segmentDWR.legDWRs[legNbr].stops + '\', \'' + segmentDWR.legDWRs[legNbr].duration + '\', \''
						   + segmentDWR.legDWRs[legNbr].departureMonth + '\', \'' + segmentDWR.legDWRs[legNbr].departureDay + '\', \'' + segmentDWR.legDWRs[legNbr].departureTm + '\', \'' + segmentDWR.legDWRs[legNbr].arrivalMonth + '\', \''
						   + segmentDWR.legDWRs[legNbr].arrivalDay + '\', \'' + segmentDWR.legDWRs[legNbr].arrivalTm + '\')';
		text[text.length] = '<a href="javascript:openWin(\''+ legDWR.flightDetailsURL +'\',\'equipmentDetail\',550,310)" '
								+ ' onMouseOver="' + fltSummary + '" onMouseOut="javascript:hideMessage()" ><!-- mp_trans_disable_start -->'
								+ legDWR.displayAirlineName + '<!-- mp_trans_disable_end -->&nbsp;' + legDWR.flightNbr + '</a>';
		text[text.length] = '<br /><!-- mp_trans_disable_start -->' + legDWR.aircraftType + '<!-- mp_trans_disable_end -->';
		if( legDWR.displayOperatingCarrier != null ) {
			text[text.length] = '<br />operated by <!-- mp_trans_disable_start -->' + legDWR.displayOperatingCarrier + '<!-- mp_trans_disable_end -->';
		}
		if( legDWR.equipmentChangeNeeded ) {
			text[text.length] = '<br />Change Planes';
		}
		if( legDWR.notPreferredCabin ) {
			text[text.length] = '' ;
		}
		if( legDWR.subjectToApproval ) {
			text[text.length] = '<br />subject to government approval';
		}
		text[text.length] = '<br /><a href="javascript:openWin(\''+ legDWR.inFlightDetailsURL +'\',\'inflightservices\',550,310)">In-Flight Services</a>';
		text[text.length] = '</div>';
		text[text.length] = '<div class="flightCabin';
		if( legDWR.upgradeDWR != null && hasUpgradeEligible ) {
			text[text.length] = 'Upgrade';
		}
		text[text.length] = '_Cabin">';
		text[text.length] = '<div class="cabin';
		if( legDWR.upgradeDWR != null && hasUpgradeEligible ) {
			text[text.length] = 'Upgrade';
		}
		text[text.length] = '">';
		text[text.length] = legDWR.cabinAndBookingCode;
		if( exists(legDWR.OAFlight) && !legDWR.OAFlight ) {
			text[text.length] = '<br \><a href="javascript:openWin(\'' + legDWR.viewSeatsURL + '\',\'LSM\',875,580)">View Seats</a>';
		}
		text[text.length] = '</div>';
		if( legDWR.upgradeDWR != null && hasUpgradeEligible ) {
			text[text.length] = '<div class="upgrade">Upgrade:<br \>';
			text[text.length] = '<a href="#" onFocus="blur()" onClick="openHelp2(\'' + legDWR.upgradeDWR.upgradePopUpHelpFile + '\',event,265); return false">' + legDWR.upgradeDWR.upgradeStatusDisplayText + '</a></div>';
		}
		text[text.length] = '</div>';
		text[text.length] = '<div class="clear"></div>';
		text[text.length] = '</div>';
	} //end for legDWR
	return text.join('');
}

function getPriceColumn(segmentDWR) {
	var text = [];
	if( segmentDWR.fareDWR.lowestFare ) {
		text[text.length] = '<div class="lowFareBadge">';
		text[text.length] = '<div class="icon"></div>';
		text[text.length] = '<dl>' + getFareText(segmentDWR) + '</dl>';
		text[text.length] = getSelectFareButton(segmentDWR);
		text[text.length] = '</div>';
	} else {
		text[text.length] = '<dl>' +  getFareText(segmentDWR) + '</dl>';
		text[text.length] = getSelectFareButton(segmentDWR);
	}
	return text.join('');
}

function getFareText(segmentDWR) {
	var text = [];
	text[text.length] = '<dt>Segment Base Fare</dt><dd class="segment_base_fare" onmouseover="showCurrencyToolTip(event)" onmouseout="hideCurrencyToolTip(event)">';
	if( !segmentDWR.lastSegment ) {
		text[text.length] = 'From&nbsp;';
	}
	text[text.length] = '<!-- mp_trans_disable_start --><strong>' + segmentDWR.fareDWR.baseFare + '</strong></dd><!-- mp_trans_disable_end -->&nbsp;';
	text[text.length] = '<dt>Trip Type</dt><dd class="trip_type">';
	if( segmentDWR.roundTrip ) {
		text[text.length] = 'round trip';
	} else {
		text[text.length] = 'full trip';
	}
	text[text.length] = '</dd>';
	text[text.length] = '<br/>' ;
	text[text.length] = ' &#43; ';
	text[text.length] = '<dt>Taxes</dt><!-- mp_trans_disable_start --><dd class="taxes">' + segmentDWR.fareDWR.taxesFees + '</dd>&nbsp;' + '<a href="#" onClick="openAll(\'/planning_reservations/plan_flight/online_reservations/fares_ticketing_rules/taxes_fees/index.jsp\'); return false" style="text-decoration: underline; font-weight:normal"><!-- mp_trans_disable_end -->Taxes/Fees</a>&nbsp;=&nbsp;';
	text[text.length] = '<dt>Full Fare</dt><dd class="full_fare">' + segmentDWR.fareDWR.total + '</dd>';
	return text.join('');
}

function getSelectFareButton(segmentDWR) {
	var text = [];
	text[text.length] = '<div class="action">';
	if( segmentDWR.fareDWR.ECouponFare && !segmentDWR.fareDWR.amexCompanionFare) {
		text[text.length] = '<a href="#" onfocus="blur()" onclick="openHelp2(\'/booking/components/booking/ecoupon/ecoupon_popup.html\', event, 125); return false"><img src="'+imageServer+'/images/icons/ecoupon.gif" width="35" height="18" alt="eCoupon"></a>&nbsp;';
	} else if( segmentDWR.fareDWR.negotiatedFare ) {
		text[text.length] = '<img src="'+imageServer+'/images/icons/negotiated.gif" width="35" height="18" border="O" align="absmiddle" alt="Negotiated Fare">&nbsp;';
	} else if( segmentDWR.fareDWR.webFare ) {
		text[text.length] = '<a href="#" onfocus="blur()" onclick="openHelp2(\'/booking/components/booking/webfare_popup.html\', event, 125); return false"><img src="'+imageServer+'/images/icons/webfare.gif" width="35" height="18" alt="Web Fare"></a>&nbsp;';
	}
	text[text.length] = '<input type="button" class="button right" value="Select" name="select_button" id="back_button" onclick="javascript:selectFlight(' + segmentDWR.segmentNbr + ', \'' + segmentDWR.segmentId + '\',' + segmentDWR.itinSequenceNumber +')" />'
	if( segmentDWR.payWithMilesEligible ) {
		text[text.length] = '<br /><span class="pwm_pitins_span"><a href="/skymiles/use_miles/pay_miles/index.jsp" target="_blank">';
		text[text.length] = '<span class="pwm" onMouseOver="javascript:showHoverContent(event,450,160,\'pwm_segments_msg\',\'/shared/components/pwm/segments_pwm_ad.jsp\', \'no\',-500, -125)" onMouseOut="javascript:hideHoverContent(event,\'pwm_segments_msg\')">Pay with Miles</span></a> eligible</span>';
	}
	text[text.length] = '</div>';
	return text.join('');
}

function formatDuration(dur) {
   f = "";
   if (dur.length == 4) {
      try {
	      th = dur.substr(0,2);
	      tm = dur.substr(2,2);
	      if( th.substr(0,1) == 0 ) {
	      	th = th.substr(1,1);
	      }
	      if (tm.substr(0,1) == 0) {
	      	tm = tm.substr(1,1);
	      }
	      h = parseInt(th);
	      m = parseInt(tm);
	      if( h > 0 && m > 0 ) {
	      	f = h+" hr "+m+" min";
	      } else if( h > 0 ) {
	      	f = h+" hr";
	      } else if( m > 0 ) {
	      	f = m+" min";
	      }
      } catch (e) { f = dur; }
		return f;
	} else {
		return dur;
	}
}

var resultCellFuncs = [ getDepartureColumn, getArrivalColumn, getResultsStopsColumn, getTimeColumn, getFlightsColumn, getPriceColumn ];
var summaryCellFuncs = [ getDepartureColumn, getArrivalColumn, getSummaryStopsColumn, getTimeColumn, getFlightsColumn ];
var bannerCellFuncs = [ getBanner ];

function populateFlightResultsTable(data) {
	var tableId = 'resultsList';
    DWRUtil.removeAllRows(tableId);
	if( data.sortByColumn == 3 ) {
		var segmentsArray = [];
		var index=0;
		var segments = data.segmentDWR;
		var itinCategory = '';
		for( var i=0, j=segments.length; i < j;i++ ) {
			if( itinCategory != segments[i].itinCategory ) {
				if( segmentsArray.length > 0 ) {
					populateTable(tableId, segmentsArray, resultCellFuncs);
					segmentsArray = [];
					index=0;
				}
				populateRowBanner(tableId, getStopsText(segments[i].itinCategory), bannerCellFuncs);
				itinCategory = segments[i].itinCategory;
			}
			segmentsArray[index] = segments[i];
			index = index+1;
		}
		if( segmentsArray.length > 0 ) {
			populateTable(tableId, segmentsArray, resultCellFuncs);
		}
	} else {
		populateTable(tableId, data.segmentDWR, resultCellFuncs);
	}
}

function populateFlightSummaryTable(data) {
	var tableId = 'flightsSummary';
	DWRUtil.removeAllRows(tableId);
	for( var i=0, j=data.currentSegment; i < j;i++ ) {
		var segDetail = data.itinRQDWR.departureCities[i] + '&nbsp;to&nbsp;' + data.itinRQDWR.arrivalCities[i] + '&nbsp;on&nbsp;' + data.itinRQDWR.departureDates[i];
		populateRowBanner(tableId, segDetail, bannerCellFuncs);
		var segmentsArray =[];
		segmentsArray[0] = data.itinDWR.segmentDWRs[i]
		populateTable(tableId, segmentsArray, summaryCellFuncs);
	}
}

function populateTable(tableId, segmentDWR, cellFuncs) {
	DWRUtil.addRows( tableId, segmentDWR, cellFuncs, {
		rowCreator:function(options) {
			segmentDWR =  options.rowData;
			var rowColor;
			if( (options.rowIndex % 2) == 0 ) {
				rowColor = "odd";
			} else {
				rowColor =  "even";
			}
			var row = document.createElement("tr");
			row.className =  rowColor;
			return row;
		},
		cellCreator:function(options) {
			segmentDWR =  options.rowData;
			var td = document.createElement("td");
			if( options.cellNum == 5 && segmentDWR.fareDWR.lowestFare ) {
				td.className =  "lowestCell";
			}
			return td;
		},
		escapeHtml:false
	});
}

function populateRowBanner(tableId, bannerText, cellFuncs) {
	var banner =[];
	banner[0] = bannerText;
	DWRUtil.addRows( tableId, banner, cellFuncs, {
		rowCreator:function(options) {
			var row = document.createElement("tr");
			row.className =  "rowBanner";
			return row;
		},
		cellCreator:function(options) {
			var td = document.createElement("th");
			td.setAttribute("align","left");
			td.setAttribute("colSpan", 6);
			return td;
		},
		escapeHtml:false
	});
}

/******* End booking/javascripts/dwr/populatePricingTable.js ***********/


/* eCreditSearch.js */
function changeDoc(radioValue, eCreditNumber)
{
var typeId = "DocumentType" + eCreditNumber;
var NameId = "DocumentName" + eCreditNumber;
if (radioValue == "Yes") {
document.getElementById(typeId).innerHTML="eTicket";
document.getElementById(NameId).innerHTML="Name on the eTicket";
}

else {
document.getElementById(typeId).innerHTML="eCredit";
document.getElementById(NameId).innerHTML="Name on the eCredit";
}

}

   function checkDocNumFields() {
      var eCreditCheck = false;
	  for (i=1; i<4; i++) {
	      if ((document.getElementById('DocNumberInput' + i).value != null && document.getElementById('DocNumberInput' + i).value.length > 1) ||
		  (document.getElementById('FirstNameInput' + i).value != null && document.getElementById('FirstNameInput' + i).value.length > 1 ) ||
		  (document.getElementById('LastNameInput' + i).value != null && document.getElementById('LastNameInput' + i).value.length > 1 )) {
		  eCreditCheck = true;
          }
	   }
       if (eCreditCheck == true) {
		   document.getElementById('documentNumSearchSelected').checked=true;
        }
  }
  
   function checkSMPinFields() {
      var SMPinCheck = false; {
	      if ((document.getElementById('SmSearchSelected').value != null && document.getElementById('SmSearchSelected').value.length > 1) ||
		  (document.getElementById('SmPinSearch').value != null && document.getElementById('SmPinSearch').value.length > 1 )) {
		  SMPinCheck = true;
		   document.getElementById('documentSMSearchSelected').checked=true;
          }
	   }
  }
  
 function resetName(num){
  document.getElementById('FirstNameInput' + num).disabled = false;
  document.getElementById('LastNameInput' + num).disabled = false;
  document.getElementById('FirstNameInput' + num).value = "";
  document.getElementById('LastNameInput' + num).value = "";
  document.getElementById('DocNumberInput' + num).value = "";
  }

 function chkRadioStatus(){
   if (document.getElementById('eTicketType1').checked) {
     changeDoc('Yes', 1);
	 populateName(1);
   }                                                         
   if (document.getElementById('eTicketType2').checked){
     changeDoc('Yes', 2); 
	 populateName(2);  
   }           
   if (document.getElementById('eTicketType3').checked){
     changeDoc('Yes', 3); 
	 populateName(3);           
   }
 }
 
 function populateName(num){
    document.getElementById('FirstNameInput' + num).value = jsPopulateName1[0];
    document.getElementById('LastNameInput' + num).value =  jsPopulateName1[1];
    document.getElementById('FirstNameInput' + num).disabled = true;
   document.getElementById('LastNameInput' + num).disabled = true;
   checkDocNumFields();
}



/*cityCodes.js*/
var airportListForm = "";
var airportListBox = "";

function openCityCodes(tbForm, tbBox, e) {
   self.airportListForm = tbForm;
   self.airportListBox = tbBox;

   w = screen.width-400
   h = screen.height-215
   x = e.screenX
   y = e.screenY
      if(x > w){
         x = x-400
         }
      if(y > h){
         y = y-215
         }

   childwin=window.open('/booking/cityCodes.do','CityCodes','width=400,height=215,top='+y+',left='+x);
}

function setAirportValue(airportCode) {
   var box = document.getElementsByName(airportListBox);
   for (var i=0; i<box.length; i++) {
      box[i].value = airportCode;
   }
}

// this will auto close the calendar if no date is selected and focus is lost

function closeMe(){
   if (childwin != null){
   childwin.close()
   childwin = null
   }
}
/* validation object */
/*
	Validation Object
	Version 1.1
	last updated: 4/28/2008
*/
function ValidationObj() {
	this.oProps = new GenObj();
	this.forms = new Array();
	this.today = new Date();
	this.months = {Jan:0,Feb:1,Mar:2,Apr:3,Apr:4,Jun:5,Jul:6,Aug:7,Sep:8,Oct:9,Nov:10,Dec:11};
	this.monthsFullName = {"January":0,"February":1,"March":2,"April":3,"May":4,"June":5,"July":6,"August":7,"September":8,"October":9,"November":10,"December":11};
	this.curField = "";
	this.labels = null;
	this.numLabels = 0;
	this.numForms = 0;
	this.errorCollection = { }; /*this is a collection of errors based on LABEL, eg: { first_name : { count:2, errorRegionDivId : "name_fname_pax1_req_e", allElementIds:{ name_fname_pax1_req : "first_name", name_fname_pax2_req : "first_name"} } }*/
}
ValidationObj.prototype.setProp = function(prop,value) { this.oProps.setProp(prop,value); };
ValidationObj.prototype.getProp = function(prop) { var rtn = this.oProps.getProp(prop); if(rtn===undefined) {} return rtn; };
ValidationObj.prototype.disableFeatures = function(types) {
	//console.log("disableFeatures");
	/* supported values: disabled_buttons, init */
	this.setProp("disable",types);
};
/* function to allow the disabling of specific features, passed as a string array */
ValidationObj.prototype.isDisabled = function(val) {
	//console.log("isDisabled");
	var disabledFeatures = this.getProp("disable");
	if(exists(disabledFeatures)) {
		j = disabledFeatures.length;
		for (var i=0;i<j;i++) {
			if(disabledFeatures[i] == val) { return true; }
		}
	}
	return false;
};

ValidationObj.prototype.doesCCNumPassesLuhn = function(ccNum) {
	var sum = 0, digit = 0, addend = 0, timesTwo = false;
	for (i = ccNum.length - 1; i >= 0; i--) {
		digit = parseInt(ccNum.substring (i, i + 1));
		if (timesTwo) {
			addend = digit * 2;
			if (addend > 9) {
				addend -= 9;
			}
		} else {
			addend = digit;
		}
		sum += addend;
		timesTwo = !timesTwo;
	}
	return (sum % 10) === 0;
};
ValidationObj.prototype.getMonthNum = function(month) { 
	//console.log("getMonthNum");
	return this.months[month];
};
ValidationObj.prototype.deltamaticNames = function(t) {
	return t.replace(/['-]/g," "); /* replace ' with space, for names in deltamatic */
};
ValidationObj.prototype.removeSpaces = function(t) {
	return t.replace(/\s*/g,"");
};
ValidationObj.prototype.replaceMultipleSpaces = function(t) {
	return t.replace(/[\s]{2,}/g," "); 
};
ValidationObj.prototype.stripWhiteSpace = function(t) {
	return t.replace(/^\s*/,"").replace(/\s*$/,"");
};
ValidationObj.prototype.stripBadChars = function(t) {
	//console.log("stripBadChars");
	return this.stripWhiteSpace(this.replaceMultipleSpaces(t.replace(/[/\\]/g,""))).replace(/['-]/g," ");
};
ValidationObj.prototype.isNumber = function(id, length) {
	//console.log("isNumber");
	//Lucas added length parameter for number validation
	var t = get(id).value.replace(/,/g, "");
	if(arguments.length > 1){
		length = parseInt(length);	
		if(isNaN(t)){
			this.markError(id); return false;
		} else if(t.length == length){
			this.removeError(id);return true;
		} else {
			this.markError(id); return false;
		}		
	} else {
		if(isNaN(t) || this.stripWhiteSpace(t) === "") { this.markError(id); return false; }
		else { this.removeError(id);return true; }
	}
};
ValidationObj.prototype.isDataMMSlashDDSlashYYYY = function(id) {
	var t = get(id).value;
	if(/\d{1,2}\/\d{1,2}\/\d{2,4}/.test(t)) { this.removeError(id);return true; }
	else { this.markError(id); return false; }
}
ValidationObj.prototype.areEqual = function(id1, id2) {
	if(get(id1).value != get(id2).value) { 
		this.markError(id2); return false; }
}
ValidationObj.prototype.requiresCCID = function(type) {
	return (type == "AX" || type == "VI" || type == "CA" || type == "DS" || type == "DC");
};
ValidationObj.prototype.findParentForm = function(id) {
	//console.log("findParentForm");
	var curField = get(id);
	while(curField.parentNode) {
		if(exists(curField.parentNode.nodeName) && curField.parentNode.nodeName.toLowerCase() === "form") {
			return curField.parentNode.id;
		}
		curField = curField.parentNode;
	}
};
ValidationObj.prototype.copyFieldData = function(id,fromContainerId,toContainerId) {
	//console.log("copyFieldData");
	var tFrom = [];
	var tTo = [];
	var tmpCollection;
	var tmpType;
	if(get(id).checked) {
		tmpCollection = get(fromContainerId).getElementsByTagName("*");
		for(var i=0;i<tmpCollection.length;i++) {
			if(tmpCollection[i].id!="") {
				if(exists(get(tmpCollection[i].id))) {
					tmpType = tmpCollection[i].type;
					if(tmpType=="text"||tmpType=="textarea"||tmpType=="select-one"||tmpType=="select-multiple"||tmpType=="radio"||tmpType=="checkbox") {
						if(!tmpCollection[i].id.match(/_replicate/) && (!tmpCollection[i].id.match(/_exclude/))) { tFrom.push(tmpCollection[i]);}
					}
				}
			}
		}
	}
	tmpCollection = get(toContainerId).getElementsByTagName("*");
	for(var i=0;i<tmpCollection.length;i++) {
		if(tmpCollection[i].id!="") { 
			if(exists(get(tmpCollection[i].id))) {
				tmpType = tmpCollection[i].type;
				if(tmpType=="text"||tmpType=="textarea"||tmpType=="select-one"||tmpType=="select-multiple"||tmpType=="radio"||tmpType=="checkbox") {
					if(!tmpCollection[i].id.match(/_replicate/) && (!tmpCollection[i].id.match(/_exclude/))) { tTo.push(tmpCollection[i]);}
				}
			}
		}
	}
	if(get(id).checked) {
		for(var i=0;i<tFrom.length;i++) {
			tmpType = get(tFrom[i].id).type;
			switch(tmpType) {
				case "radio": get(tTo[i].id).selected = (get(tFrom[i].id).selected) ? "selected" : false; break;
				case "checkbox": get(tTo[i].id).checked = get(tFrom[i].id).checked; break;
				default: get(tTo[i].id).value = get(tFrom[i].id).value; break;
			}
			//get(tTo[i].id).disabled="disabled";
		}
	} else {
		for(var i=0;i<tTo.length;i++) { 
			tmpType = get(tTo[i].id).type;
			if(tmpType!="radio" && tmpType!="checkbox") { get(tTo[i].id).value=""; }
			//get(tTo[i].id).disabled="";
		}
	}
};


ValidationObj.prototype.copyHiddenFieldData = function(id,fromContainerId,toContainerId) {
	//number of fields must match in fromContainerId and toContainerId any other fields that are not to be copied should have a reference of _exclude in the ID
	//console.log("copyHiddenFieldData");
	var tFrom = [];
	var tTo = [];
	var tmpCollection;
	var tmpType;
	if(get(id).checked) {
		tmpCollection = get(fromContainerId).getElementsByTagName("input");
		for(var i=0;i<tmpCollection.length;i++) {
			if(tmpCollection[i].id!="") {
				if(exists(get(tmpCollection[i].id))) {
					tmpType = tmpCollection[i].type;
					if(tmpType=="hidden") {
						if(!tmpCollection[i].id.match(/_exclude/)) { tFrom.push(tmpCollection[i]); }
					}
				}
			}
		}
	}
	tmpCollection = get(toContainerId).getElementsByTagName("input");
	for(var i=0;i<tmpCollection.length;i++) {
		if(tmpCollection[i].id!="") { 
			if(exists(get(tmpCollection[i].id))) {
				tmpType = tmpCollection[i].type;
				if(tmpType=="hidden") {
					if(!tmpCollection[i].id.match(/_exclude/)) { tTo.push(tmpCollection[i]); }
				}
			}
		}
	}
	if(get(id).checked) {
		for(var i=0;i<tFrom.length;i++) {
			tmpType = get(tFrom[i].id).type;
			tmpValue = get(tFrom[i].id).value;
			get(tTo[i].id).value = get(tFrom[i].id).value; break;
		}
	} else {
		for(var i=0;i<tTo.length;i++) { 
		get(tTo[i].id).value=""; 
		}
	}
};

/* support for custom error messages */
ValidationObj.prototype.getCustomErrorMsg = function(id,label,whichCustom) {
	var formId = this.findParentForm(id);
	var customMessage = this.getProp("customMessages")[formId];
	var patterns = customMessage.patterns;
	for( var patternIdx=0, patternCheck=patterns.length; patternIdx<patternCheck; patternIdx++) {
		var patternTest = new RegExp(patterns[patternIdx].pattern);
		if(patterns[patternIdx].whichCustom.toLowerCase() === whichCustom.toLowerCase() && patternTest.test(id)) {
			return patterns[patternIdx].message;
		}
	}
	return ""; 
};

/* error marking */
ValidationObj.prototype.notificationExists = function(id) {
	//console.log("notificationExists");
	var t = get(id);
	return (exists(get("alerts_errors")) && exists(t))
};
ValidationObj.prototype.findErrorRegionDivIdByCollectionProp = function(errorCollectionProp, notFoundReturnValue) {
	var errorDetail = this.errorCollection[errorCollectionProp];
	if(exists(errorDetail)) {
		return errorDetail.errorRegionDivId
	}
	return notFoundReturnValue;
};
ValidationObj.prototype.createEmptyErrorElement = function(errorCollectionProp, currentErrorRegionDivId) {
	return this.errorCollection[errorCollectionProp] = { count : 0, errorRegionDivId : currentErrorRegionDivId, allIncludedElementIds : {} };
};
ValidationObj.prototype.addNotification = function(type,id,label,whichCustom) {	
	//console.log("addNotification");
	// supported types are alert, error, info, and success
	var errorCollectionProp = label.replace(/\W/g, "_");
	var errorDetail = this.errorCollection[errorCollectionProp];
	var currentErrorRegionDivId = this.findErrorRegionDivIdByCollectionProp(errorCollectionProp, id.toString() + '_e');
	if(!exists(errorDetail)) {
		errorDetail = this.createEmptyErrorElement(errorCollectionProp, currentErrorRegionDivId);
	}
	if(!exists(errorDetail.allIncludedElementIds[id])) {
		errorDetail.allIncludedElementIds[id] = errorCollectionProp;
		errorDetail.count ++;
	}
	if(!this.notificationExists(currentErrorRegionDivId)) {
		label = label.replace(/\*/g,"");
		var errorType = id.split("_")[0];
		   if(id.match("ffNum") || id.match("SMNum")) { errorType="loyaltyNum"; }
           if(id.match("ffPrgm")){ errorType="loyaltyProg"; }
		var msgs = getInnerHTML("alerts_errors");
		var customMsg = "";
		if(exists(this.getProp("customMessages"))) {
			customMsg = this.getCustomErrorMsg(id,label, ( exists(whichCustom) ? whichCustom : "" ) );
		}
		var message = "<div class=\""+type+"\" id=\"" + currentErrorRegionDivId + "\">";
		if(customMsg == "") {
			message += "The information entered for "+label+" below is not valid.";
			message += " ";
			switch(errorType) {
				case "name":
					message += "Please ensure it has at least 2 characters and contains only letters and spaces.";
					break;
				case "cc":
					message += "";
					break;
				case "birth":
					message += "Please enter a date in the past for the date of birth.";
					break;
				case "exp":
					message += "Please enter a date in the future for the expiration.";
					break;
				case "gender":
					message += "Please select one of the options for gender.";
					break;
				case "passport":
					message += "";
					break;
			    case "loyaltyNum":
					message += "Frequent flyer numbers must contain between 5 to 20 numbers.";
                    break;
                 case "loyaltyProg":
	                 message += "Please select an airline program from the list provided.";
                   break;
                 case "email":
	                 message += "Please make sure your email addresses match.";
                   break;
				default:
					break;
			}
		} else {
			message += customMsg;
		}
		message += "</div>";
		msgs += message;
		setInnerHTML("alerts_errors",msgs);
	}
};
ValidationObj.prototype.getErrorCollectionPropByElementId = function(id) {
	for(var errorProp in this.errorCollection) {
		var errorDetail = this.errorCollection[errorProp];
		for(var errorElementId in errorDetail.allIncludedElementIds) {
			if(errorElementId === id) {
				return errorDetail.allIncludedElementIds[errorElementId];
			}
		}
	}
	return null;

};
ValidationObj.prototype.removeNotification = function(id) {
	//console.log("removeNotification");
	setClassName(id,"");
	var removeErrorMessage = false;
	var errorRegionDivId = id + "_e";
	var errorCollectionProp = this.getErrorCollectionPropByElementId(id);
	var errorDetail = this.errorCollection[errorCollectionProp];
	if( exists(errorDetail) ) {
		if(exists(errorDetail.allIncludedElementIds[id])) {
			errorDetail.count --;
		}
		errorRegionDivId = errorDetail.errorRegionDivId;
		if(errorDetail.count === 0) { removeErrorMessage = true; }
		errorDetail.allIncludedElementIds[id] = null;
	}
	if(removeErrorMessage) {
		var msgNodes = get("alerts_errors").getElementsByTagName("div");
		for(var i=0;i<msgNodes.length;i++){
			if( msgNodes[i].id === errorRegionDivId ) { get("alerts_errors").removeChild(msgNodes[i]);}
		}
	}
};
ValidationObj.prototype.addFormAndLabelData = function(id) {
	var tmpId;
	this.labels = getByTagName("label");
	var fieldLabels = this.labels;
	this.forms = document.forms;
	this.numLabels = this.labels.length;
	this.numForms = this.forms.length;
	
}
ValidationObj.prototype.markError = function(id,whichCustom) {
	//console.log("markError");
	get(id).setAttribute('class','error');
	get(id).setAttribute('className','error'); /* for ie */

	if(!exists(this.labels)) { this.addFormAndLabelData(id); }
	var fieldLabels = this.labels;
	for(var i=0;i<fieldLabels.length;i++) {
		if(fieldLabels[i].getAttribute('for')==id || fieldLabels[i].getAttribute('htmlFor')==id) {
			fieldLabels[i].setAttribute('class','error');
			fieldLabels[i].setAttribute('className','error'); /* for ie */
			this.addNotification("error",id,fieldLabels[i].innerHTML,whichCustom);
		}
	}
};
ValidationObj.prototype.removeError = function(id) {
	//console.log("removeError");
	get(id).setAttribute('class','');
	get(id).setAttribute('className',''); /* for ie */
	if(!exists(this.labels)) { this.addFormAndLabelData(); }
	var fieldLabels = this.labels;
	for(var i=0;i<fieldLabels.length;i++) {
		if(fieldLabels[i].getAttribute('for')==id || fieldLabels[i].getAttribute('htmlFor')==id) {
			fieldLabels[i].setAttribute('class','');
			fieldLabels[i].setAttribute('className',''); /* for ie */
		}
	}
	this.removeNotification(id);
};

/* data validation functions */
ValidationObj.prototype.validateSelectField = function(id) {
	//console.log("validateSelectField");
	if(get(id).selectedIndex==0) { this.markError(id); return false; }
	else { this.removeError(id); return true; }
};
ValidationObj.prototype.validateName = function(id) {
	//console.log("validateName");
	var t = get(id);
	if(t.value == "" || t.value.length < 2 || t.value.match(/^([a-zA-Z][a-zA-Z\&\-\'\s]*|)$/) == null ) { this.markError(id); return false; }
	else { this.removeError(id);return true; }
};
ValidationObj.prototype.validateFirstname = this.validateName; /* alias for itineraries app */
ValidationObj.prototype.validateLastname = this.validateName; /* alias for itineraries app */

ValidationObj.prototype.validatePassportNum = function(id) {
	//console.log("validatePassportNum");
	var t = get(id).value;
	if(!t.value.match(/^[a-z0-9]+$/i)) { this.markError(id); return false; }
	else { this.removeError(id); return true; }
};

/*D9208617 start added validateDate function */

ValidationObj.prototype.validateDate = function(id) {
	var t = get(id);
	t.value = t.value.replace(/\s*/g,"");
	if(!t.value.match(/^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{4}$/)) { this.markError(id); return false; }
	else { this.removeError(id);return true; }
};

/*D9208617 end added validateDate function */

ValidationObj.prototype.validateBirthDate = function(id) {
	//console.log("validateBirthDate");
	var custDate;
	var dayField_Id; var monthField_Id; var yearField_Id; 
	var dayField; var monthField; var yearField;
	if(id.match(/day/) != null) {
		dayField_Id = id;
		monthField_Id = id.replace(/day/,"month");
		yearField_Id = id.replace(/day/,"year");
	} else if(id.match(/month/) != null) {
		dayField_Id = id.replace(/month/,"day");
		monthField_Id = id;
		yearField_Id = id.replace(/month/,"year");
	} else if (id.match(/year/) != null) {
		dayField_Id = id.replace(/year/,"day");
		monthField_Id = id.replace(/year/,"month");
		yearField_Id = id;
	} else {}
	dayField = get(dayField_Id).value;
	monthField = this.getMonthNum(get(monthField_Id).value);
	yearField = get(yearField_Id).value;

	if(this.curField == yearField_Id || (this.dayField !="" && this.monthField != "" && this.yearField != "")) { 
		if( this.validateSelectField(dayField) 
		&& this.validateSelectField(monthField) 
		&& this.validateSelectField(id) ) {
			var custDate = new Date();
			custDate.setYear(get(id).value);
			custDate.setDate(get(dayField).value);
			custDate.setMonth(this.getMonthNum(get(monthField).value));
			if(this.today<custDate) { 
				this.markError(dayField_Id); 
				this.markError(monthField_Id);
				this.markError(yearField_Id);
				return false;
			} else { 
				this.removeError(dayField_Id); 
				this.removeError(monthField_Id);
				this.removeError(yearField_Id);
				return true;
			}
		}
		return this.validateSelectField(id);
	}
	return true;
};
ValidationObj.prototype.validateExpirationDate = function(id) {
	//console.log("validateExpirationDate");
	var custDate;
	var dayField_Id; var monthField_Id; var yearField_Id; 
	var dayField; var monthField; var yearField;
	var maxDays;
	if(id.match(/day/) != null) {
		dayField_Id = id;
		monthField_Id = id.replace(/day/,"month");
		yearField_Id = id.replace(/day/,"year");
	} else if(id.match(/month/) != null) {
		dayField_Id = id.replace(/month/,"day");
		monthField_Id = id;
		yearField_Id = id.replace(/month/,"year");
	} else if (id.match(/year/) != null) {
		dayField_Id = id.replace(/year/,"day");
		monthField_Id = id.replace(/year/,"month");
		yearField_Id = id;
	} else {}
	if(exists(get(dayField_Id))) { dayField = get(dayField_Id).value; }
	monthField = this.getMonthNum(get(monthField_Id).value);
	yearField = get(yearField_Id).value;
	maxDays = 32 - new Date(yearField,monthField, 32).getDate();

	if (exists(get(dayField_Id))) {
		if( this.validateSelectField(dayField_Id) 
		&& this.validateSelectField(monthField_Id) 
		&& this.validateSelectField(yearField_Id) ) {
			custDate = new Date(yearField,monthField,dayField);
			if(this.today>custDate) { 
				this.markError(dayField_Id);
				this.markError(monthField_Id);
				this.markError(yearField_Id);
				return false;
			}
			else { 
				this.removeError(dayField_Id);
				this.removeError(monthField_Id);
				this.removeError(yearField_Id);
				return true;
			}
		} else { /* not all date fields have selections */ }
	} else {
		if(this.curField == yearField_Id || (this.curField == monthField_Id && yearField != "")) { 
			if( this.validateSelectField(monthField_Id) 
			&& this.validateSelectField(yearField_Id) ) {
				custDate = new Date(get(id).value, this.getMonthNum(get(monthField_Id).value),maxDays);
				if(this.today>custDate) { 
					this.markError(monthField_Id);
					this.markError(yearField_Id);
					return false;
				} else { 
					this.removeError(monthField_Id);
					this.removeError(yearField_Id);
					return true;
				}
			}
		} else {
			return this.validateSelectField(monthField_Id);
		}
	}
	return this.validateSelectField(id);
};

// this will likely be migrated to an aliased function as it does not support validating the ccid
ValidationObj.prototype.validateCCExpDateMulti = function(monthId,yearId,i) {
	var theMonth = get(monthId).value;
	var theYear = get(yearId).value;
	var expLabel = "month_exp_pax" + i + "_req";
	//alert(theYear + " " + this.today.getFullYear() + " " + parseInt(theMonth, 10) + " " + (this.today.getMonth()+1));
	if (theMonth == "" || theYear == "") {
		this.markError(monthId);
		this.markError(yearId);
		this.markError(expLabel);
		return false;
	} else if ( ( theYear <= this.today.getFullYear() ) && ( parseInt(theMonth, 10) < this.today.getMonth()+1 ) ) {
		this.markError(monthId);
		this.markError(yearId);
		this.markError(expLabel);
		return false;
	} else {
		this.removeError(monthId);
		this.removeError(yearId);
		this.removeError(expLabel);
		return true;
	}
};


ValidationObj.prototype.validateCCExpDate = function(monthId,yearId,expLabel) {
	//console.log("validateCCExpDate");
	var theMonth = get(monthId).selectedIndex+1;
	var theYear = get(yearId).value;
	var expLabel = expLabel;
	//alert(theYear + " " + this.today.getFullYear() + " " + (theMonth) + " " + (this.today.getMonth()+1));
	if (theMonth == "" || theYear == "") {
		this.markError(monthId);
		this.markError(yearId);
		this.markError(expLabel);
		return false;
	} else if ( ( theYear <= this.today.getFullYear() ) && ((theMonth) < this.today.getMonth()+1 ) ) {
		this.markError(monthId);
		this.markError(yearId);
		this.markError(expLabel);
		return false;
	} else {
		this.removeError(monthId);
		this.removeError(yearId);
		this.removeError(expLabel);
		return true;
	}
};

ValidationObj.prototype.validateBoolean =function(id) {
	//console.log("validateBoolean");
	if(get(id).checked) {
		this.removeError(id); return true;
	} else {
		this.markError(id); return false;
	}
};

ValidationObj.prototype.validateGender = function(id) {
	//console.log("validateGender");
	if(get(id).value=="") { this.markError(id);return false; }
	else { this.removeError(id); return true; }
};
ValidationObj.prototype.validateRadioButton =function(id) {
	/* the ids are the same on radio inputs. needs more work or grouping. */
};

ValidationObj.prototype.validateGlobalPhone = function(reqPhoneObj) {
		
	var error = false;
	
	if(reqPhoneObj.phoneList.primaryPhone){
		if(!this.validatePhoneCC("primaryCountryCode")){
			error = true;
		}
		if(!this.validatePhoneArea("primaryAreaCode")){
			error = true;
		}
		if(!this.validatePhoneNumber("primaryNumber")){
			error = true;
		}
		if(reqPhoneObj.phoneList.primaryPhone.primExt != ""){
			if(!this.validatePhoneExt("primaryExt")){
				error = true;
			}
		}
	}
	
	if(reqPhoneObj.phoneList.alternatePhone){
		if(reqPhoneObj.phoneList.alternatePhone.altCC != ""){
			if(!this.validatePhoneCC("altCountryCode")){
				error = true;
			}
		}
		if(reqPhoneObj.phoneList.alternatePhone.altArea != ""){
			if(!this.validatePhoneArea("altAreaCode")){
				error = true;
			}
		}
		if(reqPhoneObj.phoneList.alternatePhone.altPhone != ""){
			if(!this.validatePhoneNumber("altNumber")){
				error = true;
			}
		}
		if(reqPhoneObj.phoneList.alternatePhone.altExt != ""){
			if(!this.validatePhoneExt("altExt")){
				error = true;
			}
		}
		
	}
	
	return error;
	
};


ValidationObj.prototype.validateGlobalAddress = function(reqAddrObj){

	var error = false;
	
	if(reqAddrObj.addrLine1StreetName) {
		if(!this.validateStreet("addr1")) {
			error = true;
		}
	}
	if(reqAddrObj.addrLine2RoomApartment) {
		if(!this.validateStreet("addr2")) { 
			error = true;
		}
	}
	if(reqAddrObj.cityCountyWard) {
		if(!this.validateCity("cityCountyWard")) { 
			error = true;
		}
	}
	if(reqAddrObj.stateProvCode) {
		if(!this.validateCity("stateProv")) {
			error = true;	
		}
	}	
	if(reqAddrObj.districtTownVillage) {
		if(!this.validateCity("districtTownVillage")) {
			error = true;	
		}
	}
	if(reqAddrObj.areaTerritoryPrefecture) {
		if(!this.validateStreet("areaTerritoryPrefecture")) {
			error = true;	
		}
	}
	if(reqAddrObj.postalCode) {
		if(!this.validatePostalCode("postal")) {
			error = true;	
		}
	}
	
	return error;		
};
/******* Global Phone Validation Methods ***************/
ValidationObj.prototype.validatePhoneNumber = function(id) {
	//console.log("validatePhoneNumber");
	var t = get(id);
	//t.value.replace("+","");
	//if(!t.value.match(/[\d\-\.]{10,}/)) { this.markError(id); return false; } 
	if(!t.value.match(/^[0-9- ]{7,20}$/))
	{ this.markError(id); return false; }
	else { this.removeError(id);return true; }
};
ValidationObj.prototype.validatePhoneCC = function(id){
	var t = get(id);
	if(t.value != "" && t.value.match(/[0-9\+]{1,10}/)) { this.removeError(id);return true;} 
	else { this.markError(id); return false; }
};
ValidationObj.prototype.validatePhoneArea = function(id){
	var t = get(id);
	if(t.value != "" && t.value.match(/[0-9]{3,5}/)) { this.removeError(id);return true; } 
	else { this.markError(id); return false; }
};
ValidationObj.prototype.validatePhoneExt = function(id){
	var t = get(id);
	if(t.value != "" && t.value.match(/[0-9\+]{0,5}/)) { this.removeError(id);return true; } 
	else { this.markError(id); return false; }
};


/******* Global Address Validation Methods ************/
ValidationObj.prototype.validateCity = function(id) {
	//console.log("validateCity");
	var t = get(id);
	if(t.value == "" || t.value.match(/[^-||\d||\w||\s]/)!=null) { this.markError(id); return false; } 
	else { this.removeError(id);return true; }
};
ValidationObj.prototype.validateStreet = function(id) {
	//console.log("validateStreet");
	var t = get(id);
	if(t.value == "" || t.value.match(/[^-||,||\d||\w||\s]\#/)!=null) { this.markError(id); return false; } 
	else { this.removeError(id); return true; }
};
ValidationObj.prototype.validatePostalCode = function(id) {
	//console.log("validateStreet");
	var t = get(id);
	if(t.value == "" || t.value.match(/[\d\w\-\s\.]{4,12}/)==null) { this.markError(id); return false; } 
	else { this.removeError(id); return true; }
};
ValidationObj.prototype.validateEmail = function(id) {
	//console.log("validateEmail");
	var t = get(id);
	if(t.value == "" || (t.value.match(/\w+@[a-zA-Z_]+?\.[a-zA-Z]{1}[a-zA-Z0-9]+/)==null) ) { this.markError(id); return false; }
	else { this.removeError(id); return true; }
};
ValidationObj.prototype.validateSMNum = function(id) {
	//console.log("validateSMNum");
	var t = get(id);
	if(this.isNumber(id)) {
		if(t.value == "" || t.value.match(/\d{10}/)==null) { this.markError(id); return false; }
		else { this.removeError(id); return true; }
	}
	return false;
};
ValidationObj.prototype.validatePinFormat = function(id) {
	//console.log("validatePinFormat");
	var t = get(id);
	if(this.isNumber(id)) {
		if(t.value.length!=4) { this.markError(id); return false; }
		else { this.removeError(id); return true; }
	}
	return false;
};
ValidationObj.prototype.validateCCID = function(id) {
	//console.log("validateCCID");
	var t = get(id);
	if(t.value.match(/[^\d]/) == null  && t.value.match(/\d{3,4}/) != null ) { 
		this.removeError(id); 
		return true; 
	} else { 
		this.markError(id); return false;
	}
};
ValidationObj.prototype.isCCNumMasked = function(ccNum, ccType) {
	ccNum = ccNum.replace(/^\s+/,"");
	switch(ccType) {
		case "AX": return ccNum.match(/^\*{11}\d{4}$/); // American Express: length 15
		case "VI":  // VI length 16
		case "CA": // CA: length 16
		case "DS": // Diners: length 16
		case "XS": // XS: length 16
		case "BB": // BB: length 16
		case "EC": // EC : length 16
		case "JC": // JC : length 16
		case "BF": // BF: length 16
		case "CG": // CG: length 16
		case "MD": // MD: length 16
		case "DL": // DL : length 16
			return ccNum.match(/^\*{12}\d{4}$/);
		case "TP": return ccNum.match(/^\*{11,12}\d{4}$/); // TP : length 16, 15
		case "ER": // ER : length 14
		case "DC": // Discover: length 14
		case "CB": // CB : length 14
			return ccNum.match(/^\*{10}\d{4}$/);
		default: return false;
	}
}
ValidationObj.prototype.validateCCNum = function(id, ccType) {
	//console.log("validateCCNum");
	var ccNum = get(id).value;
	if(ccNum === "") { this.markError(id); return false;}
	if(ccType == "AI" || ccType == "PA" || ccType == "UA") { ccType= "TP"; }
	if(ccType == "AT" || ccType == "TC") { ccType= "DC"; }
	if(ccType == "BR") { ccType= "DS"; }
	if(ccType == "CD") { ccType= "CA"; }
	if(this.isCCNumMasked(ccNum, ccType)) {
		this.removeError(id);
		return true;
	}
	ccNum = ccNum.replace(/\D/g, "");
	if (this.doesCCNumPassesLuhn(ccNum) ) {
		switch(ccType) {
			case "AX": if (ccNum.match(/^3[4,7]\d{13}$/)== null) { this.markError(id); return false;  } else { this.removeError(id); return true; }// American Express: length 15, prefix 34 or 37.
			case "VI": if (ccNum.match(/^4\d{15}$/) == null) { this.markError(id); return false;  } else { this.removeError(id); return true; } // VI length 16, prefix 4.
			case "CA": if (ccNum.match(/^5[1-5]\d{14}$/) == null) { this.markError(id); return false;  } else { this.removeError(id); return true; } // CA: length 16, prefix 51-55.
			case "DS":  if (ccNum.match(/^6[0,5]\d{14}$/) == null) { this.markError(id); return false;  } else { this.removeError(id); return true; } // Diners: length 16, prefix 60, 65
			case "DC": if (ccNum.match(/^3[0,6]\d{12}$/) == null) { this.markError(id); return false;  } else { this.removeError(id); return true; } // Discover: length 14, prefix 30, 36.
			case "CB": if (ccNum.match(/^3\d{13}$/) == null) { this.markError(id); return false;  } else { this.removeError(id); return true; } // CB : length 14, prefix 3
			case "TP": if (ccNum.match(/\d{15,16}$/) == null) { this.markError(id); return false; } else { this.removeError(id); return true; } // TP : length 16, no prefix
			case "XS": if (ccNum.match(/^5[1-5]\d{14}$/) == null) { this.markError(id); return false;  } else { this.removeError(id); return true; } // XS: length 16, prefix 51-55.
			case "BB": if (ccNum.match(/^4\d{15}$/) == null) { this.markError(id); return false;  } else { this.removeError(id); return true; } // BB: length 16, prefix 4.
			case "BF": if (ccNum.match(/^4\d{15}$/) == null) { this.markError(id); return false;  } else { this.removeError(id); return true; } // BF: length 16, prefix 4.
			case "CG": if (ccNum.match(/^4\d{15}$/) == null) { this.markError(id); return false;  } else { this.removeError(id); return true; } // CG: length 16, prefix 4.
			case "MD": if (ccNum.match(/^5[1-5]\d{14}$/) == null) { this.markError(id); return false;  } else { this.removeError(id); return true; } // MD: length 16, prefix 51-55.
			case "DL": if (ccNum.match(/^2006\d{12}$/) == null) { this.markError(id); return false;  } else { this.removeError(id); return true; } // DL : length 16, prefix 2006
			case "ER": if (ccNum.match(/\d{14}$/) == null) { this.markError(id); return false;  } else { this.removeError(id); return true; } // ER : length 14, no prefix
			case "EC": if (ccNum.match(/\d{16}$/) == null) { this.markError(id); return false;  }	else { this.removeError(id); return true; } // EC : length 16, no prefix
			case "JC": if (ccNum.match(/^3\d{15}$/) == null) { this.markError(id); return false;  } else { this.removeError(id); return true; } // JC : length 16, prefix 3
			default: this.removeError(id); return true;
		}
	} else {
		this.markError(id); return false;
	}
};
ValidationObj.prototype.validateCreditCard = function(id) {
	//console.log("validateCreditCard "+ id);
	var rtn = false;
	var valType;
	var ccType_Id; var ccNum_Id; var ccCCID_Id; // field ids
	var ccType; var ccNum; var ccCCID; // field values
	if(id.match(/num/) != null || id.match(/ccid/) != null || id.match(/type/) != null) {
		if(id.match(/type/) != null) {
			valType = "type";
			ccType_Id = id;
			ccCCID_Id = id.replace(/type/,"ccid");
			ccNum_Id = id.replace(/type/,"num");
		} else if(id.match(/num/) != null) { //if the id is for the cc number
			valType = "num";
			ccNum_Id = id;
			ccType_Id = id.replace(/num/,"type");
			ccCCID_Id = id.replace(/num/,"ccid");
		} else if (id.match(/ccid/) != null) { // else the id is for the ccid
			valType = "ccid";
			ccType_Id = id.replace(/ccid/,"type") + "_req";
			ccNum_Id = id.replace(/ccid/,"num") + "_req";
		} else {}
		// the assumption is that the credit card number is provided with the above naming
		// conventions, the field exists that provides the credit card type
		ccType = get(ccType_Id).options[parseInt(get(ccType_Id).selectedIndex)].value;
		ccNum = get(ccNum_Id).value;
		switch(valType) {
			case "type":
				if(ccType != "" && ccNum != "") { 
					rtn = this.validateCCNum(ccNum_Id, ccType);
					if(rtn) { 
						this.removeError(ccType_Id);
						this.removeError(ccNum_Id);
						return rtn;
					} else {
					}
				} else if (ccType == "" && ccNum != "") { 
					this.markError(ccType_Id);
					return false;
				} else {
				}
				break;
			case "num":
				if(ccType != "" && ccNum != "") { 
					rtn = this.validateCCNum(ccNum_Id, ccType);
					if(rtn) { 
						this.removeError(ccType_Id);
						this.removeError(ccNum_Id);
						return rtn;
					}
				} else if (ccType != "" && ccNum == "") { 
					this.markError(ccType_Id);
					this.markError(ccNum_Id);
					return false;
				} else {}
				break;
			case "ccid":
				if(this.curField == id  && exists(get(ccCCID_Id))) {
					if(this.requiresCCID(ccType)) { 
						return this.validateCCID(id);
					} else {
						return this.isNumber(id);
					}
				}
				break;
			default:
				break;
		}
	}  else { 
		//console.log("the field id "+ id +" does not contain num, ccid, or type");
		return false;
	}
};
ValidationObj.prototype.validateETicketNum = function(id) {
	//console.log("validateETicketNum");
	var t = get(id);
	t.value = this.removeSpaces(t.value);
	
//	if(
//		t.value = t.value.replace(/\s*/g,"");
//		if(t.value != ""&&t.value.match(/^006\d{10}$/)) { get('eTicketNumLabel').innerHTML = '&nbsp;eTicket #'; return true; }
//			 if(t.value != ""&&t.value.match(/\d{10}$/)) { get('eTicketNumLabel').innerHTML = '&nbsp;eTicket #'; return true; }
//	}
//	get('eTicketNumLabel').innerHTML = '<img src="/images/icons/error_x.gif" width="19" height="19" alt="" border="0" align="absmiddle" /> <span class="cpyError">eTicket #</span>';
//	showDiv('validationFormError');
//	get('validationFormError').innerHTML = '<p class="cpyError" style="padding-top:5px;padding-bottom:5px;"><img src="/images/icons/error_x.gif" width="19" height="19" alt="" border="0" align="absmiddle" />You have entered invalid information in one or more fields below.</p>';
//	return false;
};
ValidationObj.prototype.validateRedressNumber = function(id) {
	//console.log("validateETicketNum");
	var t = get(id);
	t.value = this.removeSpaces(t.value);
	t.value = this.stripBadChars(t.value);
	if(t.value.length > 0 && t.value.length < 14 && t.value.match(/^[a-z0-9]+$/i)){
		this.removeError(id); return true; 
	} else { 
		this.markError(id); return false; 
	}
};
ValidationObj.prototype.validateSecureName = function(id) {
	var t = get(id);
	if(t.value.match(/^[a-z]+[a-z\'\-\s]+$/i)){
		this.removeError(id); return true; 
	} else { 
		this.markError(id); return false; 
	}
}

/*

ValidationObj.prototype.validateFields = function(fieldArray) {
	//console.log("validateFields");
	var submitForm = true;
	submitForm = true;
	for(i=0;i<fieldArray.length;i++){
		var tempProp = fieldArray[i].toString();
		var tempArray = tempProp.split(',');
		for(j=0;j<tempArray.length;j++){
			if(tempArray[j + 1] == "CCType"){
				var tempString = this.validateCCType(tempArray[j], tempArray[j+2]);
				if(!tempString){ submitForm = false; }
			} else if(tempArray[j+1]) {
				var tempString = this.validateField(tempArray[j], tempArray[j+1]);
				if(!tempString){ submitForm = false; }
			} else {}
		}	
	}
	if(submitForm){ formName.submit(); }
}

/*
	match two values
	get ie working.
*/

ValidationObj.prototype.validateField = function(id, type) { 
	//console.log("validateField "+id+", data type of "+type);
	var validationType = type;
	if(validationType=="day"||validationType=="month"|| validationType=="year") { validationType = id.split("_")[1]; }
	else if(validationType=="genderm"||validationType=="genderf") { validationType = "gender"; }
	else if(validationType=="booleant"||validationType=="booleanf") { validationType = "boolean"; }
	else if(validationType=="fname"||validationType=="lname") { validationType = "name"; }
	else if(validationType=="ETicketNum") {validationType = "eticket"; }
	else { /* doNothing() */ }
	if(exists(id)) {
		switch(validationType.toLowerCase()) {
			// name, cc, day, month, year, gender, passport 
			case "name": get(id).value = this.stripBadChars(get(id).value);return this.validateName(id);
			case "cc": if(get(id).type == "text" || get(id).type == "textarea" ) { get(id).value = this.stripBadChars(get(id).value); } return this.validateCreditCard(id);
			case "gender": return this.validateGender(id);
			case "boolean": return this.validateBoolean(id); 
			case "passport": get(id).value = this.stripBadChars(get(id).value);return this.validatePassportNum(id);
			case "birth": return this.validateBirthDate(id);
			case "exp": return this.validateExpirationDate(id);
			case "num": get(id).value = this.stripBadChars(get(id).value);return this.isNumber(id);
			case "pin": return this.validatePinFormat(id);
			case "country": return this.validateSelectField(id);
			case "state":  return this.validateSelectField(id);
			case "phone":  get(id).value = this.stripBadChars(get(id).value);return this.validatePhoneNumber(id);
			case "city":  get(id).value = this.stripBadChars(get(id).value);return this.validateCity(id);
			case "street":  get(id).value = this.stripBadChars(get(id).value);return this.validateStreet(id);
			case "freeform": get(id).value = this.stripBadChars(get(id).value);return true; /* update if needed */
			case "validateRadioButton": return this.validateRadioButton(id); /* function needs writing */
			case "mmslashddslashyyyydate": return this.isDataMMSlashDDSlashYYYY(id) ;
			case "email": return this.validateEmail(id);
			case "smnum": return this.validateSMNum(id);
			case "eticket": return this.validateETicketNum(id); break;
			//case "PINNum": return this.validatePINNum(id); break;
			//case "ConfirmNum": return this.validateConfirmNum(id); break;
			default: return true;
		}
	}
};
ValidationObj.prototype.validateForm = function(id) { /* validates that all fields with data are correct */
	//console.log("validateForm");
	var oForm = document.forms[id];
	for(var i=0;i<oForm.length;i++) {
		if(!this.validateField(oForm[i].id,oForm[i].id.split("_")[0])) { 
			//console.log(oForm[i].id + " failed to validate as datatype "+ oForm[i].id.split("_")[0]);
			return false; 
		}
	}
	return true;
};
ValidationObj.prototype.checkForm = function(id) {
	//console.log("checkForm");
	this.curField = id;
	var rtn = true;
	var parentFormId = this.findParentForm(id);
	var oForm = document.forms[parentFormId];
	for(var i=0;i<oForm.length;i++) {
		if(oForm.elements[i].id.match(/_req/)) { /* check if field is required */
			switch(oForm.elements[i].type) {
				case "text":  if(oForm[i].value=="") { rtn=false; }; break; /* catches only empty fields without a value */
				case "textarea":  if(oForm[i].value=="") { rtn=false; }; break;  /* catches only empty fields without a value */
				case "select-one": if(oForm[i].selectedIndex==0) { rtn=false; }; break; /* catches if left at index of 0 */
				//case "select-multiple": if(oForm[i].selectedIndex==0) { rtn=false; }; break;  /* catches if left at index of 0 */
				case "radio": if(!oForm[i].checked) { rtn=false; }; break;
				case "checkbox": if(!oForm[i].checked) { rtn=false; }; break;
				case "password": break;
				case "hidden": if(oForm[i].value=="") { rtn=false; }; break;
				default: break;
			}
		} else { /* handle non-required fields */
			switch(oForm.elements[i].type) {
				case "text":  if(oForm[i].value=="") { rtn=true; } else; break; /* catches only empty fields without a value */
				case "textarea":  if(oForm[i].value=="") { rtn=true; }; break;  /* catches only empty fields without a value */
				case "select-one": if(oForm[i].selectedIndex==0) { rtn=true; }; break; /* catches if left at index of 0 */
				//case "select-multiple": if(oForm[i].selectedIndex==0) { rtn=false; }; break;  /* catches if left at index of 0 */
				case "radio": if(!oForm[i].checked) { rtn=true; }; break;
				case "checkbox": if(!oForm[i].checked) { rtn=true; }; break;
				case "password": break;
				case "hidden": if(oForm[i].value=="") { rtn=true; }; break;
				default: break;
			}
			if(oForm.elements[i].id.match(/replicate/)) {
				/* put code here to copy fields from one to another */
			}
		}
		if(!rtn) { break; }
	}
	if(!rtn) {
		this.validateField(id,id.split("_")[0]);
	} else {
		if(this.validateForm(parentFormId)) { this.enableForm(parentFormId); /*this.submitForm(parentFormId);*/}
	}
	return rtn;
};

ValidationObj.prototype.enableForm = function(id) {
	//console.log("enableForm");
	var oForms = document.forms;
	for(var i=0;i<oForms.length;i++) {
		if(exists(oForms[i].id) && oForms[i].id == id) {
			for(var j=0;j<oForms[i].length;j++) {
				if(oForms[i][j].type=="submit" && oForms[i][j].value != "Start Over") { 
					oForms[i][j].disabled="";
					setClassName(oForms[i][j].id,getClassName(oForms[i][j].id).split("_")[0]);
					oForms[i].action = this.getProp(id+"_action");
					return true;
				}
			}
		}
	}
};
ValidationObj.prototype.submitForm = function(id) {
	//console.log("submitForm");
	var oForm = document.forms[id];
	oForm.submit();
};

/* .init() disables the continue button and adds "handleField()" as the onchange handler */
ValidationObj.prototype.init = function() { 
	//console.log("init");
	var hasButton = false;
	this.addFormAndLabelData();
	var oForms = document.forms;
	if (exists(this.getProp("disable")) && this.isDisabled("init")) { return; }
	for(var i=0;i<oForms.length;i++) {
		hasButton = false;
		if(exists(oForms[i]) && exists(oForms[i].id) && oForms[i].id !="") { 
			for(var j=0;j<oForms[i].length;j++) {
				if(exists(oForms[i][j].id) && oForms[i][j].type=="submit" && oForms[i][j].value != "Start Over" && oForms[i][j].value != "Back") { 
					/* if the desire is to not disable buttons for form submissions */
					if (!this.isDisabled("disabled_buttons")) {
						oForms[i][j].disabled="disabled";
						setClassName(oForms[i][j].id,getClassName(oForms[i][j].id)+"_disabled");
						hasButton = true;
					}
				} else { 
					oForms[i][j].onchange = handleField;
				}
			}
			if(hasButton) { /* in order to properly disable the buttons we remove the form action as well */
				this.setProp(oForms[i].id+"_action",oForms[i].action);
				oForms[i].action = "";
			}
		}
	}
};

// create instance of Object
var valObj = new ValidationObj();


// inline handlers for events and initialization
function handleField() { 
	//console.log("handleField: " + this.id);
	valObj.checkForm(this.id);
};
function addClientSideValidation() { 
	//console.log("addClientSideValidation");
	valObj.init();
};

// add form processing to page on load
//addEvent(window,"load",addClientSideValidation,false);


/* merch_paxInfo.js, reference removed for merchandising isolation */
/* ******************** end core js for booking ******************** */

/* on select flights in prod */

/* pwm_js.js.js */
/******* Begin booking/javascripts/pwm_js.js ***********/
	//DOM Elements
	var form_control ;
	var passenger_price ;
	var passenger_miles ;
	var itinerary_price ;
	var itinerary_miles ;
	//Data Elements
	var passengers ;
	var member_status ;
	var available_miles ;
	var itinerary_fare ;
	var addMerchCost = new Boolean();
function updateScreenView(pwm_select, pwm_ppp, pwm_mpp, pwm_tp, pwm_tm, itin_noPax, itin_medallion_status, pwm_balance, itin_tp, costPlusMerch){
	//DOM Elements
	form_control = get(pwm_select);
	passenger_price = get(pwm_ppp);
	passenger_miles = get(pwm_mpp);
	itinerary_price = get(pwm_tp);
	itinerary_miles = get(pwm_tm);
	addMerchCost = costPlusMerch;
	//Data Elements
	passengers = parseInt(itin_noPax);
	member_status = itin_medallion_status;
	available_miles = parseInt(pwm_balance);
	itinerary_fare =  itin_tp;
	//itinerary fare must be converted to proper format
    if(itinerary_fare.charAt(0) == '$'){
		itinerary_fare = itinerary_fare.substring(1, itin_tp.length);
    }
	itinerary_fare = itinerary_fare.replace(/\,/g,'');
	itinerary_fare = parseFloat(itinerary_fare);
	if(passenger_price){
		passenger_price.innerHTML = "$" + calculatePaxPrice(form_control, itinerary_fare);
	}
	if(passenger_miles){
		passenger_miles.innerHTML = formatNumber(calculatePaxMiles(form_control, available_miles),0,',','','','','');
	}
	if(itinerary_price){
		itinerary_price.innerHTML = "$" + calculateItinPrice(form_control, itinerary_fare, passengers);
	}
	if(itinerary_miles){
		itinerary_miles.innerHTML = formatNumber(calculateItinMiles(form_control, available_miles, passengers),0,',','','','','');
	}
	setHiddenFields(form_control);
	//Display or Hide '+ miles off' discount
	if(form_control.selectedIndex == 0 || form_control.selectedIndex == 1){
		//NO PWM selection, turn on One-Click Purchase Functionality
		checkOneClick(true);
		// No PWM selection, turn on first/biz upsell
		showUpsellChoice();
		//Miles off display
		hide('passenger_miles_off');
		hide('itinerary_miles_off');
		if(get('tss_passenger_miles_off')){
			hide('tss_passenger_miles_off');
		}
		if(get('tss_itinerary_miles_off')){
			hide('tss_itinerary_miles_off');					
		}
	} else {
		//Miles off display
		if(get('passenger_miles_off')){	
			get('passenger_miles_off').style.display = 'inline';
		}
		if(get('passenger_miles_off')){	
			get('itinerary_miles_off').style.display = 'inline';
		}
		if(get('tss_passenger_miles_off')){
			get('tss_passenger_miles_off').style.display = 'inline';				
		}
		if(get('tss_itinerary_miles_off')){
			get('tss_itinerary_miles_off').style.display = 'inline';				
		}
		try {
         	//PWM selected, turn off One-Click Purchase Functionality
			checkOneClick(false);
			//PWM selected, turn off First/Biz upsell
			if (isUpsellSelected() == false) {
				hideUpsellChoice();
			}
		} catch (e) {}
	}
	if(get('pwm_MQM') && get('pwm_noMQM')){
		if(form_control.selectedIndex == 0 || form_control.selectedIndex == 1){
			show('pwm_MQM');
			hide('pwm_noMQM');
		} else {
			hide('pwm_MQM');
			show('pwm_noMQM');
		}
	} 
	try {
		if (typeof(resizeItineraryIframe) !== "undefined") {
			resizeItineraryIframe();
		}
		if (window.parent !== window && typeof(window.parent.updateForPWM) !== "undefined") {
			window.parent.updateForPWM.udpateForPWM(calculateItinMiles(form_control, available_miles, passengers), calculateItinPrice(form_control, itinerary_fare, passengers));
		}
	} catch(e) {}
}

function calculatePaxPrice(form_control, itinerary_fare){
	var selectedDiscount = form_control.selectedIndex;
	selectedDiscount = form_control.options[selectedDiscount].value;
	if(selectedDiscount.match("_")){
		selectedDiscount = selectedDiscount.split("_")[1];
	}
	if(selectedDiscount.match("-")){
		selectedDiscount = selectedDiscount.split("-")[1];
	}
	selectedDiscount = parseFloat(selectedDiscount);
	selectedDiscount = parseFloat(itinerary_fare) - selectedDiscount;
	selectedDiscount = formatTo(selectedDiscount, 2, 1);	
	return selectedDiscount;
}

function calculatePaxMiles(form_control, available_miles){
	var selectedDiscount = form_control.selectedIndex;
	selectedDiscount = form_control.options[selectedDiscount].value;
	selectedDiscount = selectedDiscount.split("_")[0];
	return selectedDiscount;
}

function calculateItinPrice(form_control, itinerary_fare, passengers){
	var ItinPrice = calculatePaxPrice(form_control, itinerary_fare) * parseInt(passengers);
  	// calculate additional costs for merchandising items 
	if(addMerchCost){
  		var merchCost = get('costPlusMerch').value;
  		merchCost = merchCost.split(" ")[0];
		merchCost = merchCost.substring(1, merchCost.length);
		merchCost = merchCost.replace(/\,/g,'');
		merchCost = parseFloat(merchCost);
		ItinPrice = ItinPrice + merchCost;
  	}
	ItinPrice = formatTo(ItinPrice, 2, 1);
	return ItinPrice;
}

function calculateItinMiles(form_control, available_miles, passengers){
	var ItinMiles = calculatePaxMiles(form_control, available_miles) * parseInt(passengers);
	return ItinMiles;
}

function setHiddenFields(form_control){
	var selectedDiscount = form_control.selectedIndex;
	if(get('hidden_pwm_index_selected')){
		get('hidden_pwm_index_selected').value = selectedDiscount;
	}
}

function storeChoice(){
	var formElement = get('pwmSelectionForm');
	var formName = formElement.name;
	var formAction = formElement.action;
	retrieveURL(formAction, formName);
}

function retrieveURL(url,nameOfFormToPost) {
	//convert the url to a string
	url=url+getFormAsString(nameOfFormToPost);
	//Do the AJAX call
	if (window.XMLHttpRequest) { 
	// Non-IE browsers
		req = new XMLHttpRequest();
		req.onreadystatechange = processStateChange;
		try {
			req.open("GET", url, true); 
		} catch (e) {
			alert("Server Communication Problem\n"+e);
		}
		req.send(null);
	} else if (window.ActiveXObject) {
		// IE
		req = new ActiveXObject("Microsoft.XMLHTTP");
		if (req) {
			req.onreadystatechange=processStateChange;
			req.open("GET", url, true);
			req.send();
		}
	}
}

function getFormAsString(formName){
	//Setup the return String
	returnString ="";
	//Get the form values
	formElements=document.forms[formName].elements;
	//loop through the array, building up the url
	//in the format '/strutsaction.do&name=value'
	for(var i=formElements.length-1;i>=0; --i ){
	    //we escape (encode) each value
        returnString+="&" 
        +escape(formElements[i].name)+"=" 
        +escape(formElements[i].value);
	}
	return returnString; 
}

function processStateChange() {
	if (req.readyState == 4) { // Complete
	    if (req.status != 200) { // OK response
			alert("Problem with server response:\n " + req.statusText);
    	}
	}
}

function update(){
	var sm_balance = get('pwm_balance').innerHTML;
	var total_price = get('pwm_tpp').innerHTML;
	var no_pax = get('pwm_noPax').innerHTML;
	updateScreenView('pwm_select', 'pwm_ppp', 'pwm_mpp', 'pwm_tp', 'pwm_tm', no_pax, 'silver medallion', sm_balance, total_price);
	storeChoice();
}

function checkOneClick(visible){
	if(exists(get('express_purchase'))){
		visible ? get('express_purchase').style.display = 'block' : get('express_purchase').style.display = 'none';
		if(exists(get('continue_button'))) {
			visible ? get('continue_button').value = 'Review and Purchase' : get('continue_button').value = 'Continue';
		}
		if(exists(get('continue_button_top'))) {
			visible ? get('continue_button_top').value = 'Review and Purchase' : get('continue_button_top').value = 'Continue';
		}
		if(exists(get('continue_button_bottom'))) {
			visible ? get('continue_button_bottom').value = 'Review and Purchase' : get('continue_button_bottom').value = 'Continue';
		}
		visible ? get('continue_button').value = 'Review and Purchase' : get('continue_button').value = 'Continue';
	}
}
/******* End booking/javascripts/pwm_js.js ***********/


/* upsell.js */

var upsell_why_msg = 'components/booking/pitins/firstUp.jsp';
var upsell_width = 400;
var upsell_height = 150;
var upsellExists = false;

function hideUpsellChoice() {
	hide('upsellchoice');
	hide('upsellnote');
   hide('upsellPWMnote');
	var box = eval(get('upsellSelectBox'));
	if (box != null) {
		box.checked = false;
	}
}

function showUpsellChoice() {
   if (upsellExists == true) {
      show('upsellchoice');
      show('upsellPWMnote');
   } else {
      hide('upsellPWMnote');
   }
}

function setUpsellWhyMsg(upsellItin) {
	upsell_width = 400;
	upsell_height = 150;
	if (upsellItin.bizElite == true) {
		if (upsellItin.hasLieFlatSeats == true) {
			upsell_why_msg = 'components/booking/pitins/busLieFlatUp.jsp';
			upsell_width = 500;
			upsell_height = 223;
		} else {
			upsell_why_msg = 'components/booking/pitins/busUp.jsp';
		}
	} else {
		upsell_why_msg = 'components/booking/pitins/firstUp.jsp';
	}
}

function setUpsellCabin(upsellItin) {
	var upselCabin =  'First Class'; 
	if (upsellItin.bizElite == true) {
		upselCabin = 'BusinessElite';
	}
	setInnerHTML('upsell_cabin1', upselCabin);
	setInnerHTML('upsell_cabin2', upselCabin);
	setInnerHTML('upsell_cabin3', upselCabin);
	setInnerHTML('upsell_cabin4', upselCabin);
}

function setUpsellCoachFltsNote(upsellItin) {
	var coachFlts = null;

	var segments = upsellItin.segmentDWRs;
	for( var i=0; i < segments.length;i++ ) {
		var legDWRs = segments[i].legDWRs;
		for(var legNbr=0; legNbr < legDWRs.length; legNbr++ ) {
			if (legDWRs[legNbr].coach == true) {
				var legText = legDWRs[legNbr].displayAirlineName + ' '  + legDWRs[legNbr].flightNbr + '(' + legDWRs[legNbr].departureCity.airportCode  + ' to ' +  legDWRs[legNbr].arrivalCity.airportCode + ')';
				if (coachFlts == null) {
					coachFlts = '';
				} else {
					coachFlts = ', ';
				}
				coachFlts = coachFlts+ legText;
			}
		}
	}
	if (coachFlts != null) {
		setInnerHTML('upsell_coach_flts', coachFlts);
		show('upsellnote');
	} else {
       hide('upsellnote');
    }
}

function processUpsellResponse(upsellItin) {
    upsellExists = false;
    upsellCallinProgress = false;
	try {
        if (ignoreUpsellResponse) {
           ignoreUpsellResponse = false;
        } else if (upsellItin != null) {
            upsellExists = true;
			   setUpsellWhyMsg(upsellItin);
			   setUpsellCabin(upsellItin);
			   setInnerHTML('upsellPriceDiff', upsellItin.upsellPriceDiff);
			   setUpsellCoachFltsNote(upsellItin);
			   showUpsellChoice();
            show('upsellPWMnote');
         try {
            omnitureUpsell(upsellItin);
         } catch (ex) { }
		}
	} catch (e) {
		hideUpsellChoice();
	}
}


function handleUpsellError() {
   upsellExists = false;
   upsellCallinProgress = false;
   ignoreUpsellResponse = false;
   hideUpsellChoice();
}

function isUpsellSelected() {
	var upsellSelected = false;
	var box = eval(get('upsellSelectBox'));
	if (box != null) {
		if (box.checked == true) {
			upsellSelected = true;
		}
	}
    return upsellSelected;
}

function upsellSelect(upsellSelected) {
	if (upsellSelected == true) {
		setClassName('upsellchoice','selected');
		//hide('pwmOption');
	} else {
		setClassName('upsellchoice','');
		//show('pwmOption');
	}
}

function shoppingFlowUpsellSelect() {
	var upsellSelected = isUpsellSelected();
    upsellSelect(upsellSelected);
	selectFirstClassItin(upsellSelected);
}

function processSelectUpsellResponse(data) {
	processResponse(data);
   if (isUpsellSelected() == true) {      
		hide('pwmOption');
   }
}

function omnitureUpsell(upsellItin) {
   try {
      OMTR_pageName = 'Trip Summary with Upsell';
      s.events= "scAdd,event25,event26,event56";
      products= ";Revenue" + "-" + OMTR_tripType + "-" +(OMTR_departureCity[0].toUpperCase())+"-"+(OMTR_destinationCity[0].toUpperCase())
                  + ";;;event25=" + (OMTR_flightTotalPrice*OMTR_paxCount) + "|event26=" + OMTR_paxCount+ "|event56=" + formatTo(upsellItin.decimalUpsellPriceDiff, 2, 1);
	   s.products=products;
      s.pageName=OMTR_pageName;
	   void(s.t());
   } catch (e) {}
}


/* ntrMerchandisingTools.js */

var ntrSummaryParentIframeUtilityReference = null;
function resizeItineraryIframe() {
	if (exists(ntrSummaryParentIframeUtilityReference)) {
		ntrSummaryParentIframeUtilityReference.fullySize();
	}
}

var paymentAppHander = {
	yesValue : "Y",
	noValue : "N",
	isAllowPaxInfoContinue : true,
	terminateIntervalId : null,
	terminateIntervalTime : 5000,
	defaultStringValue : "",
	defaultBooleanValue : false,
	defaultDoubleValue : 0.00,
	defaultIntValue : 0,
	passengerCount : 0,
	ccDropDownValue : "",
	maskingChar : "*",
	storedCCToggle : null,
	hasTripAdditions : false,
	returnValueToSet : function(value, ifNullValue) {
		return exists(value) ? value : ifNullValue;
	},
	idMapping : {
		creditCardFirstName:"", creditCardLastName:"", creditCardType:"", creditCardNumber:"", creditCardExpireMonth:"", creditCardExpireYear:"", ccID:"", storedCreditCardList:"", storedCreditCardExpireMonth:"", storedCreditCardExpireYear: "", storedCCId: "",useStoredCardValue:"", storedCCToggle: "",
		billingAddress1:"", billingAddress2:"", billingCity:"", billingRegion:"", billingZip:"", billingCountry:"", phoneNumber:"", phoneType:"",phoneAreaCode:"", emailAddress:"", initPaymentCache:"",
		formId : "", firstNameFieldPrefix : "", lastNameFieldPrefix : "", postNameFieldIndexChar : "", preNameFieldIndexChar : "", ccDropDownValue : "" , paymentHfId : "paymentHfId", isInsuranceSelected : "insuranceRadio", error : ""
	},
	errorHash : "",
	setIdMapping : function(Definition) {
		var idMapping = this.idMapping;
		for (var prop in Definition) {
			if (exists(Definition[prop]) && exists(idMapping[prop])) {
				idMapping[prop] = Definition[prop];
			}
		}
	},
	init : function(Definition) {
		var defaultStringValue = this.defaultStringValue;
		var returnValueToSetRef = this.returnValueToSet;
		this.setIdMapping(Definition);
		this.errorHash = returnValueToSetRef(Definition.errorHash, defaultStringValue);
		this.ccDropDownValue = returnValueToSetRef(Definition.ccDropDownValue, defaultStringValue);
		this.passengerCount = returnValueToSetRef(Definition.passengerCount, this.defaultIntValue);
		this.hasTripAdditions = returnValueToSetRef(Definition.hasTripAdditions, this.defaultBooleanValue);
		this.skymilesNumber = returnValueToSetRef(Definition.skymilesNumber, defaultStringValue);
		this.storedCCToggle = Definition.storedCCToggle;
	},
	passPassengerInformationToNTRFrame : function(index, isFirstName, value) {
		if (typeof(ntrMerchandisingPaxInfoIframeHandler) !== "undefined" ) {
			var propertyToSet = ntrMerchandisingPaxInfoIframeHandler.getJavascriptValue('collectPaxInfoHandler').personProperties[(isFirstName ? 'firstName' : 'lastName')];
			var paramsToEval = index.toString() + ', \'' + propertyToSet + '\', \'' + value + '\', ' + index.toString() + ', \'' + ntrMerchandisingPaxInfoIframeHandler.getJavascriptValue('collectPaxInfoHandler').nameDataTypes.passenger + '\'';
			ntrMerchandisingPaxInfoIframeHandler.runJavascriptFunction('collectPaxInfoHandler.addName', paramsToEval);
		}
	},
	getTagValue : function(id) {
		var tag = get(id);
		if (exists(tag)) {
			switch (tag.type.toLowerCase()) {
				case "select-one":
					return tag.options[tag.selectedIndex].value;
				case "radio":
					tag = tag.form[tag.name];
					for (var i=0, j=tag.length; i<j; i++) {
						if (tag[i].checked) { 
							return tag[i].value; 
						} 
					}
					break;
				case "text":
				case "hidden":
					return tag.value;
			}
		}
		return "";
	},
	setTagValue : function(id, value) {
		var tag = get(id);
		if (exists(tag)) {
			switch (tag.type.toLowerCase()) {
				case "hidden":
				case "text":
					tag.value = value;
					break;
			}
		}
	},
	getIsAllowPaxInfoContinue : function() {
		return this.isAllowPaxInfoContinue;
	},
	setIsAllowPaxInfoContinue : function(value) {
		this.isAllowPaxInfoContinue = value;
	},
	markInsuranceError : function() {
		var insuranceErrorElement = get("insuranceRequired");
		if (!exists(insuranceErrorElement)) {
			var concat = new conCatTool();
			concat.conCat('<div class="error" id="insuranceRequired">Please tell us if you would like to add Trip Protection</div>');
			get(this.idMapping.error).innerHTML += concat.toString(true);
		}
		window.location.hash = "#" + this.errorHash;
	},
	removeInsuranceError : function() {
		try {
			var childToRemove = get("insuranceRequired");
			if (exists(childToRemove)) {
				get(this.idMapping.error).removeChild(childToRemove);
			}
		} catch(e) { }
	},
	markHotelError : function() {
		var hotelErrorElement = get("hotelRequired");
		if (!exists(hotelErrorElement)) {
			var concat = new conCatTool();
			concat.conCat('<div class="error" id="hotelRequired">Please provide all required information for your hotel reservation</div>');
			get(this.idMapping.error).innerHTML += concat.toString(true);
		}
		window.location.hash = "#" + this.errorHash;
	},
	removeHotelError : function() {
		try {
			var childToRemove = get("hotelRequired");
			if (exists(childToRemove)) {
				get(this.idMapping.error).removeChild(childToRemove);
			}
		} catch(e) { }
	},
	markCarError : function() {
		var carErrorElement = get("carRequired");
		if (!exists(carErrorElement)) {
			var concat = new conCatTool();
			concat.conCat('<div class="error" id="carRequired">Please provide all required information for your car rental</div>');
			get(this.idMapping.error).innerHTML += concat.toString(true);
		}
		window.location.hash = "#" + this.errorHash;
	},
	removeCarError : function() {
		try {
			var childToRemove = get("carRequired");
			if (exists(childToRemove)) {
				get(this.idMapping.error).removeChild(childToRemove);
			}
		} catch(e) { }
	},
	sendPassengerDataToPayment : function() {
		try {
			paymentAppHander.setIsAllowPaxInfoContinue(true);
			var isOptedForInsurance = false;
			if (typeof(ntrMerchandisingPurchaseTripInsuranceIframeHandler) !== "undefined") {
				var isInsuranceSelected = isPaymentEligibleForTripProtector ? ntrMerchandisingPurchaseTripInsuranceIframeHandler.getJavascriptValue('collectPaxInfoHandler').isInsuranceSelected() : true;
				paymentAppHander.setIsAllowPaxInfoContinue(isInsuranceSelected);
				if (!isInsuranceSelected) {
					this.markInsuranceError();
				} else {
					this.removeInsuranceError();
				}
				isOptedForInsurance = isPaymentEligibleForTripProtector ? ntrMerchandisingPurchaseTripInsuranceIframeHandler.getJavascriptValue('collectPaxInfoHandler').hasOptedForInsurance() : false;
				paymentAppHander.setTagValue(paymentAppHander.idMapping.isInsuranceSelected, (isOptedForInsurance ? paymentAppHander.yesValue : paymentAppHander.noValue) );
			}
			if (paymentAppHander.getIsAllowPaxInfoContinue() && typeof(ntrMerchandisingPaxInfoIframeHandler) !== "undefined") {
				var collectPaxInfoRef = ntrMerchandisingPaxInfoIframeHandler.getJavascriptValue('collectPaxInfoHandler');
				var isCarInformationEntered = collectPaxInfoRef.isCarDataEntered();
				var isHotelInformationEntered = collectPaxInfoRef.isHotelDataEntered();
				if (isHotelInformationEntered && isCarInformationEntered) {
					paymentAppHander.setIsAllowPaxInfoContinue(true);
					this.removeCarError();
					this.removeHotelError();
					var idMapping = paymentAppHander.idMapping;
					var isUsingStoredCard = paymentAppHander.getTagValue(idMapping.useStoredCardValue) === paymentAppHander.storedCCToggle;
					var creditcCardFrstName = paymentAppHander.getTagValue(idMapping.creditCardFirstName);
					var creditcardLastName = paymentAppHander.getTagValue(idMapping.creditCardLastName);

					var ccID = paymentAppHander.getTagValue((!isUsingStoredCard || !exists(idMapping.storedCCId) ? idMapping.ccID : idMapping.storedCCId));
					var creditCardExpireMonth = paymentAppHander.getTagValue((!isUsingStoredCard || !exists(idMapping.storedCreditCardExpireMonth) ? idMapping.creditCardExpireMonth : idMapping.storedCreditCardExpireMonth));
					var creditCardExpireYear = paymentAppHander.getTagValue((!isUsingStoredCard  || !exists(idMapping.storedCreditCardExpireYear) ? idMapping.creditCardExpireYear : idMapping.storedCreditCardExpireYear));
					var profileCCID = !isUsingStoredCard ? "" : paymentAppHander.getTagValue(idMapping.storedCreditCardList);
					var creditCardNumber = !isUsingStoredCard ? paymentAppHander.getTagValue(idMapping.creditCardNumber) : "";
					var creditCardType = paymentAppHander.getTagValue(idMapping.creditCardType);
					if (creditCardNumber.indexOf(this.maskingChar) >= 0 && exists(this.ccDropDownValue) && this.ccDropDownValue !== "") {
						creditCardNumber = "";
						profileCCID = this.ccDropDownValue;
					}
					var phoneNumber = paymentAppHander.getTagValue(idMapping.phoneAreaCode) + paymentAppHander.getTagValue(idMapping.phoneNumber);
					var phoneType = paymentAppHander.getTagValue(idMapping.phoneType);
					var emailAddress = paymentAppHander.getTagValue(idMapping.emailAddress);
					var billingAddress1 = paymentAppHander.getTagValue(idMapping.billingAddress1);
					var billingAddress2 = paymentAppHander.getTagValue(idMapping.billingAddress2);
					var billingCity = paymentAppHander.getTagValue(idMapping.billingCity);
					var billingRegion = paymentAppHander.getTagValue(idMapping.billingRegion);
					var billingCountry = paymentAppHander.getTagValue(idMapping.billingCountry);
					var billingZip = paymentAppHander.getTagValue(idMapping.billingZip);
					paymentAppHander.terminateIntervalId = window.setInterval('paymentAppHander.failPaymentInitAndSubmitForm()', paymentAppHander.terminateIntervalTime);
					collectPaxInfoRef.initForPaymentCache(creditcCardFrstName, creditcardLastName, phoneNumber, phoneType, emailAddress, profileCCID, paymentAppHander.skymilesNumber, creditCardNumber, creditCardType, ccID, creditCardExpireMonth, creditCardExpireYear, billingAddress1, billingAddress2, billingCity, billingRegion, billingCountry, billingZip);
					window.clearInterval(paymentAppHander.terminateIntervalId);
					var isPaymentInit = collectPaxInfoRef.getIsPaymentCacheInit();
					var paymentHfId = collectPaxInfoRef.getPaymentHfId();
					paymentAppHander.setTagValue(paymentAppHander.idMapping.initPaymentCache, isPaymentInit);
					paymentAppHander.setTagValue(paymentAppHander.idMapping.paymentHfId, paymentHfId);
					if (isOptedForInsurance && isPaymentInit) {
						paymentAppHander.terminateIntervalId = window.setInterval('paymentAppHander.failPaymentInitAndSubmitForm()', paymentAppHander.terminateIntervalTime);
						ntrMerchandisingPurchaseTripInsuranceIframeHandler.getJavascriptValue('insurancePurchaseHandler').doSendMerchOverride(paymentHfId);
						window.clearInterval(paymentAppHander.terminateIntervalId);
					}
				} else {
					paymentAppHander.setIsAllowPaxInfoContinue(false);
					if (!isHotelInformationEntered) {
						this.markHotelError();
					}
					if (!isCarInformationEntered) {
						this.markCarError();
					}
				}
			}
		} catch(e) { }
		return paymentAppHander.getIsAllowPaxInfoContinue();
	},
	failPaymentInitAndSubmitForm : function() {
		paymentAppHander.setTagValue(paymentAppHander.idMapping.initPaymentCache, false);
		paymentAppHander.setTagValue(paymentAppHander.idMapping.paymentHfId, "");
		window.clearInterval(paymentAppHander.terminateIntervalId);
		get(paymentAppHander.idMapping.formId).submit();
	},
	setNamesFromFormInput : function() {
		var idMapping = this.idMapping;
		var form = get(paymentAppHander.idMapping.formId);
		for (var i=0, j=this.passengerCount; i<j; i++) {
			var nameField = idMapping.firstNameFieldPrefix + idMapping.preNameFieldIndexChar + i.toString() + idMapping.postNameFieldIndexChar;
			var nameValue = exists(form[nameField]) ? form[nameField].value : "";
			if (nameValue !== "") {
				this.passPassengerInformationToNTRFrame(i, true, nameValue);
			}
			nameField = idMapping.lastNameFieldPrefix + idMapping.preNameFieldIndexChar + i.toString() + idMapping.postNameFieldIndexChar;
			nameValue = exists(form[nameField]) ? form[nameField].value : "";
			if (nameValue !== "") {
				this.passPassengerInformationToNTRFrame(i, false, nameValue);
			}
		}
	}
};

var omniturePurhchaseHandler = {
	isUsingTrackingObject : true,
	isTripAdditionsIframePresent : false,
	isInsuranceIframePresent : false,
	tripAdditionsOmnitureHandlerReference : null,
	insuranceOmnitureHandlerReference : null,
	maxDataReturnedCheckTime : 5000,
	maxSetHandlerTime : 1000,
	checkProperty : null,
	iframOmnitureHandlerReference : null,
	forceHasDataReturnedTrue : function() {
		if (exists(omniturePurhchaseHandler.iframOmnitureHandlerReference) && exists(omniturePurhchaseHandler.checkProperty)) {
			omniturePurhchaseHandler.iframOmnitureHandlerReference.setDataReturnedChecksIsDataSet(omniturePurhchaseHandler.checkProperty, true);
		}
	},
	hasDataReturned : function(iframOmnitureHandlerReference, checkProperty) {
		var isReturned = true;
		if (exists(iframOmnitureHandlerReference) && exists(checkProperty)) {
			this.iframOmnitureHandlerReference = iframOmnitureHandlerReference;
			this.checkProperty = checkProperty;
//			var timeoutId = setTimeout("omniturePurhchaseHandler.forceHasDataReturnedTrue()", this.maxDataReturnedCheckTime);
			try {
//				while(!iframOmnitureHandlerReference.isNeededDataSet(checkProperty)) {
//					isReturned = false;
//				}
				isReturned = true
			} catch(e) {}
			clearTimeout(timeoutId);
		}
		return isReturned;
	},
	setTripAdditionsOmnitureHandlerReference : function() {
		if (this.isTripAdditionsIframePresent && !exists(this.tripAdditionsOmnitureHandlerReference)) {
			this.tripAdditionsOmnitureHandlerReference = ntrMerchandisingPurchaseTripAdditionsIframeHandler.getJavascriptValue('omnitureHandler');
		}
	},
	exitSetInsuranceOmnitureHandlerReference : function() {
		omniturePurhchaseHandler.insuranceOmnitureHandlerReference = {};
	},
	setInsuranceOmnitureHandlerReference : function() {
//		var timeoutId = setTimeout("omniturePurhchaseHandler.exitSetInsuranceOmnitureHandlerReference()", this.maxSetHandlerTime);
		if (this.isInsuranceIframePresent && !exists(this.insuranceOmnitureHandlerReference)) {
//			while(!exists(this.insuranceOmnitureHandlerReference)) {
				this.insuranceOmnitureHandlerReference = ntrMerchandisingPurchaseTripInsuranceIframeHandler.getJavascriptValue('omnitureHandler');
//			}
		}
	},
	setHotelData : function() {
		try {
			if (this.isTripAdditionsIframePresent) {
				this.setTripAdditionsOmnitureHandlerReference();
				var omnitureHandlerReference = this.tripAdditionsOmnitureHandlerReference;
				if (exists(omnitureHandlerReference) && this.hasDataReturned(omnitureHandlerReference, omnitureHandlerReference.dataReturnedCheckProperties.hotelCheck)) {
					var hotelDetails = this.tripAdditionsOmnitureHandlerReference.getHotelPurchaseDetails();
					if (!this.isUsingTrackingObject) {
						OMTR_hotelName = hotelDetails.name;
						OMTR_hotelTotal = hotelDetails.totalCost;
						OMTR_hotelRooms = hotelDetails.roomQuantity;
					}
				}
			}
		} catch(e) { }
	},
	setCarData : function() {
		try {
			if (this.isTripAdditionsIframePresent) {
				this.setTripAdditionsOmnitureHandlerReference();
				var omnitureHandlerReference = this.tripAdditionsOmnitureHandlerReference;
				if (exists(omnitureHandlerReference) && this.hasDataReturned(omnitureHandlerReference, omnitureHandlerReference.dataReturnedCheckProperties.carCheck)) {
					var carDetails = omnitureHandlerReference.getCarPurchaseDetails();
					if (!this.isUsingTrackingObject) {
						OMTR_carCompanyName = carDetails.vendorCode;
						OMTR_carType = carDetails.carType;
						OMTR_carTotal = carDetails.totalCost;
						OMTR_carPickupDate = carDetails.pickupDate;
						OMTR_carReturnDate = carDetails.returnDate;
					}
				}
			}
		} catch(e) { }
	},
	setDSPData : function() {
		try {
			if (this.isTripAdditionsIframePresent) {
				this.setTripAdditionsOmnitureHandlerReference();
				var omnitureHandlerReference = this.tripAdditionsOmnitureHandlerReference;
				if (exists(omnitureHandlerReference) && this.hasDataReturned(omnitureHandlerReference, omnitureHandlerReference.dataReturnedCheckProperties.dspCheck)) {
					var dspDetails = omnitureHandlerReference.getDSPPurchaseDetails();
					if (!this.isUsingTrackingObject) {
						OMTR_dspTotal = dspDetails.totalCost;
					}
				}
			}
		} catch(e) {}
	},
	setInsuranceData : function() {
		try {
			if (this.isInsuranceIframePresent) {
				this.setInsuranceOmnitureHandlerReference();
				var omnitureHandlerReference = this.insuranceOmnitureHandlerReference;
				if (exists(omnitureHandlerReference) && this.hasDataReturned(omnitureHandlerReference, omnitureHandlerReference.dataReturnedCheckProperties.insuranceCheck)) {
					var insuranceDetails = omnitureHandlerReference.getInsurancePurchaseDetails();
					if (exists(insuranceDetails)) {
						if (!this.isUsingTrackingObject) {
							OMTR_insurance = insuranceDetails.isPurchased;
							OMTR_insuranceTotal = insuranceDetails.cost;
						}
					}
				}
			}
		} catch(e) { }
	},
	init : function(isUsingTrackingObject) {
		this.isUsingTrackingObject = isUsingTrackingObject;
		this.isTripAdditionsIframePresent = typeof(ntrMerchandisingPurchaseTripAdditionsIframeHandler ) !== "undefined";
		this.isInsuranceIframePresent = typeof(ntrMerchandisingPurchaseTripInsuranceIframeHandler ) !== "undefined";
		this.setTripAdditionsOmnitureHandlerReference();
		this.setInsuranceOmnitureHandlerReference();
	}
}

var updateTotalHandler = {
	numericCosts : {insurance : 0.0, dsp : 0.0, hotel : 0.0, car : 0.0, flight : 0.0, totalCost : 0.0, tripTotalsNTRCost : 0.0},
	formattedCosts : {insurance : "", dsp : "",	hotel : "", car : "", flight : "", totalCost : "", tripTotalsNTRCost : ""},
	properties : {insurance : "insurance", dsp : "dsp",	hotel : "hotel", car : "car", flight : "flight", totalCost : "totalCost", tripTotalsNTRCost : "tripTotalsNTRCost"},
	selectedItems : {insurance : false, dsp : false, hotel : false, car : false},
	populateWhich : "",
	adjustForCurrencyFlip : false,
	currencyCode : "",
	currencySymbol : "",
	zeroFormattedValue : "",
	populateWhichTypes : { booking : "bookingTripTotals" },
	idMapping : {
		booking : { formattedHotelCostTag : "hotelCost", formattedCarRentalCostTag : "carRentalCost", formattedDSPCostTag : "dspCost", formattedInsuranceTag : "insuranceAmount", formattedTotalCost : "amountDue", formattedNTRTripTotalsDSPCostForConversion : "tripTotalsDSPCost", formattedHeaderDSPCost : "headerTripAdditionTotals" }
	},
	init : function(populateWhich, currencyCode, currencySymbol) {
		this.populateWhich = populateWhich;
		this.currencyCode = currencyCode;
		this.currencySymbol = currencySymbol;
		this.zeroFormattedValue = mp_util.doDisable(this.currencySymbol + '0.00 (' + this.currencyCode + ')');
	},
	setCarData : function(formattedValue, numericValue, isSelected) {
		this.formattedCosts[this.properties.car] = formattedValue;
		this.numericCosts[this.properties.car] = numericValue;
		this.selectedItems[this.properties.car] = isSelected;
	},
	getCarCost : function(isReturnNumeric) {
		return isReturnNumeric ? parseFloat(this.numericCosts[this.properties.car]) : this.formattedCosts[this.properties.car];
	},
	getIsCarSelected : function() {
		return this.selectedItems[this.properties.car];
	},
	setHotelData : function(formattedValue, numericValue, isSelected) {
		this.formattedCosts[this.properties.hotel] = formattedValue;
		this.numericCosts[this.properties.hotel] = numericValue;
		this.selectedItems[this.properties.hotel] = isSelected;
	},
	getHotelCost : function(isReturnNumeric) {
		return isReturnNumeric ? this.numericCosts[this.properties.hotel] : this.formattedCosts[this.properties.hotel];
	},
	getIsHotelSelected : function() {
		return this.selectedItems[this.properties.hotel];
	},
	setDSPData : function(formattedValue, numericValue, isSelected) {
		this.formattedCosts[this.properties.dsp] = formattedValue;
		this.numericCosts[this.properties.dsp] = numericValue;
		this.selectedItems[this.properties.dsp] = isSelected;
	},
	getDSPCost : function(isReturnNumeric) {
		return isReturnNumeric ? this.numericCosts[this.properties.dsp] : this.formattedCosts[this.properties.dsp];
	},
	getIsDSPSelected : function() {
		return this.selectedItems[this.properties.dsp];
	},
	setInsuranceData : function(formattedValue, numericValue, isSelected) {
		this.formattedCosts[this.properties.insurance] = formattedValue;
		this.numericCosts[this.properties.insurance] = numericValue;
		this.selectedItems[this.properties.insurance] = isSelected;
	},
	getInsuranceCost : function(isReturnNumeric) {
		return isReturnNumeric ? this.numericCosts[this.properties.insurance] : this.formattedCosts[this.properties.insurance];
	},
	setFlightData : function(formattedValue, numericValue) {
		this.formattedCosts[this.properties.flight] = formattedValue;
		this.numericCosts[this.properties.flight] = numericValue;
	},
	getFlightCost : function(isReturnNumeric) {
		return isReturnNumeric ? this.numericCosts[this.properties.flight] : this.formattedCosts[this.properties.flight];
	},
	formatCurrency : function(value) {
		return value.replace(/(^|[^\w.])(\d{4,})/g, function($0, $1, $2) {
			return $1 + $2.replace(/\d(?=(?:\d\d\d)+(?!\d))/g, "$&,");
		});
	},
	getInsuranceSelected : function() {
		return this.selectedItems[this.properties.insurance];
	},
	returnIdMapping : function() {
		var idMapping = this.idMapping;
		switch(this.populateWhich) {
			case this.populateWhichTypes.booking:
				return idMapping.booking;
		}
		return null;
	},
	getNTRTotal : function(isReturnNumeric) {
		var totalCost = 0.0;
		if (this.getIsCarSelected()) {
			totalCost += this.getCarCost(true);
		}
		if (this.getIsHotelSelected()) {
			totalCost += this.getHotelCost(true);
		}
		if (this.getIsDSPSelected()) {
			totalCost += this.getDSPCost(true);
		}
		return isReturnNumeric ? totalCost : mp_util.doDisable(this.formatCurrency("$" + formatTo(totalCost, 2, 1) + ' (USD)'));
	},
	setNTRTotal : function() {
		this.numericCosts[this.properties.tripTotalsNTRCost] = this.getNTRTotal(true);
		this.formattedCosts[this.properties.tripTotalsNTRCost] = this.getNTRTotal(false);
	},
	setTotalCost : function() {
		var totalCost = this.getFlightCost(true);
		if (!this.getAdjustForCurrencyFlip()) {
			totalCost += this.getNTRTotal(true);
		}
		if (this.getInsuranceSelected()) {
			totalCost += this.getInsuranceCost(true);
		}
		this.numericCosts[this.properties.totalCost] = totalCost;
		this.formattedCosts[this.properties.totalCost] = mp_util.doDisable(this.formatCurrency(this.currencySymbol + formatTo(this.numericCosts[this.properties.totalCost], 2, 1)) + ' (' + this.currencyCode + ')');
	},
	doPopulate : function() {
		var idMapping = this.returnIdMapping();
		this.setTotalCost();
		if (exists(idMapping)) {
			setInnerHTML(idMapping.formattedHotelCostTag, (this.getIsHotelSelected() ? this.getHotelCost(false) : this.zeroFormattedValue));
			setInnerHTML(idMapping.formattedCarRentalCostTag, (this.getIsCarSelected() ? this.getCarCost(false) : this.zeroFormattedValue));
			setInnerHTML(idMapping.formattedDSPCostTag, (this.getIsDSPSelected() ? this.getDSPCost(false) : this.zeroFormattedValue));
			setInnerHTML(idMapping.formattedInsuranceTag, (this.getInsuranceSelected() ? this.getInsuranceCost(false) : this.zeroFormattedValue));
			setInnerHTML(idMapping.formattedTotalCost, this.formattedCosts[this.properties.totalCost]);
			setInnerHTML(idMapping.formattedHeaderDSPCost, this.getNTRTotal(false));
			if (this.getAdjustForCurrencyFlip()) {
				setInnerHTML(idMapping.formattedNTRTripTotalsDSPCostForConversion, this.getNTRTotal(false));
			}
		}
	},
	setAdjustForCurrencyFlip : function(value) {
		this.adjustForCurrencyFlip = value;
	},
	getAdjustForCurrencyFlip : function() {
		return this.adjustForCurrencyFlip;
	}
}
