// ListBox, CityList: N. Viau, B. Larose (Ekidev) 

// Stubs for pages that don't include errorlog.js.
if (typeof logError == "undefined") {
  logError = function(){};
}
if (typeof logLoaded == "undefined") {
	logLoaded = function(){};
}
if (typeof logDebug == "undefined") {
	logDebug = function(){};
}
var jsName = "citysearch.js";
logDebug(jsName + "@start");


// common.js start (temporary copy until all required pages include common.js)
function e(id) {
  return document.getElementById(id);
}

function hide(id) {
	var el = e(id);
	if (el != null)
  	el.style.display = 'none';
  return el;
}

function show(id) {
	var el = e(id);
	if (el != null)
  	el.style.display = '';
  return e;
}

function isShown(id) {
	var el = e(id);
	if (el != null)
        return el.style.display != 'none';
    return true;
}

function isHidden(id) {
    return ! isShown(id);
}

function getSelected(field) {
	var index = field.selectedIndex;
	if (typeof index == "undefined") return null;
	return field.options[index].value
}

function isChecked(field) {
	return field.checked == true;
}

function isEmpty(value) {
	return value == null || value == "";
}

function getEventTarget(event) {
	var target = event.target ? event.target : event.srcElement;
	if (target.nodeType == 3) target = target.parentNode; // handle Safari bug
	return target;
}

function cancelEvent(event) {
	if (event.preventDefault) event.preventDefault(); // FF and others
	if (event.stopPropagation) event.stopPropagation(); // FF and others
	event.returnValue = false; // IE
	event.cancelBubble = true; // IE
}

function isMouseOutForTarget(event, targetId) {
	if (! event) var event = window.event;
	var target = getEventTarget(event);
	if (target.id != targetId) return false; // Mouse left some other element.
	var relTarget = (event.relatedTarget) ? event.relatedTarget : event.toElement;
	while (relTarget != target && relTarget.nodeName != 'BODY') // See if ancestor of related target is the target.
		relTarget = relTarget.parentNode
	if (relTarget == target) return false; // Mouse moved to a link in element or child of element.
	// Mouse out event took place when mouse actually left element with id 'targetId'.
	return true;
}

function stopEventPropagation(event){
	if (! event) var event = window.event;
	event.cancelBubble = true;
	if (event.stopPropagation) event.stopPropagation();
}

function getMouseOverTarget(event) {
	if (! event) var event = window.event;
	return event.relatedTarget || event.fromElement;
}

function getMouseOutTarget(event) {
	if (! event) var event = window.event;
	return event.relatedTarget || event.toElement;
}

// common.js end

  var origAirport;
  var destAirport;
  var POSITIVE_INFINITY=Math.pow(2,32);
  var MAX_CITY_PAIRS = 1;
  var MAX_DEPARTURES=2;
  var FLIGHT_PAGE=false;
  var MAX_FLIGHT_SELECTION_MONTH = 12;
  var DATE_VALUE_PLANITGO = "5";
  POS="";
  POS_arr="";
  var WITHHOLD_SURCHARG=false;
  //SR97502918______________________________________
  var CARIBBEAN=new Array("MQ","AW","LC","BM","BB","BS","AG","TT","VE","JM","MX","CU","CR","DO","KY","GD","GP","GT","HT","PR","AN","TC");
  //________________________________________________
  var CARIBBEAN_FLAG=false;
  var SP_CARIBBEAN="VE";
  var CARIBBEAN_CITY=new Array("MBJ","KIN","HAV","MEX");
  var IntlCaribbeanCOR = new Array("TC","KY"); //Caribbean countries that should be treateds as International flights => COMMERCIAL_FARE_FAMILY_1 == WORLTRAVEL

  //SR97502918______________________________________
  var th = document.getElementsByTagName('head')[0];
  var s = document.createElement('script');
  s.setAttribute('type','text/javascript');
  s.setAttribute('src',"/shared/includes/common/flightssearch/lookup_data.js");
  th.appendChild(s);
  //________________________________________________

//List of countries that will be redirected to Canadian Site when selected in the Splash page:
var CanadianCOR = new Array("AR","AT","BH","BE","CL","CN","CR","CZ","FI","GR","HU","JP","JO","MX","NZ","PL","PT","QA","SA","KR","ES","TW","TH","UA","AE","VN");

//List of countries that Surcharge does not apply to it. i.e. SO_SITE_FP_WITHHOLD_SURCHARG = FALSE
var NoneSurchargedCountries = new Array("AU","GB","IE","FR","CH","DE","IT","DK","NO","SE","IL","NL");

// --- City list start ---
var listmap = {};
function getCityList(id) {
	var templist = listmap[id];
	if (templist == null) {
		templist = list;
		if (typeof initCityListMulti != "undefined") {
			templist = new ListBox();
			initCityListMulti(templist);
		} else if (typeof initCityList != "undefined") {
			initCityList();
		} else if (typeof initHomeCityList != "undefined") {
			initHomeCityList();
		}
		listmap[id] = templist;
	}
	return templist;
}

var isOverList = false;
var cityListFieldId = null;
function cityListOnFocus(event, id) {
	if (cityList == null) return;

	// Hack to make sure these 2 global variables are always initialized.
	fl = document.flights;
	dpg = document.flightsPlanitgo;

	try {
		var target;
		// START - For backward compatibility with multicity.do page.
		if (id) target = e(id); else
		//END - For backward compatibility with multicity.do page. 
		{
			if (! event) event = window.event;
			target = getEventTarget(event);
		}
		var list = getCityList(target.id);
		
		list.open(target);
		cityListFieldId = target.id;
		document.getElementById(target.id).select();
	} catch (err) {
		logError(err, "cityListOnFocus");
	}
}

function cityListOnKeyDown(event) {
	if (cityList == null) return;
	if (! event) event = window.event;
	target = getEventTarget(event);
	var list = getCityList(target.id);
	try {
		list.processKeyDownEvent(event);
	} catch (err) {
		logError(err, "cityListOnKeyDown");
	}
}

function cityListOnKeyPress(event) {
	if (cityList == null) return;
	if (! event) event = window.event;
	target = getEventTarget(event);
	var list = getCityList(target.id);
	try {
		list.processKeyPressEvent(event);
	} catch (err) {
		logError(err, "cityListOnKeyPress");
	}
}

function cityListOnKeyUp(event) {
	if (cityList == null) return;
	if (! event) event = window.event;
	target = getEventTarget(event);
	var list = getCityList(target.id);
	try {
		list.processKeyUpEvent(event);
	} catch (err) {
		logError(err, "cityListOnKeyUp");
	}
}

function cityListOnBlur(event) {
	if (isOverList) return;
	if (cityList == null) return;
	if (! event) event = window.event;
	target = getEventTarget(event);
	var list = getCityList(target.id);
	try {
		list.close();
	} catch (err) {
		logError(err, "cityListOnBlur");
	}
	// Adjust forms fields and options.
	showAndHide();
}

function ListBox(){
	logDebug("new ListBox");
	this.maxLength = 20;
	this.maxShownLength = 10;
	this.maxHeight = 160;
	this.minChars = 3;
	this.scrollingIncrement = 16;

	this.div = null;
	this.targetBox = null;
	this.initialValue = null;
	this._clearResults();
	this.searchHandler = new function(entry){};
	this.fullListHandler = new function(entry){};
	this.codeInputs = new Object();
	this.valueInputs = new Object();
	this.targetObjects = new Object();
	this.fieldsTohide = new Object();
	this.nextFocusField = new Object();
}

var lP=ListBox.prototype;

lP.open=function(target){
	// Properly close previous list if still open.
	if (this.list != null) this.close();

	this.targetBox = target;
	this.initialValue = target.value;
	this._updateShownList(this.targetBox.value);
	this._toggleSelectFields(false);
}

lP.mover=function(event){
	isOverList = true;
}

lP.mout=function(event){
	isOverList = false;
}

lP.close=function(){
	if (this.targetBox.value != this.initialValue || this.currentIndex != -1) {
		this._updateCurrentField();
		this._updateRegisteredInputs();
	}
	this._hide();
	this._clearResults();
	this._toggleSelectFields(true);
}

lP.mouseOverItem=function(event){
	var list = getCityList(cityListFieldId);
	// Event handler, use 'list' instead of 'this'.
	if (! event) event = window.event;
	stopEventPropagation(event);
	list.unselect();
	var target = getEventTarget(event);
	target.className = "over";
	list.currentIndex = target.getAttribute("pos");
}

lP.mouseOutItem=function(event){
	var list = getCityList(cityListFieldId);
	// Event handler, use 'list' instead of 'this'.
	if (! event) event = window.event;
	stopEventPropagation(event);
	var target = getEventTarget(event);
	target.className = "";
	list.currentIndex = -1;
}

lP.processKeyDownEvent=function(event){
	// START - For backward compatibility with flights.do page.
	if (this.list == null) {
		if (! event) event = window.event;
		this.open(getEventTarget(event));
	} 
	//END - For backward compatibility with flights.do page. 
	switch(event['keyCode']){
		case 38: this.selectPrevious(); break;			// Up arrow
		case 40: this.selectNext(); break;				// Down arrow
		case 9:											// Tab
			if (this.currentIndex == -1) this.currentIndex = 0;
			break;
		case 13:										// Enter
			if (this.currentIndex == -1) this.currentIndex = 0;
			this.nextFocus();
			break;
	}
}

lP.processKeyPressEvent=function(event){
	switch(event['keyCode']){
        	case 38: case 40: case 13: cancelEvent(event); break;
	}
}

lP.processKeyUpEvent=function(event){
	switch(event['keyCode']){
        	case 38: case 40: case 9: case 13: break;
        	default: this._updateShownList(this.targetBox.value);
	}
}

// START - For backward compatibility with flights.do page. 
lP.clickOut=function(event){
	list.close(); 
}
lP.processKeyEvent=function(event){
	var list = getCityList(cityListFieldId);
	list.processKeyUpEvent(event);
}
lP.hide=function(){
	var list = getCityList(cityListFieldId);
	list._hide();
}
//END - For backward compatibility with flights.do page. 
	
lP._show=function(){
	if (this.div != null) {
		this._position();
		this.div.style.display = "";
	}
}

lP._clearResults=function(){
	this.list = null;
	this.currentIndex = -1;
	this.initialValue = null;
}

lP._hide=function(){
	if (this.div) this.div.style.display = "none";
	if (! e("citylist")) return; // For backward compatibility with flights.do page.
	e("citylist").style.display = "none";
	if (! e("citysearchinfodiv")) return; // For backward compatibility with flights.do page.
	e("citysearchinfodiv").style.display = "none";
	if (! e("citysearchinfodiverror")) return; // For backward compatibility with flights.do page.
	e("citysearchinfodiverror").style.display = "none";
}

lP._toggleSelectFields=function(show){
	if (this.targetBox == null || this.targetBox.id == null) return;
	var fields = this.fieldsTohide[this.targetBox.id];
	if (fields == null) return;
	for (var i = 0; i < fields.length; i++){
		var field = e(fields[i]);
		if (! field) continue;
		var replacementField = e(fields[i] + "_replacement");
		if (show) {
			if (replacementField) replacementField.style.display = "none";
			field.style.display = "";
		} else {
			var tmpValue = field.options[field.selectedIndex].text;
			var tmpWidth = field.offsetWidth;
			//var tmpHeight = field.offsetHeight;
			field.style.display = "none";
			if (replacementField) {
				if (tmpWidth > 0) {
				 replacementField.style.width = tmpWidth + "px";
				 replacementField.style.paddingLeft = "3px";
				 replacementField.style.paddingTop = "1px";
				 replacementField.style.paddingBottom = "0px";
				 replacementField.style.marginTop = "0px";
				 replacementField.style.marginBottom = "1px";
				}
				 replacementField.style.display = "";
				 replacementField.value = tmpValue;
			}
		}
	}
}

lP._populateDiv=function(data){
	this.div.style.height = (data.length >= this.maxShownLength) ? this.maxHeight + "px" : "";
	this.div.innerHTML = "";
	this.div.className = "listbox";
	for (var i = 0; i < data.length && i < this.maxLength; i++){
		var node = document.createElement("div");
		node.setAttribute("pos", i);
		node.setAttribute("code", data[i].value);
		node.appendChild(document.createTextNode(data[i].text));
		if (! node.addEventListener){
			node.attachEvent("onmouseover", this.mouseOverItem);
			node.attachEvent("onmouseout", this.mouseOutItem);
		}else{
			node.addEventListener("mouseover", this.mouseOverItem, false);
			node.addEventListener("mouseout", this.mouseOutItem, false);
		}
		this.div.appendChild(node);
	}
}

lP._configureDiv=function(){
	this.div = e("citylist");
	if (! this.div) {
		logError("Missing citylist DIV", "citylist.js@lP.open");

		// IE (all versions) will unload the page if the citylist is used before page is
		// completely loaded. To avoid this, make sure an empty DIV with an id of
		// "citylist" exists on the page so this code never gets executed.
		this.div = document.createElement("div");
		this.div.setAttribute("id", "citylist");
		document.getElementsByTagName("body")[0].appendChild(this.div);
	}
	if(! this.div.addEventListener){
		this.div.attachEvent("onmouseover", this.mover);
		this.div.attachEvent("onmouseout", this.mout);
	}else{
		this.div.addEventListener("mouseover", this.mover, false);
		this.div.addEventListener("mouseout", this.mout, false);
	}
}

lP._updateCurrentField=function(){
	if (this.list != null && this.list.length > 0 && this.currentIndex != -1) {
		this.targetBox.value = this.getSelectedValue();
		this.targetBox.className = "";
	}
}

lP.unselect=function(){
	if (this.list == null) return;
	for (var i = 0; i < this.div.childNodes.length; i++)
		this.div.childNodes[i].className = "";
}

lP.selectFirst=function(){
	if (this.list.length < 1) return;
	this.unselect();
	this.div.childNodes[0].className = "on";
}

lP.scrollUp=function(){
	var presentVisible = parseInt((this.currentIndex) * this.scrollingIncrement);
	this.div.scrollTop = presentVisible - this.scrollingIncrement;
}

lP.scrollDown=function(){
	var presentVisible = parseInt((this.currentIndex - 3) * this.scrollingIncrement);
	this.div.scrollTop = presentVisible + this.scrollingIncrement;
}

lP.selectNext=function(){
	this.unselect();
	if (this.currentIndex < 0) this.currentIndex = 0;
	else if (this.currentIndex < (this.div.childNodes.length - 1)){this.currentIndex++; this.scrollDown();}
	this.div.childNodes[this.currentIndex].className = "on";
}

lP.selectPrevious=function(){
	this.unselect();
	if (this.currentIndex > 0){ this.currentIndex--; this.scrollUp();}
	this.div.childNodes[this.currentIndex].className = "on";
}

lP.getSelectedCode=function()  {return this.isValidSelected() ? this.list[this.currentIndex].value : "";}
lP.getSelectedObject=function(){return this.isValidSelected() ? this.list[this.currentIndex] : null;}
lP.getSelectedValue=function() {return this.isValidSelected() ? this.list[this.currentIndex].text : "";}
lP.isValidSelected=function(){
	return this.list != null && this.currentIndex >= 0 && this.currentIndex < this.list.length;
}
lP._showInfoDiv=function(){
	var listInfoDiv = (this.targetBox.className == 'invalid') ? e('citysearchinfodiverror'): e('citysearchinfodiv');
	if (! listInfoDiv) return;
	listInfoDiv.style.position = "absolute";
	listInfoDiv.style.left = this.findPosX(this.targetBox) + "px";
	listInfoDiv.style.top = (this.findPosY(this.targetBox) + 18) + "px";
	listInfoDiv.style.display = "block";
}

lP._hideInfoDiv=function(){
	if (! e('citysearchinfodiv')) return;
	e('citysearchinfodiv').style.display = "none";
	if (e('citysearchinfodiverror')) e('citysearchinfodiverror').style.display = "none";
}

lP._updateShownList=function(inputValue){
	if (! this.div) this._configureDiv();
	if (this.div.scrollTop != null) this.div.scrollTop = 0;

	if (inputValue.length < this.minChars) {
		this._clearResults();
		this.targetBox.className = '';
		this._hide();
		this._showInfoDiv();
		return true;
	}

	this.list = this.searchHandler(inputValue);
	if (this.list.length == 0) {
		this._clearResults();
		this.targetBox.className = 'invalid';
		this._hide();
		this._showInfoDiv();
		return true;
	}

	this.currentIndex = 0;
	this.targetBox.className = '' ;
	this._populateDiv(this.list);
	this.div.childNodes[this.currentIndex].className = "over";
	this._hideInfoDiv();
	this._show();
}

lP.processFullListing=function(target){
	var data = this.fullListHandler();
	(this.data.length == 0) ? this.hide() : this.open(target);
}
lP.setSearchHandler=function(f){this.searchHandler = f;}
lP.setFullListHandler=function(f){this.fullListHandler = f;}
lP._updateRegisteredInputs=function(){
	this._setRegisteredInputs(this.codeInputs, this.targetBox.id, this.getSelectedCode());
	this._setRegisteredInputs(this.valueInputs, this.targetBox.id, this.getSelectedValue());
	this.targetObjects[this.targetBox.id] = this.getSelectedObject();
}
lP._setRegisteredInputs=function(regInputs, targetId, value){
	var inputs = regInputs[targetId];
	if (inputs == null) return;
	for (var i = 0; i < inputs.length; i++){
		if (e(inputs[i]) != null)
			e(inputs[i]).value = value;
	}
}
lP.registerCodeInput=function(sourceFieldId, targetFieldId){
	if (this.codeInputs[sourceFieldId] == null) this.codeInputs[sourceFieldId] = new Array();
	this.codeInputs[sourceFieldId].push(targetFieldId);
}
lP.registerValueInput=function(sourceFieldId, targetFieldId){
	if (this.valueInputs[sourceFieldId] == null) this.valueInputs[sourceFieldId] = new Array();
	this.valueInputs[sourceFieldId].push(targetFieldId);
}
lP.registerNextFocusField=function(fieldId, nextFieldId){
	this.nextFocusField[fieldId] = nextFieldId;
}
lP.registerTargetObject=function (fieldId, targetObject){
	this.targetObjects[fieldId] = targetObject;
}
lP.registerFieldTohide=function(fieldId, fieldToHideId){
	if(this.fieldsTohide[fieldId] == null) this.fieldsTohide[fieldId] = new Array();
	this.fieldsTohide[fieldId].push(fieldToHideId);
}
lP.nextFocus=function(){
	var fieldId = this.nextFocusField[this.targetBox.id];
	if (fieldId != null && e(fieldId) != null)
		e(fieldId).focus();
}
lP.findPosX=function(obj){
	var curleft=0;
	if(obj.offsetParent){
		while(obj.offsetParent){
			curleft+=obj.offsetLeft;
			obj=obj.offsetParent;
		}
	}
	else if(obj.x) curleft+=obj.x;
	return curleft;
}
lP.findPosY=function(obj){
	var curtop=0;
	if(obj.offsetParent){
		while(obj.offsetParent){
			curtop+=obj.offsetTop;
			obj=obj.offsetParent;
		}
	}
	else if(obj.y) curtop+=obj.y;
	return curtop;
}
lP._position=function(){
	var c=this.div;
	c.style.position="absolute";
	c.style.left=this.findPosX(this.targetBox)+"px";
	c.style.top=(this.findPosY(this.targetBox)+18)+"px";
	c.style.display="block";
}
function d(id,text){e(id).value+=text;}
function hideDiv(divId){e(divId).style.display="none";}
function showDiv(divId){e(divId).style.display="block";}

function parseInputString(input){
	if (! input) return null;
	input = input.replace(/\([^)]+\)/g, "");
	input=input.replace(/[éèêëÉÈÊË]/g,"e");
	input=input.replace(/[àâäÀÂÄ]/g,"a");
	input=input.replace(/[ïîìÏÎÌ]/g,"i");
	input=input.replace(/[ôöòÔÖÒ]/g,"o");
	input=input.replace(/[ûüùÛÜÙ]/g,"u");
	input=input.replace(/[çÇ]/g,"c");
	input = input.replace(/[-]/g, " ");
	input = input.replace(/[^A-Za-z0-9\.\/' \-]+/g," ");
	return input.toLowerCase();
}
String.prototype.soundex=function(p){
	p=isNaN(p)?4:p>10?10:p<4?4:p;
	var m={BFPV:1,CGJKQSXZ:2,DT:3,L:4,MN:5,R:6},r=(s=this.toUpperCase().replace(/[^A-Z]/g,"").split("")).splice(0,1);
	for(var i in s){
		for(var j in m){
			if(j.indexOf(s[i])+1&&r[r.length-1]!=m[j]&&r.push(m[j])) break;
		}
	}
	return r.length>p&&(r.length=p),r.join("")+(new Array(p-r.length+1)).join("0");
}
function CityList(){
	logDebug("Creating CityList @507");
	this.cities=new Array();
	this.listInUse=false;
	this.countriesList=new CountriesList();
	this.statesList=new StatesList();
	this.populate();
	logDebug("Created CityList @513");
}
var cP=CityList.prototype;
cP.add=function(ac,co,st,n,f,err,start,end){
	var airport=new Airport(ac,co,st,n,f,err,start,end);
	airport.setText(this.countriesList,this.statesList);
	this.cities.push(airport);
}
cP.populate=function(){populateCities(this);}
cP.sortAirportsByName=function(a,b)
{
	if(a.name==b.name)return 0;
	if(a.name<b.name){return -1};
	if(a.name>b.name){return 1};

}
cP.getFullAirportsList=function(){
	var airports=new Array();
		for(var cpt=0;cpt<this.cities.length;cpt++){
			airports.push(this.cities[cpt]);
		}
	airports.sort(cP.sortAirportsByName);
	return airports;
}
cP.searchAirports=function(value, isFromSubmit){
	value = parseInputString(value);
	var countryList = new CountriesList();
	var stateList = new StatesList();
	
	var results = new Array();
	for (var i = 0; i < 6; i++)
		results[i] = new Array();
	
	var count = 0;
	for (i = 0; i < cityList.cities.length; i++) {
		var airport = cityList.cities[i];
		if (! airport.isEndDateValid()) continue;
		count++;

		if (this.equalsMatch(value, airport.code)) {
			results[0].push(airport);
			continue;
		}
		
		if (this.wordMatch(value, airport.cleanName) || this.equalsMatch(value, airport.text)) {
			results[1].push(airport);
			continue;
		}
		
		var filteredName = cleanUpAbreviation(airport.cleanName);
		if (this.wordMatch(value, filteredName)) {
			results[2].push(airport);
			continue;
		}
		
		var countryName = countryList.countries[airport.country]; 
		if (this.wordMatch(value, countryName)) {
			results[3].push(airport);
			continue;
		}

		var stateName = stateList.states[airport.state];
		if (this.prefixMatch(value, stateName)) {
			results[4].push(airport);
			continue;
		}
		
		count--;
		if (count > nbresults) break;
	}

	if (isFromSubmit == true && count == 0 && value.length > 5) {
		results[5] = this.findSoundex(value);
	}
	
	// Combine results in search order, avoiding duplicated.
	var combinedResults = new Array();
	for (i = 0; i < 6; i++) {
		var subResults = results[i];
		for (var j = 0; j < subResults.length; j++) {
			var airport = subResults[j];
			for (var k = 0; k < combinedResults.length; k++)
				if (airport.code == combinedResults[k].code) break;
			if (k == combinedResults.length) // Not found.
				combinedResults.push(airport);
		}
	}
	
	return combinedResults;
}
cP.equalsMatch=function(value, potentialMatch) {
	return value == parseInputString(potentialMatch);
}
cP.wordMatch=function(value, potentialMatch) {
	if (! potentialMatch) return;
	potentialMatch = parseInputString(potentialMatch);
	var re = new RegExp("\\b" + value);
	return potentialMatch.match(re);
}
cP.prefixMatch=function(value, potentialMatch) {
	if (! potentialMatch) return;
	potentialMatch = parseInputString(potentialMatch);
	return value == potentialMatch.substring(0, value.length);
}
cP.findSoundex=function(value){
	value = parseInputString(value);
	if (value.length <= 4) return;

	var results = new Array();
	for (var i = 0; i < this.cities.length; i++){
		var airport = this.cities[i]; 
		if (airport.cleanName.substring(0,1) == value.substring(0, 1)) {
			var name = parseInputString(airport.cleanName.substring(0, value.length));
			if (name.soundex() == value.soundex() && airport.isEndDateValid())
				results.push(airport);
		}
	}

	for (var i = 0; i < this.cities.length; i++){
		var airport = this.cities[i]; 
		var name = parseInputString(airport.country).substring(0, value.length);
		if (name.soundex() == value.soundex() && airport.isEndDateValid())
			results.push(airport);
	}
	
	return results;
}
function Airport(ac,co,st,n,f,err,stDate,enDate){
	this.code=ac;
	this.state=st;
	this.country=co;
	this.name=n;
	this.flag=f;
	this.cleanName=parseInputString(n);
	this.value=ac;
	this.text=null;
	this.errMsg=err;
	this.startDate=stDate;
	this.endDate=enDate;
}
var aP=Airport.prototype;
aP.getCode=function(){return this.code;}
aP.isEndDateValid=function(){
	if(this.endDate!=null&&this.endDate!=""){
		if(parseDateFromForm(this.endDate)<getGMTServerDate()) return false;
	}
	return true;
}
aP.setText=function(countriesList,statesList){
	this.text=this.name;
	if(this.state==""){
		if(countriesList.countries[this.country]!=null) this.text=this.text+", "+countriesList.countries[this.country];
	}else this.text=this.text+", "+statesList.states[this.state];
	this.text=this.text+" ("+this.code+")";
	return this.text;
}
aP.getValue=function(){return this.name;}
aP.getState=function(){return this.state;}
aP.getCountry=function(){return this.country;}
aP.getName=function(){return this.name;}
aP.getFlag=function(){return this.flag;}
aP.getCleanName=function(){return this.cleanName;}

//-----------Added for SR 2903-----------------------
function setSessionCookie(cookieName, cookieValue, domain) {
	document.cookie = cookieName + "=" + cookieValue + "; path=/;domain=" + domain;	
}

function submitPopUp(formActionValue){
	var resCountry=fl.countryOfResidence.options[fl.countryOfResidence.selectedIndex].value;
//	popUpVal= getCookie('cookiePopUp');
	
//-------------------

messagesList = new MessagesList();
	fl = document.flights;
	dpg = document.flightsPlanitgo;

	logDebug("validateSubmit start " + validateSubmit);
	try{
		messagesList.errorMessages=new Array();

		var checkNeeded = isUsingTripCheckbox() && isRoundTrip();
		var inpageErrorFlag = false;
		origAirport=fetchAiport("org1","origin1");
		if(origAirport==null){
			processErrors();
			return false;
		}else{
			destAirport=fetchAiport("dest1","destination1");
			if(destAirport==null){
				processErrors();
				return false;
			}
		}
		if(origAirport.code==destAirport.code){
		  messagesList.addMessage("SAMEAIRPORTS",destAirport);
			processErrors();
			fl.dest1.focus();
			return false;
		}
		if(typeof(fl.tripType.value)!="string"){
			if(isUsingTripCheckbox() && isRoundTrip()){
				if(!isDateDefined(fl.departure1)){
					fl.departure1.focus();
					return false;
				}
				if(!isDateDefined(fl.departure2)){
					e("ReturnTextbar").style.display = "block";
					fl.departure2.focus();
					return false;
				}
			}else{
				if(!isDateDefined(fl.departure1)){
					fl.departure1.focus();
					return false;
				}
			}
		}else{
			if(fl.tripType.value=="R"){
				if(!isDateDefined(fl.departure1)){
					fl.departure1.focus();
					return false;
				}
				if(!isDateDefined(fl.departure2)){
					e("ReturnTextbar").style.display = "block";
					fl.departure2.focus();
					return false;
				}
			}else{
				if(!isDateDefined(fl.departure1)){
					fl.departure1.focus();
					return false;
				}
			}
		}

		if(!isDatesValidForAirport(origAirport)) inpageErrorFlag=true;
		if(!isDatesValidForAirport(destAirport)) inpageErrorFlag=true;
		if(origAirport.errMsg!=null&&origAirport.errMsg!=""){
			messagesList.addMessage(origAirport.errMsg,origAirport);
			fl.org1.focus();
			inpageErrorFlag=true;
		}
		if(destAirport.errMsg!=null&&destAirport.errMsg!=""){
		  messagesList.addMessage(destAirport.errMsg,destAirport);
			fl.dest1.focus();
			inpageErrorFlag=true;
		}
		if((origAirport.country=="US"||destAirport.country=="US")&&(origAirport.country=="CU"||destAirport.country=="CU")){
			messagesList.addMessage("USACUBA");
			inpageErrorFlag=true;
		}
		if(origAirport.country=="US"&&destAirport.country=="US"){
			messagesList.addMessage("BOTHUSA");
			inpageErrorFlag=true;
		}
		var nbAdults   = Number(getSelected(fl.numberOfAdults));
		var nbInfants  = Number(getSelected(fl.numberOfInfants));
		var nbChildren = Number(getSelected(fl.numberOfChildren));
		var nbYouth    = Number(getSelected(fl.numberOfYouth));
		var totalPass  = nbAdults + nbYouth + nbChildren + nbInfants;

		if(totalPass == 0 || totalPass > 9){
			messagesList.addMessage("NBPASSENGERS");
			inpageErrorFlag=true;
		}
		if(isShown("Infant") && nbInfants > nbAdults){
			messagesList.addMessage("NBINFANTS");
			inpageErrorFlag=true;
		}
		if((nbInfants + nbChildren) > 0 && nbAdults == 0){
			if(dpg.PRIVATE_LABEL.value=="AGENT") {
        messagesList.addMessage("CHILDNOTPERMITTEDWITHYOUTH");
			}
			else{
        messagesList.addMessage("CHILDNOTPERMITTEDWITHYOUTHACO");
			}
			inpageErrorFlag=true;
		}
		if((e("CheckUpgrade").checked) && (e('invalidMessage').style.display == '')){
			if(dpg.PRIVATE_LABEL.value=="AGENT") {
			messagesList.addMessage("INVALIDCERTIFICATE");
			}else{
			messagesList.addMessage("INVALIDCERTIFICATEACO");
			}
			processErrors();
			fl.certificateField.focus();
			return false;
		}
		if ((e("CheckUpgrade").checked) && (fl.certificateField.value.length <7)){
			if(dpg.PRIVATE_LABEL.value=="AGENT") {
			messagesList.addMessage("INVALIDCERTIFICATE");
			}else{
			messagesList.addMessage("INVALIDCERTIFICATEACO");
			}
			fl.certificateField.focus();
			processErrors();
			return false;
		}

		try{
			// Non Can-US sites dont have a promotion code.
			if (typeof validatePromotionCode != "undefined") {
			if(!validatePromotionCode()){
				messagesList.addMessage("PROMOTIONCODEERROR");
				inpageErrorFlag=true;
			}
			}
			if (typeof validateInfantHomePromotion != "undefined") {
			if(!validateInfantHomePromotion()){
				messagesList.addMessage("PROMOTIONCODEINFANTSERROR");
				inpageErrorFlag=true;
			}
			}
		}catch(err){
          logError(err, "citylist@742");
        }
		try {
		if(inpageErrorFlag){
			processErrors();
			return false;
		}
		} catch(err) {
		        logError(err, "citylist@770");
		}
		
		

	} catch (err) {
        logError(err, "@811");
    }


//-----------------

	if(resCountry == "AG" || resCountry == "KY" ||
		resCountry == "TC" || resCountry == "BS" || resCountry == "BM" ||
		resCountry == "LC" || resCountry == "TT" || resCountry == "BB" || 
		resCountry == "JM"){
			//if the popup is not already shown, then show it
			if(getCookie('ACOL_PopupFlag') == null){
				setSessionCookie('ACOL_PopupFlag', 'Popup_Flag_Set', ".aircanada.com");
				initAdSun();
			}else{ //Otherwise don't show the popup again. Just submit the form.
				validateSubmit(formActionValue);
			}
		}
	else if(   resCountry == "AR" || resCountry == "AT" ||
	    resCountry == "BH" || resCountry == "BE" || resCountry == "CL" || 
		resCountry == "CN" || resCountry == "CR" || resCountry == "CZ" || 
		resCountry == "FI" || resCountry == "GR" || resCountry == "HU" || 
		resCountry == "JP" || resCountry == "JO" || resCountry == "MX" || 
		resCountry == "NZ" || resCountry == "PH" || resCountry == "PL" || 
		resCountry == "PT" || resCountry == "QA" || resCountry == "SA" || 
		resCountry == "KR" || resCountry == "ES" || resCountry == "TW" || 
		resCountry == "TH" || resCountry== "UA" || resCountry == "AE" || 
		resCountry == "VN"){
		//if the popup is not already shown, then show it
		if(getCookie('ACOL_PopupFlag') == null){
			setSessionCookie('ACOL_PopupFlag', 'Popup_Flag_Set', ".aircanada.com");
			initAd();
		}else{ //Otherwise don't show the popup again. Just submit the form.
			validateSubmit(formActionValue);
		}
	}
	else{
		validateSubmit(formActionValue);
	}
//		}////////////////////
//	    else{////////////////////
//			validateSubmit(formActionValue);////////////////////
//		}////////////////////
 	showHideHomeDropdown("true");
}



function submitFlightSearchPopUp(){
	var resCountry=fl.countryOfResidence.options[fl.countryOfResidence.selectedIndex].value;
//	popUpVal= getCookie('cookiePopUp');
	 
   //---------------------------

    messagesList = new MessagesList();
	fl = document.flights;
	dpg = document.flightsPlanitgo;

	logDebug("validateSubmit start " + validateSubmit);
	try{
		messagesList.errorMessages=new Array();

		var checkNeeded = isUsingTripCheckbox() && isRoundTrip();
		var inpageErrorFlag = false;
		origAirport=fetchAiport("org1","origin1");
		if(origAirport==null){
			processErrors();
			return false;
		}else{
			destAirport=fetchAiport("dest1","destination1");
			if(destAirport==null){
				processErrors();
				return false;
			}
		}
		if(origAirport.code==destAirport.code){
		  messagesList.addMessage("SAMEAIRPORTS",destAirport);
			processErrors();
			fl.dest1.focus();
			return false;
		}
		if(typeof(fl.tripType.value)!="string"){
			if(isUsingTripCheckbox() && isRoundTrip()){
				if(!isDateDefined(fl.departure1)){
					fl.departure1.focus();
					return false;
				}
				if(!isDateDefined(fl.departure2)){
					e("ReturnTextbar").style.display = "block";
					fl.departure2.focus();
					return false;
				}
			}else{
				if(!isDateDefined(fl.departure1)){
					fl.departure1.focus();
					return false;
				}
			}
		}else{
			if(fl.tripType.value=="R"){
				if(!isDateDefined(fl.departure1)){
					fl.departure1.focus();
					return false;
				}
				if(!isDateDefined(fl.departure2)){
					e("ReturnTextbar").style.display = "block";
					fl.departure2.focus();
					return false;
				}
			}else{
				if(!isDateDefined(fl.departure1)){
					fl.departure1.focus();
					return false;
				}
			}
		}

		if(!isDatesValidForAirport(origAirport)) inpageErrorFlag=true;
		if(!isDatesValidForAirport(destAirport)) inpageErrorFlag=true;
		if(origAirport.errMsg!=null&&origAirport.errMsg!=""){
			messagesList.addMessage(origAirport.errMsg,origAirport);
			fl.org1.focus();
			inpageErrorFlag=true;
		}
		if(destAirport.errMsg!=null&&destAirport.errMsg!=""){
		  messagesList.addMessage(destAirport.errMsg,destAirport);
			fl.dest1.focus();
			inpageErrorFlag=true;
		}
		if((origAirport.country=="US"||destAirport.country=="US")&&(origAirport.country=="CU"||destAirport.country=="CU")){
			messagesList.addMessage("USACUBA");
			inpageErrorFlag=true;
		}
		if(origAirport.country=="US"&&destAirport.country=="US"){
			messagesList.addMessage("BOTHUSA");
			inpageErrorFlag=true;
		}
		var nbAdults   = Number(getSelected(fl.numberOfAdults));
		var nbInfants  = Number(getSelected(fl.numberOfInfants));
		var nbChildren = Number(getSelected(fl.numberOfChildren));
		var nbYouth    = Number(getSelected(fl.numberOfYouth));
		var totalPass  = nbAdults + nbYouth + nbChildren + nbInfants;

		if(totalPass == 0 || totalPass > 9){
			messagesList.addMessage("NBPASSENGERS");
			inpageErrorFlag=true;
		}
		if(isShown("Infant") && nbInfants > nbAdults){
			messagesList.addMessage("NBINFANTS");
			inpageErrorFlag=true;
		}
		if((nbInfants + nbChildren) > 0 && nbAdults == 0){
			if(dpg.PRIVATE_LABEL.value=="AGENT") {
        messagesList.addMessage("CHILDNOTPERMITTEDWITHYOUTH");
			}
			else{
        messagesList.addMessage("CHILDNOTPERMITTEDWITHYOUTHACO");
			}
			inpageErrorFlag=true;
		}
		if((e("CheckUpgrade").checked) && (e('invalidMessage').style.display == '')){
			if(dpg.PRIVATE_LABEL.value=="AGENT") {
			messagesList.addMessage("INVALIDCERTIFICATE");
			}else{
			messagesList.addMessage("INVALIDCERTIFICATEACO");
			}
			processErrors();
			fl.certificateField.focus();
			return false;
		}
		if ((e("CheckUpgrade").checked) && (fl.certificateField.value.length <7)){
			if(dpg.PRIVATE_LABEL.value=="AGENT") {
			messagesList.addMessage("INVALIDCERTIFICATE");
			}else{
			messagesList.addMessage("INVALIDCERTIFICATEACO");
			}
			fl.certificateField.focus();
			processErrors();
			return false;
		}

		try{
			// Non Can-US sites dont have a promotion code.
			if (typeof validatePromotionCode != "undefined") {
			if(!validatePromotionCode()){
				messagesList.addMessage("PROMOTIONCODEERROR");
				inpageErrorFlag=true;
			}
			}
			if (typeof validateInfantHomePromotion != "undefined") {
			if(!validateInfantHomePromotion()){
				messagesList.addMessage("PROMOTIONCODEINFANTSERROR");
				inpageErrorFlag=true;
			}
			}
		}catch(err){
          logError(err, "citylist@742");
        }
		try {
		if(inpageErrorFlag){
			processErrors();
			return false;
		}
		} catch(err) {
		        logError(err, "citylist@770");
		}
		
		

	} catch (err) {
        logError(err, "@811");
    }


   //---------------
	if(resCountry == "AG" || resCountry == "KY" ||
		resCountry == "TC" || resCountry == "BS" || resCountry == "BM" ||
		resCountry == "LC" || resCountry == "TT" || resCountry == "BB" || 
		resCountry == "JM"){
			//if the popup is not already shown, then show it
			if(getCookie('ACOL_PopupFlag') == null){
				setSessionCookie('ACOL_PopupFlag', 'Popup_Flag_Set', ".aircanada.com");
				initAdSun();
			}else{ //Otherwise don't show the popup again. Just submit the form.
				submitFlightSearch();
			}
		}
	else if(   resCountry == "AR" || resCountry == "AT" ||
	    resCountry == "BH" || resCountry == "BE" || resCountry == "CL" || 
		resCountry == "CN" || resCountry == "CR" || resCountry == "CZ" || 
		resCountry == "FI" || resCountry == "GR" || resCountry == "HU" || 
		resCountry == "JP" || resCountry == "JO" || resCountry == "MX" || 
		resCountry == "NZ" || resCountry == "PH" || resCountry == "PL" || 
		resCountry == "PT" || resCountry == "QA" || resCountry == "SA" || 
		resCountry == "KR" || resCountry == "ES" || resCountry == "TW" || 
		resCountry == "TH" || resCountry== "UA" || resCountry == "AE" || 
		resCountry == "VN"){
			//if the popup is not already shown, then show it
			if(getCookie('ACOL_PopupFlag') == null){
				setSessionCookie('ACOL_PopupFlag', 'Popup_Flag_Set', ".aircanada.com");
				initAd();
			}else{ //Otherwise don't show the popup again. Just submit the form.
				submitFlightSearch();
			}
	}
	else{
		submitFlightSearch();
	}
//	}////////////////////
//    else{////////////////////
//		       submitFlightSearch();////////////////////
//	}////////////////////
 showHideFlightMagnetDropdown("true");
}

//--------------for hide drop downs-----------------

function showHideHomeDropdown(isDropdownToBeDisplayed) {
	if(isDropdownToBeDisplayed=="true") {
               
             document.getElementById("numberOfAdults").style.display='none';
			 document.getElementById("numberOfAdults_replacement").value=document.flights.numberOfAdults.options[document.flights.numberOfAdults.selectedIndex].text;
			 document.getElementById("numberOfAdults_replacement").style.display='block';
		
			 document.getElementById("tripType").style.display='none';
			 document.getElementById("textTripType").value=document.flights.tripType.options[document.flights.tripType.selectedIndex].text;
			 document.getElementById("textTripType").style.display='block';

			 document.getElementById("numberOfYouth").style.display='none';
			 document.getElementById("numberOfYouth_replacement").value=document.flights.numberOfYouth.options[document.flights.numberOfYouth.selectedIndex].text;
			 document.getElementById("numberOfYouth_replacement").style.display='block';

			 document.getElementById("numberOfChildren").style.display='none';
			 document.getElementById("numberOfChildren_replacement").value=document.flights.numberOfChildren.options[document.flights.numberOfChildren.selectedIndex].text;
			 document.getElementById("numberOfChildren_replacement").style.display='block';

			 document.getElementById("numberOfInfants").style.display='none';
			 document.getElementById("numberOfInfants_replacement").value=document.flights.numberOfInfants.options[document.flights.numberOfInfants.selectedIndex].text;
			 document.getElementById("numberOfInfants_replacement").style.display='block';

			 document.getElementById("countryOfResidence").style.display='none';
			 document.getElementById("countryOfResidence_replacement").value=document.flights.countryOfResidence.options[document.flights.countryOfResidence.selectedIndex].text;
			 document.getElementById("countryOfResidence_replacement").style.display='block';

			 document.getElementById("classType").style.display='none';
			 document.getElementById("textClassType").value=document.flights.classType.options[document.flights.classType.selectedIndex].text;
			 document.getElementById("textClassType").style.display='block';
	      
		

	
	} else {
		
		document.getElementById("numberOfAdults").style.display='block';
		document.getElementById("numberOfAdults_replacement").style.display='none';
		

		document.getElementById("tripType").style.display='block';
		document.getElementById("textTripType").style.display='none';

		document.getElementById("numberOfYouth").style.display='block';
		document.getElementById("numberOfYouth_replacement").style.display='none';

		document.getElementById("numberOfChildren").style.display='block';
		document.getElementById("numberOfChildren_replacement").style.display='none';

		document.getElementById("numberOfInfants").style.display='block';
		document.getElementById("numberOfInfants_replacement").style.display='none';


		document.getElementById("countryOfResidence").style.display='block';
		document.getElementById("countryOfResidence_replacement").style.display='none';

		document.getElementById("classType").style.display='block';
		document.getElementById("textClassType").style.display='none';

		
}

} 
function showHideFlightMagnetDropdown(isDropdownToBeDisplayed) {
	if(isDropdownToBeDisplayed=="true") {
               
            	        
			 document.getElementById("selectBoxTripType").style.display='none';
			 document.getElementById("textSelectBoxTripType").value=document.flights.selectBoxTripType.options[document.flights.selectBoxTripType.selectedIndex].text;
			 
			 document.getElementById("textSelectBoxTripType").style.display='block';

			 document.getElementById("numberOfAdults").style.display='none';
			 
			 document.getElementById("numberOfAdults_replacement").value=document.flights.numberOfAdults.options[document.flights.numberOfAdults.selectedIndex].text;
			 document.getElementById("numberOfAdults_replacement").style.display='block';
                  
			 document.getElementById("numberOfYouth").style.display='none';
			 document.getElementById("numberOfYouth_replacement").value=document.flights.numberOfYouth.options[document.flights.numberOfYouth.selectedIndex].text;
			 document.getElementById("numberOfYouth_replacement").style.display='block';

			 document.getElementById("numberOfChildren").style.display='none';
			 document.getElementById("numberOfChildren_replacement").value=document.flights.numberOfChildren.options[document.flights.numberOfChildren.selectedIndex].text;
			 document.getElementById("numberOfChildren_replacement").style.display='block';

			 document.getElementById("numberOfInfants").style.display='none';
			 document.getElementById("numberOfInfants_replacement").value=document.flights.numberOfInfants.options[document.flights.numberOfInfants.selectedIndex].text;
			 document.getElementById("numberOfInfants_replacement").style.display='block';

			 document.getElementById("countryOfResidence").style.display='none';
			 document.getElementById("countryOfResidence_replacement").value=document.flights.countryOfResidence.options[document.flights.countryOfResidence.selectedIndex].text;
			 document.getElementById("countryOfResidence_replacement").style.display='block';

			 document.getElementById("classType").style.display='none';
			 document.getElementById("textClassType").value=document.flights.classType.options[document.flights.classType.selectedIndex].text;
			 document.getElementById("textClassType").style.display='block';
	      
		

	
	} else {
		
		

		document.getElementById("selectBoxTripType").style.display='block';
		document.getElementById("textSelectBoxTripType").style.display='none';

		document.getElementById("numberOfAdults").style.display='block';
		document.getElementById("numberOfAdults_replacement").style.display='none';

		document.getElementById("numberOfYouth").style.display='block';
		document.getElementById("numberOfYouth_replacement").style.display='none';

		document.getElementById("numberOfChildren").style.display='block';
		document.getElementById("numberOfChildren_replacement").style.display='none';

		document.getElementById("numberOfInfants").style.display='block';
		document.getElementById("numberOfInfants_replacement").style.display='none';


		document.getElementById("countryOfResidence").style.display='block';
		document.getElementById("countryOfResidence_replacement").style.display='none';

		document.getElementById("classType").style.display='block';
		document.getElementById("textClassType").style.display='none';

		
}

} 

//---------------------SR2903

var messagesList;
function validateSubmit(formActionValue){
	messagesList = new MessagesList();
	fl = document.flights;
	dpg = document.flightsPlanitgo;

	logDebug("validateSubmit start " + validateSubmit);
	try{
		messagesList.errorMessages=new Array();

		var checkNeeded = isUsingTripCheckbox() && isRoundTrip();
		var inpageErrorFlag = false;
		origAirport=fetchAiport("org1","origin1");
		if(origAirport==null){
			processErrors();
			return false;
		}else{
			destAirport=fetchAiport("dest1","destination1");
			if(destAirport==null){
				processErrors();
				return false;
			}
		}
		if(origAirport.code==destAirport.code){
		  messagesList.addMessage("SAMEAIRPORTS",destAirport);
			processErrors();
			fl.dest1.focus();
			return false;
		}
		if(typeof(fl.tripType.value)!="string"){
			if(isUsingTripCheckbox() && isRoundTrip()){
				if(!isDateDefined(fl.departure1)){
					fl.departure1.focus();
					return false;
				}
				if(!isDateDefined(fl.departure2)){
					e("ReturnTextbar").style.display = "block";
					fl.departure2.focus();
					return false;
				}
			}else{
				if(!isDateDefined(fl.departure1)){
					fl.departure1.focus();
					return false;
				}
			}
		}else{
			if(fl.tripType.value=="R"){
				if(!isDateDefined(fl.departure1)){
					fl.departure1.focus();
					return false;
				}
				if(!isDateDefined(fl.departure2)){
					e("ReturnTextbar").style.display = "block";
					fl.departure2.focus();
					return false;
				}
			}else{
				if(!isDateDefined(fl.departure1)){
					fl.departure1.focus();
					return false;
				}
			}
		}

		if(!isDatesValidForAirport(origAirport)) inpageErrorFlag=true;
		if(!isDatesValidForAirport(destAirport)) inpageErrorFlag=true;
		if(origAirport.errMsg!=null&&origAirport.errMsg!=""){
			messagesList.addMessage(origAirport.errMsg,origAirport);
			fl.org1.focus();
			inpageErrorFlag=true;
		}
		if(destAirport.errMsg!=null&&destAirport.errMsg!=""){
		  messagesList.addMessage(destAirport.errMsg,destAirport);
			fl.dest1.focus();
			inpageErrorFlag=true;
		}
		if((origAirport.country=="US"||destAirport.country=="US")&&(origAirport.country=="CU"||destAirport.country=="CU")){
			messagesList.addMessage("USACUBA");
			inpageErrorFlag=true;
		}
		if(origAirport.country=="US"&&destAirport.country=="US"){
			messagesList.addMessage("BOTHUSA");
			inpageErrorFlag=true;
		}
		var nbAdults   = Number(getSelected(fl.numberOfAdults));
		var nbInfants  = Number(getSelected(fl.numberOfInfants));
		var nbChildren = Number(getSelected(fl.numberOfChildren));
		var nbYouth    = Number(getSelected(fl.numberOfYouth));
		var totalPass  = nbAdults + nbYouth + nbChildren + nbInfants;

		if(totalPass == 0 || totalPass > 9){
			messagesList.addMessage("NBPASSENGERS");
			inpageErrorFlag=true;
		}
		if(isShown("Infant") && nbInfants > nbAdults){
			messagesList.addMessage("NBINFANTS");
			inpageErrorFlag=true;
		}
		if((nbInfants + nbChildren) > 0 && nbAdults == 0){
			if(dpg.PRIVATE_LABEL.value=="AGENT") {
        messagesList.addMessage("CHILDNOTPERMITTEDWITHYOUTH");
			}
			else{
        messagesList.addMessage("CHILDNOTPERMITTEDWITHYOUTHACO");
			}
			inpageErrorFlag=true;
		}
		if((e("CheckUpgrade").checked) && (e('invalidMessage').style.display == '')){
			if(dpg.PRIVATE_LABEL.value=="AGENT") {
			messagesList.addMessage("INVALIDCERTIFICATE");
			}else{
			messagesList.addMessage("INVALIDCERTIFICATEACO");
			}
			processErrors();
			fl.certificateField.focus();
			return false;
		}
		if ((e("CheckUpgrade").checked) && (fl.certificateField.value.length <7)){
			if(dpg.PRIVATE_LABEL.value=="AGENT") {
			messagesList.addMessage("INVALIDCERTIFICATE");
			}else{
			messagesList.addMessage("INVALIDCERTIFICATEACO");
			}
			fl.certificateField.focus();
			processErrors();
			return false;
		}

		try{
			// Non Can-US sites dont have a promotion code.
			if (typeof validatePromotionCode != "undefined") {
			if(!validatePromotionCode()){
				messagesList.addMessage("PROMOTIONCODEERROR");
				inpageErrorFlag=true;
			}
			}
			if (typeof validateInfantHomePromotion != "undefined") {
			if(!validateInfantHomePromotion()){
				messagesList.addMessage("PROMOTIONCODEINFANTSERROR");
				inpageErrorFlag=true;
			}
			}
		}catch(err){
          logError(err, "citylist@742");
        }
		try {
		if(inpageErrorFlag){
			processErrors();
			return false;
		}
		} catch(err) {
		        logError(err, "citylist@770");
		}
		if(dpg.PRIVATE_LABEL.value!="AGENT"){
			fl.action=(getCookie("AC-Signon-Cookie"))?"https://www.aircanada.com/secure/aco/flights.do":"http://www.aircanada.com/aco/flights.do";
		}
		if(origAirport!=null&&destAirport!=null){

		//SR97502801-------------------------------------------------------------
		var country_lang=checkLangCookie("new_lang_pref");
		var url ="http://www.aircanada.com/en/customercare/othercountries.html";
		if (document.flights.countryOfResidence.value == "O"){
			if(country_lang == "english" || country_lang == "us")
				url = "http://www.aircanada.com/en/customercare/othercountries.html";
			else if(country_lang == "french")
				url = "http://www.aircanada.com/fr/customercare/othercountries.html";
			else if(country_lang == "de")
				url = "http://www.aircanada.com/de/customercare/othercountries.html";
			else
				url = "http://www.aircanada.com/it/customercare/othercountries.html";
				
		    document.location = url;
		    return;
		}
		//-----------------------------------------------------------------------

			try {
			checkforTyrolean(origAirport.code,destAirport.code);
			var cookieLife= 5*365;
			setCookie("cityCookie",fl.origin1.value,cookieLife,"/");
			var isReqFromOffers=false,agentRequest=false,promotionCodeReq=false;
			if(location.pathname.indexOf("offers")>-1) isReqFromOffers=true;
			if(dpg.PRIVATE_LABEL.value=="AGENT")	agentRequest=true;
			if(e('Promotion Code')!=null){
				var resCountry=fl.countryOfResidence.options[fl.countryOfResidence.selectedIndex].value;
//2799				if(resCountry=="CA"||resCountry=="US"){
//					if(fl.promotionCode!=null&&fl.promotionCode.value!="") promotionCodeReq=true;
				if(fl.promotionCode!=null&&fl.promotionCode.value!="") {
					promotionCodeReq=true;
//2799 replaced with above 2 lines
				}else{
					dpg.NTP_AUTHORIZATION.value="true";
    	            fl.promotionCode.value = "";
				}
			}
			} catch(err) {
			        logError(err, "citylist@793");
			}
			if(promotionCodeReq){
				try {
				fl.promotionCode.focus();
				var flag=checkAgentDetails();
				if(flag){
					if(document.flights.fromHomePage.value == "YES"){
						var objErrsub1;
						try{
							fl.submit();
						}catch(objErrsub1) {logError(objErrsub1, "@775")}
						WDSWaitingImage.pleaseWait("anim_waiting-bar");
					}else{
					setNTPFormFields("Flights");
		      document.FlightSearchNTPRequestForm.submit();
					WDSWaitingImage.pleaseWait("anim_waiting-bar");
						var objErrsub;
						try{
							fl.submit();
						}catch(objErrsub) {logError(objErrsub, "@784")}
					}
				}
				} catch(err) {
				        logError(err, "citylist@817");
				}
			}else{
				try {
				if((agentRequest&&isReqFromOffers)){
					WDSWaitingImage.pleaseWait("anim_waiting-bar");
					var objErrsub2;
					try{
						fl.submit();
					}catch(objErrsub2) {logError(objErrsub2, "@793")}
				}else{
					try {
					setFormFields();
					if(agentRequest&&!isReqFromOffers) setFlightSearchCookie("ADO");
					else if(!agentRequest&&!isReqFromOffers) setFlightSearchCookie("ACO");
					if(formActionValue)	dpg.action=formActionValue;
					WDSWaitingImage.pleaseWait("anim_waiting-bar");
					var objErr3
					try{
						dpg.submit();
					}catch(objErr3) {logError(objErr3, "@803")}
					return;
					} catch(err) {
					        logError(err, "citylist@69");
					}
				}
				WDSWaitingImage.pleaseWait("anim_waiting-bar");
				} catch(err) {
				        logError(err, "citylist@841");
				}
			}
		}

	} catch (err) {
        logError(err, "@811");
    }
	logDebug("validateSubmit end ");
	return false;
}
function refreshDiv(divName,contents){
	e(divName).innerHTML=contents;
	(contents!="")?showDiv(divName):hideDiv(divName);
}
function processErrors(){
	var contents="",image="<img src=\"http://www.aircanada.com/shared/images/common/i_error.gif\" width=\"20\" height=\"20\" alt=\"!\" border=\"0\"/>";
	if(messagesList.errorMessages.length>0){
		contents+="<table  width='100%'>";
		for(var cpt=0;cpt<messagesList.errorMessages.length;cpt++){
			if(cpt==1) image="";
			contents+="<tr><td class='errors'>"+image+"</td><td class='errors'>"+messagesList.errorMessages[cpt]+"</td></tr>";
		}
		contents+="</table>";
	}
	refreshDiv("errorMsg",contents);
}
function fetchAiport(nameFieldId,codeFieldId){
	if (nameFieldId == null || codeFieldId == null) return null;
	if (! e(nameFieldId) || ! e(codeFieldId)) return null;

	var msgToUse = (nameFieldId.indexOf("dest") == 0) ? "NORESULTSDESTINATION" : "NORESULTSORIGIN";
	var airportName=e(nameFieldId).value;
	var airportCode=e(codeFieldId).value;
	var airport=list.targetObjects[nameFieldId];
	if (airport == null && airportCode != "") {
		var tempAirport = getAirportFromCode(airportCode);
		if (tempAirport != null && tempAirport.text == airportName)
			airport = getAirportFromCode(airportCode);
	}
	if(airportName!="")
	{
		if(airport!=null&&airport.text==airportName){
			e(nameFieldId).className="";
			return airport;
		}else{
			e(nameFieldId).className="";
			list.targetBox=e(nameFieldId);
			var airPortslist = searchAirports(airportName,true);
			if(airPortslist.length == 1)
			{
				  e(codeFieldId).value=airPortslist[0].code;
				  e(nameFieldId).value=airPortslist[0].text;
					return airPortslist[0];
			}
			else if(airPortslist.length > 1){
				messagesList.addMessage("AMBIGUOUS");
				e(nameFieldId).className="invalid";
				processErrors();
				e(nameFieldId).focus();
				list.open(airPortslist);
			  return null;
			}
		}
	}
  messagesList.addMessage(msgToUse);
  e(nameFieldId).className="invalid";
  processErrors();
  e(nameFieldId).focus();
  return null;
}
function isDate1BeforeDate2(theDate1,theDate2){
	if(theDate1.getFullYear()!=theDate2.getFullYear()) return theDate1.getFullYear()<theDate2.getFullYear();
	if(theDate1.getMonth()!=theDate2.getMonth()) return theDate1.getMonth()<theDate2.getMonth();
	return theDate1.getDate()<theDate2.getDate();
}
function isDate1equalsDate2(theDate1,theDate2){
	return theDate1.getFullYear()==theDate2.getFullYear()&&theDate1.getMonth()==theDate2.getMonth()&&theDate1.getDate()==theDate2.getDate();
}
function parseDateFromForm(text){
	text = text.replace(/\*/,'');
	var parts=text.split(/[-\/]/),origPartsLenght=parts.length;
	if(parts.length<2||parts.length>3) return null;
	if(parts.length==2)	parts[2]=String((getGMTServerDate()).getFullYear());
	else if(parts[2].length<=2)	parts[2]=String(2000+Number(parts[2]));
	if(parts[0].length<1||parts[0].length>2||! parts[0].match(/[0-9]+/)) return null;
	if(parts[1].length<1||parts[1].length>2||! parts[1].match(/[0-9]+/)) return null;
	if(parts[2].length==0||parts[2].length==3||parts[2].length>4||! parts[2].match(/[0-9]+/))	return null;
	var newDate=new Date(parts[2],Number(parts[1])-1,parts[0]);
	return newDate;
}
function isDatesValidForAirport(airport){
	if(airport.startDate==null&&airport.endDate==null) return true;
	var msg;
	var roundTrip = isUsingTripCheckbox() && isRoundTrip();
	var inboundDate = parseDateFromForm(e("departure1").value);
	var outboundDate;
	if(roundTrip) outboundDate=parseDateFromForm(e("departure2").value);
	var airportStart;
	var airportEnd;
	var exclusion = false;
	if(airport.startDate!=""&&airport.startDate!=null){
		exclusion=airport.startDate.indexOf("*")!=-1;
		airportStart=parseDateFromForm(airport.startDate);
	}
	if(airport.endDate!=""&&airport.endDate!=null){
		exclusion=airport.endDate.indexOf("*")!=-1 || exclusion;
		airportEnd=parseDateFromForm(airport.endDate);
	}
	if(exclusion){
		 if((isDate1BeforeDate2(airportStart,inboundDate)||isDate1equalsDate2(airportStart,inboundDate))&&(isDate1BeforeDate2(inboundDate,airportEnd)||isDate1equalsDate2(inboundDate,airportEnd))){
			 e("departure1").className="invalid";
			 messagesList.addMessage("EXCLUDEDDATES",airport);
			 return false;
		 }
		 if(roundTrip){
			 if((isDate1BeforeDate2(airportStart,outboundDate)||isDate1equalsDate2(airportStart,outboundDate))&&(isDate1BeforeDate2(outboundDate,airportEnd)||isDate1equalsDate2(outboundDate,airportEnd))){
				 e("departure2").className="invalid";
				 messagesList.addMessage("EXCLUDEDDATES",airport);
				 return false;
		    }
		 }
		e("departure1").className="";
		e("departure2").className="";
		return true;
	}
	if((airportStart!=null||airportEnd!=null)&&(airportStart==null||airportEnd==null)){
		if(airportStart!=null){
			if(isDate1BeforeDate2(inboundDate,airportStart)){
				e("departure1").className="invalid";
				messagesList.addMessage("BADSTARTDATE",airport);
				return false;
			}
		}
		if(airportEnd!=null&&roundTrip){
			if(isDate1BeforeDate2(airportEnd,outboundDate)){
				e("departure2").className="invalid";
				messagesList.addMessage("BADENDDATE",airport);
				return false;
			}
		}else if(airportEnd!=null){
			if(isDate1BeforeDate2(airportEnd,inboundDate)){
				e("departure1").className="invalid";
				messagesList.addMessage("BADENDDATE",airport);
				return false;
			}
		}
	}else if(airportStart!=null&&airportEnd!=null){
		var isRoundTripInvalid=false,startAndInbondDatesInvalid=false, oneWayInvalid=false;
		if(roundTrip){ isRoundTripInvalid=isDate1BeforeDate2(airportEnd,outboundDate);}
		else{oneWayInvalid=isDate1BeforeDate2(airportEnd,inboundDate);}
		startAndInbondDatesInvalid=isDate1BeforeDate2(inboundDate,airportStart);
		if(isRoundTripInvalid) e("departure2").className="invalid";
		if(startAndInbondDatesInvalid||oneWayInvalid) e("departure1").className="invalid";
		if(startAndInbondDatesInvalid||isRoundTripInvalid||oneWayInvalid){
			messagesList.addMessage("BADBOTHDATES",airport);
			return false;
		}
	}
	e("departure1").className="";
	e("departure2").className="";
	return true;
}

function checkFlightType(domestic,transborder,international,faredriven){
	countrydisplay=dpg.PRIVATE_LABEL.value!="AGENT"&&!(getCookie("AC-Signon-Cookie")&&getCookie("AC-Session-Cookie"));
	if((international||!faredriven)){
		//code deleted for sr 97502979
//		show('Shop');

		//######################[ R24-SR97502187 ]########################
		if (isShown('more_options')){
		  hide('search_button1');
		  hide('search_button2');
		  hide('search_button3');
		}else{
		  hide('search_button1');
		  show('search_button2');
		  hide('search_button3');
		}
		//################################################################
	}else{
		hide('Shop');

		//######################[ R24-SR97502187 ]########################
			if (isShown('more_options')){
			  hide('search_button1');
			  hide('search_button2');
			  show('search_button3');
			}else{
			  if(countrydisplay){
				  e('search_button1').style.display='';
				  hide('search_button2');
				  hide('search_button3');
			  }else{
				  hide('search_button1');
				  e('search_button2').style.display='';
				  hide('search_button3');
			  }
			}
		//################################################################
	}
	if(international || CARIBBEAN_FLAG || transborder){
		hide('Infant');
		show('InfantText');
		hide('SeniorText');
	}else{
		show('Infant');
		hide('InfantText');
		show('SeniorText');
	}
	var isSearchType1 = fl.searchType && fl.searchType[1].checked;
	if(international || !faredriven)
		e('Flexible').style.display = (isSearchType1 ? 'none' : 'block');
	else
		hide('Flexible');
	international && isSearchType1 ? show('Class') : hide('Class');

	if(countrydisplay){		

/**
		var corCookie = getCookie("COR-Cookie");		
		corValue=fl.countryOfResidence.options[fl.countryOfResidence.selectedIndex].value;
		//corValue=corCookie;
		if(corValue!="CA"&&corValue!="US"&&corValue!="O"&&POS==""){
			countryVal=getCookie('country_pref');
			if(countryVal=="CA"||countryVal=="US"||countryVal==COUNTRY_POS.toString().match(countryVal)){
				if(corCookie != CanadianCOR.toString().match(corCookie)&& corCookie!= CARIBBEAN.toString().match(corCookie)){
					popSelectionData(fl.countryOfResidence,countryVal);
				}
				else{
					popSelectionData(fl.countryOfResidence,corCookie);
				}
			}
			else{
				popSelectionData(fl.countryOfResidence,"CA");
			}
		}
		else { //SR97502801....
			popSelectionData(fl.countryOfResidence,corCookie);
		}
*/

		var corCookie = getCookie("COR-Cookie");
		var countryVal=getCookie('country_pref');
		if (corCookie != "")
			popSelectionData(fl.countryOfResidence,corCookie);
		else
			popSelectionData(fl.countryOfResidence,countryVal);

		show('ResidenceBar');
	}else{
		hide('ResidenceBar');

		//########[ R24-SR97502187 ]########
		if(e("search_button3").style.display == ''){
			hide("search_button1")
			hide("search_button2")
		}else{
			e('search_button2').style.display='';
		}
	}
	if(e('search_pref_section')){
		if(international){
			if(e('calltable-search')) e('calltable-search').style.borderBottom='1px solid #999999';
		}else{
			if(e('calltable-search')) e('calltable-search').style.borderBottom=0;
		}
	}
	//countryValue=getCookie("country_pref");
	//countryValue=getCookie("COR-Cookie");  //SR97502801
	countryValue=fl.countryOfResidence.options[fl.countryOfResidence.selectedIndex].value;
// 2799
//	if (e('Promotion Code')!= null){
//		if(countryValue == "CA" || countryValue == "US") {
             		show('Promotion Code');
//2799             	}else
//			hide('Promotion Code');
//	}
	if(e('Direct')){
		var aBookingFlowVal=checkBookingFlow();
		e('Direct').style.display=(aBookingFlowVal.indexOf("SCHEDULE")!=-1||aBookingFlowVal=="COMPLEX"||aBookingFlowVal=="AGENT_COMPLEX")?'block':'none';
	}
}

function checkFlightSegmentType(origCode,destcode){
	var tempOrigAirport=getAirportFromCode(origCode),tempDestAirport=getAirportFromCode(destcode);
	if(tempOrigAirport==null||tempDestAirport==null) return "";
	var depCountry=tempOrigAirport.country, depCityCode=tempOrigAirport.code;
	var arrCountry=tempDestAirport.country, arrCityCode=tempDestAirport.code;
	return checkforIntnl(depCountry,arrCountry,depCityCode,arrCityCode);
}
function checkBookingFlow(){
	var hasDomestic=false,hasTransborder=false,hasInternational=false,allFaredriven=true,i,tempFlightType;
	depCity=fl.origin1.value;
	arrCity=fl.destination1.value;
	if(depCity!=""&&arrCity!=""){
		tempFlightType=checkFlightSegmentType(depCity,arrCity);
		if(tempFlightType=="Domestic") hasDomestic=true;
		else if(tempFlightType=="Transborder") hasTransborder=true;
		else if(tempFlightType=="International") hasInternational=true;
		if((tempFlightType=="Domestic"||tempFlightType=="Transborder")&&!checkforFareDriven(depCity,arrCity)) allFaredriven=false;
		if(CARIBBEAN_FLAG) allFaredriven=false;
	}
	//SR97502207
	//var listOAL = isOAL(depCity,arrCity);
	//if(!( listOAL == "" || listOAL == "AC")){
	//	return (dpg.PRIVATE_LABEL.value=="AGENT")?"AGENT_SCHEDULE":"SCHEDULE";
	//}else{
	if(((hasDomestic||hasTransborder )&&allFaredriven)||CARIBBEAN_FLAG){
		return (dpg.PRIVATE_LABEL.value=="AGENT")?"AGENT_DOMTRANSB":"DOMTRANSB";
	}else if((hasDomestic||hasTransborder)||hasInternational){
		if(fl.searchType[0].checked){
			return (dpg.PRIVATE_LABEL.value=="AGENT")?"AGENT_INTERNATIONAL":"INTERNATIONAL";
		}else{
			return (dpg.PRIVATE_LABEL.value=="AGENT")?"AGENT_SCHEDULE":"SCHEDULE";
			}
		}
	//}
	return "";
}
function searchAirports(value, isFromSubmit){
	return cityList.searchAirports(value, isFromSubmit);
}
function getAllAirportsList(){
	var resultAirportsList = cityList.getFullAirportsList();
	return	resultAirportsList;
}
function getCityName(airportCode){
	for(var i=0;i<cityList.cities.length;i++){
		if(cityList.cities[i].code==airportCode.toUpperCase()) return cityList.cities[i].text;
	}
	return "";
}
function getAirportFromCode(airportCode){
	for(var i=0;i<cityList.cities.length;i++){
		if(cityList.cities[i].code==airportCode.toUpperCase())	return cityList.cities[i];
	}
	return null;
}

function assertValidDate(){
	checkNeeded = isUsingTripCheckbox() && isRoundTrip();
	if(checkNeeded&&( getDateNumber("Dep")==getDateNumber("Ret") )&&( fl.departTime1.options[fl.departTime1.selectedIndex].value>=fl.departTime2.options[fl.departTime2.selectedIndex].value )){
		departTime=fl.departTime1.options[fl.departTime1.selectedIndex].value;
		for(c=0;c<fl.departTime2.length;c++){
			if(fl.departTime2.options[c].value==departTime){
				fl.departTime2.selectedIndex=c;
				return;
			}
		}
		fl.departTime2.selectedIndex=c-1;
	}
}

function WDSWaitingImage(){
	this.IMG_ID="moveimageID";
	this.DIV_ID="inpageFlightsWaitPage";
	this.pleaseWait=WDSWaitingImage_pleaseWait;
}
var WDSWaitingImage=new WDSWaitingImage();
function WDSWaitingImage_pleaseWait(waitingImg){
	var waitingImageDiv=e(WDSWaitingImage.DIV_ID),container=e("inpageSearchPage"),wiSrc="/shared/images/common/";
	wiSrc+=waitingImg+".gif";
	if(e(WDSWaitingImage.IMG_ID))	e(WDSWaitingImage.IMG_ID).src=wiSrc;
	else WDSTrace.dump("WDSWaitingImage_pleaseWait : element id = WDSWaitingImage.IMG_ID NOT FOUND and MANDATORY");
	waitingImageDiv.style.display="block";
	waitingImageDiv.style.visibility="visible";
	container.style.display="none";
	self.scrollTo(0,0);
}
function popSelectionData(optName,value){
	for(var i=0;i<optName.length;i++){
		if(optName.options[i].value==value){
			optName.selectedIndex=i;
			break;
		}
	}
}
function checkforIntnl(depCountry,arrCountry,depCityCode,arrCityCode){
	POS="";
	POS_arr="";
	if(depCountry==""||arrCountry=="") return "";
	else if(depCountry=="CA"&&arrCountry=="CA") return "Domestic";
	else if((depCountry=="CA"&&arrCountry=="US")||(depCountry=="US"&&arrCountry=="CA")||(depCountry=="US"&&arrCountry=="US")) return "Transborder";
	else{
		if(((depCountry=="CA" || depCountry=="US") &&IsCaribbean(arrCountry,arrCityCode))||
		   (IsCaribbean(depCountry,depCityCode)&& (arrCountry=="CA" || arrCountry=="US"))||
		   (IsCaribbean(depCountry,depCityCode)&&IsCaribbean(arrCountry,arrCityCode))){
			CARIBBEAN_FLAG=true;
			if(IsCaribbean(depCountry)) POS=depCountry;
			if(IsCaribbean(arrCountry)) POS_arr=arrCountry;
			return "Domestic";
		}else if(((depCountry=="CA" || depCountry=="US") &&arrCountry==SP_CARIBBEAN)||(depCountry==SP_CARIBBEAN&& (arrCountry=="CA" || depCountry=="US"))||(depCountry==SP_CARIBBEAN&&arrCountry==SP_CARIBBEAN)){
			CARIBBEAN_FLAG=true;
			return "Domestic";
		}else{
			for(var i=0;i<COUNTRY_POS.length;i++){
				if(depCountry==COUNTRY_POS[i]){
					POS=depCountry;
					break;
				}
				if(arrCountry==COUNTRY_POS[i]) POS_arr=arrCountry;
			}
			return "International";
		}
	}
}
function checkforFareDriven(origCode,destcode){
	var tempOrigAirport=getAirportFromCode(origCode),tempDestAirport=getAirportFromCode(destcode);
	if(tempOrigAirport==null||tempDestAirport==null) return false;
	var depAirportCountryCity=tempOrigAirport.country, depAirportCode=tempOrigAirport.code;
	var arrAirportCountryCity=tempDestAirport.country, arrAirportCode=tempDestAirport.code;
	var aFlightType=checkforIntnl(depAirportCountryCity,arrAirportCountryCity,depAirportCode,arrAirportCode);
	return (aFlightType=="Domestic"||aFlightType=="Transborder")?tempOrigAirport.flag&&tempDestAirport.flag:true;
}
function execShowWarning(){return e("ip-depdate2")&&e("ip-depdate1within")&&e("ip-depdate2within")&&e("ip-passenger")&&e("ip-infants")&&e("ip-residence");}

function showAndHide(formSubmit,fromFacade){
	fl = document.flights;
	dpg = document.flightsPlanitgo;
	var hasDomestic=false, hasTransborder=false, hasInternational=false, allFaredriven=true, i, tempFlightType;
	CARIBBEAN_FLAG=false;
	if (e('Promotion Code')!= null){
		 if(fl.org1.value == ""){
	    fl.org1.value = document.FlightSearchNTPRequestForm.origin.value;
			fl.origin1.value=getCityName(fl.org1.value);
		 }
	   if ((fl.dest1.value == "") && (fl.dest1.value == null)){
	    fl.dest1.value = document.FlightSearchNTPRequestForm.destination.value;
		  fl.destination1.value=getCityName(fl.dest1.value);
		 }
	}

	if(formSubmit){
		if(!(fl.org1.value == "")){
			if(fl.org1.value.length == 3){
				fl.origin1.value = fl.org1.value;
				fl.org1.value=getCityName(fl.org1.value);
			}else if(fl.org1.value.indexOf(" - ") != -1){
				fl.origin1.value = fl.org1.value.substring(fl.org1.value.indexOf(" - ")+3,fl.org1.value.length);
				fl.org1.value=getCityName(fl.origin1.value);
			}
		}
		if(!(fl.dest1.value =="")){
			if(fl.dest1.value.length == 3){
				fl.destination1.value=fl.dest1.value;
				fl.dest1.value=getCityName(fl.dest1.value);
			}else if(fl.dest1.value.indexOf(" - ") != -1){
				fl.destination1.value = fl.dest1.value.substring(fl.dest1.value.indexOf(" - ")+3,fl.dest1.value.length);
				fl.dest1.value=getCityName(fl.destination1.value);
			}
		}
	}
	depCity=fl.origin1.value;
	arrCity=fl.destination1.value;
	if(depCity!=""&&arrCity!=""){
		tempFlightType=checkFlightSegmentType(depCity,arrCity);
		if(tempFlightType=="Domestic") hasDomestic=true;
		else if(tempFlightType=="Transborder") hasTransborder=true;
		else if(tempFlightType=="International") hasInternational=true;
		if(!checkforFareDriven(depCity,arrCity)) allFaredriven=false;
		if(CARIBBEAN_FLAG) allFaredriven=true;

		// Code added for the TR Item no. 2634,Revised Only for HK edition
		var depCountry =  getAirportFromCode(depCity).country;
		var arrCountry =  getAirportFromCode(arrCity).country;
		if(depCountry != "" && arrCountry != ""){
			if(arrCountry == "HK" || depCountry == "HK")
				fl.Flexible.checked= true;
			else
				fl.Flexible.checked= false;
		}
		//End of Code Change
	}
	WITHHOLD_SURCHARG=false;
	if(hasTransborder|| hasInternational){
		var tempOrgCity=getAirportFromCode(depCity).country;
		if(tempOrgCity=="US") WITHHOLD_SURCHARG=true;
	}
	checkFlightType(hasDomestic,hasTransborder,hasInternational,allFaredriven);

	if (!fromFacade && formSubmit)
		showWarning();


	//###############[ SR97502401 ]#################
	// Hide 'Shop by' for International flights
	//##############################################
  var pc = e("promotionCode") ? e("promotionCode").value : "";
	if( pc != "" || e("CheckUpgrade").checked ){
			if (fl.searchType) fl.searchType[0].checked=true;
			fl.Flexible.checked=false;
			fl.classType.value="E";
			hide("Shop");
		  	hide("Flexible");
		  	hide("Class");
	}
}

function checkEmbeddedTransaction(bookingFlow){
	if(bookingFlow.indexOf("COMPLEX_DOMTRANSB")!=-1) return "FlexPricerComplexItineraryAvailabilityServlet";
	else if(bookingFlow.indexOf("DOMTRANSB")!=-1||bookingFlow.indexOf("INTERNATIONAL")!=-1)	return "FlexPricerAvailabilityServlet";
	else if(bookingFlow.indexOf("SCHEDULE")!=-1) return "AirAvailabilityServlet";
	else return "AirComplexAvailabilityServlet";
}

// #### R39: SR297502887 - new function added: isDOT() ####
function isDOT(){
	//Checks to see if its a D.O.T intinerary
	//Definition of D.O.T Itinerary:
	//==============================
	//	. Originating in US to CA
	//	. Originating in CA to US
	//	. Originating in US to an international destination
	//	. Originating from an international origin to US
	origCode=fl.origin1.value;
	destCode=fl.destination1.value;
	var tempOrigAirport=getAirportFromCode(origCode);
	var tempDestAirport=getAirportFromCode(destCode);
	var depCountry=tempOrigAirport.country;
	var depCityCode=tempOrigAirport.code;
	var arrCountry=tempDestAirport.country;
	var arrCityCode=tempDestAirport.code;
	var hasDomestic=false, hasTransborder=false, hasInternational=false, allFaredriven=true, tempFlightType;
	depCity=fl.origin1.value;
	arrCity=fl.destination1.value;
	if(depCity!=""&&arrCity!=""){
		tempFlightType=checkFlightSegmentType(depCity,arrCity);
		if(tempFlightType=="Domestic") hasDomestic=true;
		else if(tempFlightType=="Transborder") hasTransborder=true;
		else if(tempFlightType=="International") hasInternational=true;
	}
	if (hasTransborder || (hasInternational && (depCountry == "US" || arrCountry == "US")))
		return true;
	else 
		return false;
}

function setFormFields(){
	fl = document.flights;
	dpg = document.flightsPlanitgo;
	
	var aBookingFlowVal=checkBookingFlow();
	dpg.BOOKING_FLOW.value=aBookingFlowVal;
	if(CARIBBEAN_FLAG) DATE_VALUE_PLANITGO="5";
	if(aBookingFlowVal.indexOf("DOMTRANSB")!=-1){
		if(fl.classType.selectedIndex<=1){
			dpg.COMMERCIAL_FARE_FAMILY_1.value="NORAMECO";
			dpg.COMMERCIAL_FARE_FAMILY_2.value="EXCLUSIVE";
		}else{
			dpg.COMMERCIAL_FARE_FAMILY_1.value="EXCLUSIVE";
			dpg.COMMERCIAL_FARE_FAMILY_2.value="";
		}
		if(CARIBBEAN_FLAG){
			var triptype="";
			if(typeof(fl.tripType.value)!="string"){
				if(fl.tripType[0].checked) triptype=fl.tripType[0].value;
				else if(fl.tripType[1].checked)	triptype=fl.tripType[1].value;
			}else{
				triptype=fl.tripType.value;
			}

			if(triptype=="O"){
				//dpg.COMMERCIAL_FARE_FAMILY_1.value="YOUNGFUNUS";
				//dpg.COMMERCIAL_FARE_FAMILY_2.value="EXCLUSIVE";
				//SR97502918_____________________________________
				//dpg.COMMERCIAL_FARE_FAMILY_1.value="SUNOWECO";
				//dpg.COMMERCIAL_FARE_FAMILY_2.value="SUNOWEXCLU";
				dpg.COMMERCIAL_FARE_FAMILY_1.value="NBMSUN";
				dpg.COMMERCIAL_FARE_FAMILY_2.value="";
				//_______________________________________________
			}else if(triptype=="R"){
				//dpg.COMMERCIAL_FARE_FAMILY_1.value="CFA7M5SY";
				//dpg.COMMERCIAL_FARE_FAMILY_2.value="YOUNGFUNUS";
				//dpg.COMMERCIAL_FARE_FAMILY_3.value="EXCLUSIVE";
				//SR97502918_____________________________________
				//dpg.COMMERCIAL_FARE_FAMILY_1.value="SUNOWECO";
				//dpg.COMMERCIAL_FARE_FAMILY_2.value="SUNOWEXCLU";
				dpg.COMMERCIAL_FARE_FAMILY_1.value="NBMSUN";
				dpg.COMMERCIAL_FARE_FAMILY_2.value="";
				//_______________________________________________
			}
		}
		dpg.PRICING_TYPE.value="C";
		dpg.DISPLAY_TYPE.value="2";
		dpg.CORPORATE_NUMBER_1.value="URIGET";
		dpg.CORPORATE_NUMBER_2.value="BHVQLN";
		dpg.TYPE_OF_CORPORATE_FARE.value="2";
		dpg.DATE_RANGE_QUALIFIER_1.value="C";
		dpg.DATE_RANGE_VALUE_1.value=DATE_VALUE_PLANITGO;


			if(typeof(fl.tripType.value)!="string"){
				if(fl.tripType[0].checked){
					dpg.DATE_RANGE_QUALIFIER_2.value="C";
					dpg.DATE_RANGE_VALUE_2.value=DATE_VALUE_PLANITGO;
				}
			}else{
				if(fl.tripType.value=="R"){
					dpg.DATE_RANGE_QUALIFIER_2.value="C";
					dpg.DATE_RANGE_VALUE_2.value=DATE_VALUE_PLANITGO;
				}
			}

	}else if(aBookingFlowVal.indexOf("INTERNATIONAL")!=-1){
		//SR97502918_______________________________________		
		//dpg.COMMERCIAL_FARE_FAMILY_1.value="WORLTRAVEL";
		var triptype="";
		if(typeof(fl.tripType.value)!="string"){
			if(fl.tripType[0].checked) triptype=fl.tripType[0].value;
			else if(fl.tripType[1].checked)	triptype=fl.tripType[1].value;
		}else{
			triptype=fl.tripType.value;
		}
		if(triptype=="O"){
			dpg.COMMERCIAL_FARE_FAMILY_1.value="NBMOW";
		}else if(triptype=="R"){
			dpg.COMMERCIAL_FARE_FAMILY_1.value="FLEXIWDREV";
		}
		//_________________________________________________
		
		dpg.PRICING_TYPE.value="I";
		if(!fl.Flexible.checked){
			dpg.DATE_RANGE_QUALIFIER_1.value="C";
			dpg.DATE_RANGE_VALUE_1.value="0";
			dpg.DATE_RANGE_VALUE_2.value="0";
			if(typeof(fl.tripType.value)!="string"){
				if(fl.tripType[0].checked){
					dpg.DISPLAY_TYPE.value="1";
					dpg.DATE_RANGE_QUALIFIER_2.value="C";
				}else dpg.DISPLAY_TYPE.value="2";
			}else{
				if(fl.tripType.value=="R"){
					dpg.DISPLAY_TYPE.value="1";
					dpg.DATE_RANGE_QUALIFIER_2.value="C";
				}else dpg.DISPLAY_TYPE.value="2";
			}

		}else{
			if(typeof(fl.tripType.value)!="string"){
				if(fl.tripType[1].checked){
					dpg.DISPLAY_TYPE.value="2";
					dpg.DATE_RANGE_QUALIFIER_1.value="C";
					dpg.DATE_RANGE_VALUE_1.value="5";
					dpg.DATE_RANGE_VALUE_2.value="5";
				}else{
					dpg.DISPLAY_TYPE.value="1";
					dpg.DATE_RANGE_QUALIFIER_1.value="C";
					dpg.DATE_RANGE_VALUE_1.value="3";
					dpg.DATE_RANGE_QUALIFIER_2.value="C";
					dpg.DATE_RANGE_VALUE_2.value="3";
				}
			}else{
				if(fl.tripType.value=="O"){
					dpg.DISPLAY_TYPE.value="2";
					dpg.DATE_RANGE_QUALIFIER_1.value="C";
					dpg.DATE_RANGE_VALUE_1.value="5";
					dpg.DATE_RANGE_VALUE_2.value="5";
				}else{
					dpg.DISPLAY_TYPE.value="1";
					dpg.DATE_RANGE_QUALIFIER_1.value="C";
					dpg.DATE_RANGE_VALUE_1.value="3";
					dpg.DATE_RANGE_QUALIFIER_2.value="C";
					dpg.DATE_RANGE_VALUE_2.value="3";
				}
			}
		}
	}
	setFareFamily();
	var country;
	if(dpg.PRIVATE_LABEL.value!="AGENT"){
		var signOnCookie=getCookie("AC-Signon-Cookie"),sessionCookie=getCookie("AC-Session-Cookie");
		if(signOnCookie&&sessionCookie){
			var signOnCookieValue=signOnCookie.split('^'),sessionCookieValue=sessionCookie.split('^');
			dpg.USERID.value=signOnCookieValue[0];
			dpg.TITLE.value=signOnCookieValue[1];
			dpg.LNAME.value=signOnCookieValue[4];
			dpg.MNAME.value=signOnCookieValue[3];
			dpg.FNAME.value=signOnCookieValue[2];
			dpg.FFMILES.value=signOnCookieValue[5];
			country=signOnCookieValue[6];
			dpg.EXTERNAL_ID.value=sessionCookieValue[0];
		}else{
			dpg.USERID.value="GUEST";
			dpg.EXTERNAL_ID.value="GUEST";
			if(e("ResidenceBar").style.display!='none') {
country=fl.countryOfResidence.options[fl.countryOfResidence.selectedIndex].value;
		}
		}
	}else {country=dpg.AGENCY_ADDRESS_COUNTRY.value;
}

			if(typeof(fl.tripType.value)!="string"){
				if(fl.tripType[0].checked) dpg.TRIP_TYPE.value=fl.tripType[0].value;
				else if(fl.tripType[1].checked)	dpg.TRIP_TYPE.value=fl.tripType[1].value;
			}else{
				if(fl.tripType.value=="R") dpg.TRIP_TYPE.value=fl.tripType[0].value;
				else if(fl.tripType.value=="O")	dpg.TRIP_TYPE.value=fl.tripType[1].value;
			}

	dpg.B_LOCATION_1.value=fl.origin1.value;
	dpg.E_LOCATION_1.value=fl.destination1.value;
	if(aBookingFlowVal=="DOMTRANSB"||aBookingFlowVal=="AGENT_DOMTRANSB"||aBookingFlowVal.indexOf("INTERNATIONAL")!=-1){

			if(typeof(fl.tripType.value)!="string"){
				if(fl.tripType[0].checked){
					dpg.B_LOCATION_2.value=dpg.E_LOCATION_1.value;
					dpg.E_LOCATION_2.value=dpg.B_LOCATION_1.value;
				}
			}else{
				if(fl.tripType.value=="R"){
					dpg.B_LOCATION_2.value=dpg.E_LOCATION_1.value;
					dpg.E_LOCATION_2.value=dpg.B_LOCATION_1.value;
				}
			}
	}
	var selectedTimeOption, submitfield;
	for(i=1;i<=MAX_DEPARTURES;i++){
		selectedTimeOption="0000"
		if(!dpg.PRIVATE_LABEL.value=="AGENT"){
			if(i==2&&fl.tripType[1]&&fl.tripType[1].checked){
				eval("document.flightsPlanitgo.B_DATE_"+i+".value = getDateNumber(1)+document.flights.departTime1.options[document.flights.departTime1.selectedIndex].value;");
				selectedTimeOption=eval("document.flights.departTime1.options[document.flights.departTime1.selectedIndex].value");
			}else{
				eval("document.flightsPlanitgo.B_DATE_"+i+".value = getDateNumber("+i+")+document.flights.departTime"+i+".options[document.flights.departTime"+i+".selectedIndex].value;");
				selectedTimeOption=eval("document.flights.departTime"+i+".options[document.flights.departTime"+i+".selectedIndex].value");
			}
		}else{
			if(i==2&&fl.tripType[1]&&fl.tripType[1].checked){
				eval("document.flightsPlanitgo.B_DATE_"+i+".value = getDateNumber(1)+selectedTimeOption;");
				selectedTimeOption="0000";
			}else{
				eval("document.flightsPlanitgo.B_DATE_"+i+".value = getDateNumber("+i+")+selectedTimeOption;");
				selectedTimeOption="0000";
			}
		}
		(selectedTimeOption=="0000")?eval("document.flightsPlanitgo.B_ANY_TIME_"+i+".value = \"TRUE\";"):eval("document.flightsPlanitgo.B_ANY_TIME_"+i+".value = \"FALSE\";");
	}
	totadults=Number(fl.numberOfAdults.options[fl.numberOfAdults.selectedIndex].value);
	totyouths=Number(fl.numberOfYouth.options[fl.numberOfYouth.selectedIndex].value);
	totpassengers=Number(fl.numberOfAdults.options[fl.numberOfAdults.selectedIndex].value)+Number(fl.numberOfYouth.options[fl.numberOfYouth.selectedIndex].value)+Number(fl.numberOfChildren.options[fl.numberOfChildren.selectedIndex].value);
	adult="ADT";
	child="CHD";
	for(i=1;i<=totadults+totyouths;i++) eval('document.flightsPlanitgo.TRAVELLER_TYPE_'+i+'.value = adult;');
	for(j=i;j<=totpassengers;j++) eval('document.flightsPlanitgo.TRAVELLER_TYPE_'+j+'.value = child;');
	for(k=j;k<=9;k++) eval('document.flightsPlanitgo.TRAVELLER_TYPE_'+k+'.value = "";');
	if(e("Infant").style.display!='none'){
		totinfants=Number(fl.numberOfInfants.options[fl.numberOfInfants.selectedIndex].value);
		for(i=1; i<=totinfants; i++) eval('document.flightsPlanitgo.HAS_INFANT_'+i+'.value = "TRUE";');
		for(j=i; j<=totpassengers; j++) eval('document.flightsPlanitgo.HAS_INFANT_'+j+'.value = "FALSE";');
	}else{
		for(i=1; i<=9; i++) eval('document.flightsPlanitgo.HAS_INFANT_'+i+'.value = "";');
	}

	//added for youth
	for(i=1;i<=totadults;i++) eval('document.flightsPlanitgo.IS_YOUTH_'+i+'.value = "FALSE";');
	for(j=i;j<=totadults+totyouths;j++) eval('document.flightsPlanitgo.IS_YOUTH_'+j+'.value = "TRUE";');
	for(k=j;k<=totpassengers;k++) eval('document.flightsPlanitgo.IS_YOUTH_'+k+'.value = "FALSE";');
	for(l=k;l<=9;l++) eval('document.flightsPlanitgo.IS_YOUTH_'+l+'.value = "";');

	var soSiteVal="", soTicketVal="";

	// SR97502801--------------------------------------
	var soCORVal=country;
	dpg.SO_SITE_COUNTRY_OF_RESIDENCE.value = soCORVal;
	if(country==CanadianCOR.toString().match(country)){
		soSiteVal="YOW";
		soTicketVal="YOW";
	}
	//-------------------------------------------------

	if((origAirport.country=="US"||destAirport.country=="US")&&(origAirport.country=="CU"||destAirport.country=="CU")){
		if(country=="CA"||country=="US") soSiteVal="YWG";
	}
	else {
	        if (country == "CA"){soSiteVal = "YOW";}
	        else if (country == "US") { soSiteVal = "WAS";}
        }
	if(country==COUNTRY_POS.toString().match(country)){
		for(i=0;i<COUNTRY_POS.length;i++){
			if(country==COUNTRY_POS[i]){
				soSiteVal=ETVparameters[i][2]
				soTicketVal=ETVparameters[i][3]
			}
		}
//	}else if(IsCaribbean(country)){
	}else if(IsCaribbean(country) || country==IntlCaribbeanCOR.toString().match(country)){
		if(country != "MX" && country != "CR"){
			soSiteVal="TPA";
			soTicketVal=(country=="BB")?"BGI":"NAS";
		}
	}
	if(soTicketVal=="") soTicketVal=soSiteVal;
	if(dpg.action.indexOf("jsessionid")!=-1&&soSiteVal==dpg.SO_SITE_POINT_OF_SALE.value){
		var controllerIndex=dpg.action.lastIndexOf("OverrideServlet");
		dpg.action=dpg.action.substr(0,controllerIndex)+checkEmbeddedTransaction(aBookingFlowVal)+dpg.action.substr(controllerIndex+15);
		dpg.SO_SITE_POINT_OF_SALE.value="";
		dpg.SO_SITE_POINT_OF_TICKETING.value="";
	}else{
		dpg.EMBEDDED_TRANSACTION.value=checkEmbeddedTransaction(aBookingFlowVal);
		dpg.SO_SITE_POINT_OF_SALE.value=soSiteVal;
		dpg.SO_SITE_POINT_OF_TICKETING.value=soTicketVal;
	}
	if(!(dpg.PRIVATE_LABEL.value=="AGENT")&&typeof(dpg.SO_SITE_EDITION)!='undefined'){
		var ACsignOnCookie=getCookie("AC-Signon-Cookie");
		if(ACsignOnCookie){
			var ACsignOnCookieValue=ACsignOnCookie.split('^');
			dpg.SO_SITE_EDITION.value=(ACsignOnCookieValue[6]=='CA'||ACsignOnCookieValue[6]=='US')?ACsignOnCookieValue[6]:"";
		}else{
			dpg.SO_SITE_EDITION.value=(getCookie('country_pref')=="CA")?"CA":(getCookie('country_pref')=="US")?"US":"";
		}
	}
	else if (typeof(dpg.SO_SITE_EDITION) != 'undefined'){
		if (dpg.AGENCY_ADDRESS_COUNTRY.value == "CA" || dpg.AGENCY_ADDRESS_COUNTRY.value == "US")dpg.SO_SITE_EDITION.value = dpg.AGENCY_ADDRESS_COUNTRY.value;
		else dpg.SO_SITE_EDITION.value = "";
	}
	// Changed for SR 2438
	dpg.DIRECT_NON_STOP.value="FALSE";

	if(e("Flexible").style.display!='none')
		dpg.SEVEN_DAY_SEARCH.value=(fl.Flexible.checked==true)?"TRUE":"FALSE";
	else dpg.SEVEN_DAY_SEARCH.value="";
	if(aBookingFlowVal.indexOf("INTERNATIONAL")==-1){
		if(fl.classType.selectedIndex==0) dpg.CABIN.value="R";
		else if(fl.classType.selectedIndex==1) dpg.CABIN.value="E";
		else if(fl.classType.selectedIndex==2) dpg.CABIN.value="N";
		else if(fl.classType.selectedIndex==3) dpg.CABIN.value="B";
	}
	if(Language=="french") dpg.LANGUAGE.value="FR";
	else if(Language=="de") dpg.LANGUAGE.value="DE";
	else if(Language=="it") dpg.LANGUAGE.value="IT";
	else dpg.LANGUAGE.value="US";
	temp_cor="";
	if(e("ResidenceBar").style.display!='none')
		temp_cor=fl.countryOfResidence.options[fl.countryOfResidence.selectedIndex].value;
	thisCountry=getCookie("country_pref");
	if(temp_cor!=""&&temp_cor!="O"){
		if(temp_cor==thisCountry){
		}else if((temp_cor=="CA"||temp_cor=="US")&&(thisCountry=="CA"||thisCountry=="US")){
		}else if(IsCaribbean(temp_cor)){
		}
		else{
			//Modified  for TR95008893 
			//if(temp_cor=="CA"||thisCountry==COUNTRY_POS.toString().match(thisCountry)) writeCookie('new_lang_pref','english');
			if(temp_cor=="CA") writeCookie('new_lang_pref','english');
			//end
			else if(temp_cor=="US") writeCookie('new_lang_pref','us');
			else{
				if(!(checkLangCookie("new_lang_pref")=="english" || checkLangCookie("new_lang_pref")=="en" || checkLangCookie("new_lang_pref")=="us" ))
				{
				lang="";
				for(i=0;i<countryCookieArray.length;i++){
					if(temp_cor==countryCookieArray[i][0]){
						lang=countryCookieArray[i][1];
						break;
						}
					}
					//Removed for TR95008893 
					//(lang==""||lang=="en")?writeCookie('new_lang_pref','english'):writeCookie('new_lang_pref',lang);
					//end
				}
			}
			writeCookie('country_pref',temp_cor);
			//Modified for TR95008893 
			//if(!(temp_cor=="FR"||temp_cor=="CA"||temp_cor=="US")) dpg.LANGUAGE.value="US";
			if(checkLangCookie("new_lang_pref")=="english"||checkLangCookie("new_lang_pref")=="us") dpg.LANGUAGE.value="US";
			//end
			if(!(temp_cor=="FR"||temp_cor=="CA"||temp_cor=="US"||temp_cor==CanadianCOR.toString().match(temp_cor))) dpg.LANGUAGE.value="US";
			setCountry_path();
		}
	}
	if(country==COUNTRY_POS.toString().match(country)){
		for(i=0;i<COUNTRY_POS.length;i++){
			if(country==COUNTRY_POS[i]||(country=="O"&&POS==COUNTRY_POS[i])) dpg.MARKET.value=ETVparameters[i][1];
		}
	}else if(IsCaribbean(country)||(country=="O"&&IsCaribbean(POS))) dpg.MARKET.value="SUN";
	else{
		countryVal=getCookie("country_pref");
		dpg.MARKET.value=(countryVal=="US"||checkLangCookie('new_lang_pref')=="us")?"US":"CA";
		for(i=0;i<COUNTRY_POS.length;i++) if(countryVal==COUNTRY_POS[i]) dpg.MARKET.value=ETVparameters[i][1];
	}
	countryVal=getCookie("country_pref");
	dpg.COUNTRY.value=(countryVal=="US"||checkLangCookie('new_lang_pref')=="us")?"US":"CA";
	for(i=0;i<COUNTRY_POS.length;i++){
		if(countryVal==COUNTRY_POS[i]){
			dpg.COUNTRY.value=ETVparameters[i][0];
			if(!(countryVal=="FR"||countryVal=="US"||countryVal=="CA"||countryVal=="DE"||countryVal=="IT"|| countryVal == "CH"))	dpg.LANGUAGE.value="US";
		}
	}

	//####################  SO_SITE_FP_WITHHOLD_SURCHARG  #####################
	/**------------------------------------------------------------------------
	NEW RULE:
	=========
		SO_SITE_FP_WITHHOLD_SURCHARG is to be set according to the following rule:
		'NO'
		If: a) MARKET=US and
		    b) SO_SITE_POINT_OF_SALE=WAS (i.e. COR is US) and
		    c) Itinerary is D.O.T		
		'FALSE' if COR = United Kingdom, Ireland, France, Switzerland, Germany,
		                 Italy, Denmark, Norway, Sweden, Israel, Netherlands		
		'TRUE' for all other cases		
	
	Definition of D.O.T Itinerary:
	==============================
		. Originating in US to CA
		. Originating in CA to US
		. Originating in US to an international destination
		. Originating from an international origin to US
		
	--------------------------------------------------------------------------*/
	
	if(document.flightsPlanitgo.USERID.value == "GUEST")
		COREdition = document.flights.countryOfResidence.value;
	else
		COREdition = document.flightsPlanitgo.SO_SITE_COUNTRY_OF_RESIDENCE.value;

	if(COREdition == NoneSurchargedCountries.toString().match(COREdition))
		dpg.SO_SITE_FP_WITHHOLD_SURCHARG.value="FALSE";
	else if(dpg.MARKET.value=="US"&&COREdition=="US"&&isDOT()==true)
		dpg.SO_SITE_FP_WITHHOLD_SURCHARG.value="NO";
	else
		dpg.SO_SITE_FP_WITHHOLD_SURCHARG.value="TRUE";
	//###########################################################################################

	if(CARIBBEAN_FLAG) dpg.BOOKING_FLOW.value=(dpg.PRIVATE_LABEL.value=="AGENT")?"AGENT_INTERNATIONAL":"INTERNATIONAL";

	if (e('Promotion Code')!= null){
		if (fl.promotionCode.value!= null && fl.promotionCode.value!=""){
			dpg.AUTHORIZATION_ID.value = fl.promotionCode.value;
			if (fl.IATA_AGENCY_PNR.value!= null && fl.IATA_AGENCY_PNR.value!="")dpg.TRAVEL_AGENT_PNR.value = fl.IATA_AGENCY_PNR.value;
			if (fl.AGENCY_ID.value!= null && fl.AGENCY_ID.value!="")dpg.IATA_AGENT_ID_NUMBER.value = fl.AGENCY_ID.value;
			if (fl.AGENT_LASTNAME.value!= null && fl.AGENT_LASTNAME.value!="")dpg.IATA_AGENT_LAST_NAME.value = fl.AGENT_LASTNAME.value;
			if (fl.AGENT_FIRSTNAME.value!= null && fl.AGENT_FIRSTNAME.value!="")dpg.IATA_AGENT_FIRST_NAME.value = fl.AGENT_FIRSTNAME.value;
			}
	}

	//SR97502207
	var listOAL = isOAL(depCity,arrCity);
	if( listOAL!= ""){
		document.flightsPlanitgo.SO_SITE_REST_AIRLINES_LST.value = listOAL;
	}

	if(e("CheckUpgrade").checked){
		if (document.flights.certificateField.value != "") {
			var certNbr = document.flights.certNbrPrefix.value + document.flights.certificateField.value;
			while(certNbr.search(" ")!=-1) {
				certNbr = certNbr.replace(" ","");
			}
			document.flightsPlanitgo.CERTIFICATE_NUMBER.value = certNbr;
		}
	}

}
function init(){
	logDebug("citysearch.js init start ");
  try {
	loaded=true;
	if(typeof(fl.tripType.value)!="string"){
		fl.tripType[0].checked=true;
	}else{
		fl.tripType.selectedIndex=0;
	}

	fl.org1.value="";
	fl.dest1.value="";
	fl.origin1.value="";
	fl.destination1.value="";
	fl.departTime1.selectedIndex=0;
	fl.departTime2.selectedIndex=0;
	fl.numberOfAdults.selectedIndex=1;
	fl.numberOfYouth.selectedIndex=0;
	fl.numberOfChildren.selectedIndex=0;
	fl.numberOfInfants.selectedIndex=0;
	countryVal=getCookie('country_pref');
	(countryVal=="CA"||countryVal=="US"||countryVal==COUNTRY_POS.toString().match(countryVal))?popSelectionData(fl.countryOfResidence,countryVal):popSelectionData(fl.countryOfResidence,"CA");
	hide('Class');
	if(fl.searchType[0]) fl.searchType[0].checked=true;
	if(countryCookieValue == "IL")document.flights.Flexible.checked = true;
  } catch (err) {
    logError(err, "init @1640");
  }
	logDebug("citysearch.js init end ");
}

function initFlightSearch(processFacade){
	logDebug("citysearch.js initFlightSearch start ");
	// Initialize global variables used elsewhere in this file.
	fl = document.flights;
	dpg = document.flightsPlanitgo;

  var objErr4;
  try
  {
	//initNewCalendar();
	init();
    var countrycookie=getCookie("country_pref");
	if(countrycookie==COUNTRY_POS.toString().match(countrycookie)){
		checkFlightType(false,false,true,true);
	}else{
		checkFlightType(false,false,false,true);
	}
  }
  catch(objErr4)
  {
  	logError(objErr4, "initFlightSearch  @1661: error in 4");
  }

  try {
	var cityCookie=getCookie("cityCookie"), displayedCity="",populateFlag=false,isReqFromOffers=false;
	if(location.pathname.indexOf("offers")>-1) isReqFromOffers=true;
	if((!isReqFromOffers)&&(processFacade!="block"))
	(dpg.PRIVATE_LABEL.value=="AGENT")?populateFlag=getFlightSearchCookie("ADO"):populateFlag=getFlightSearchCookie("ACO");
	if(populateFlag==false&&cityCookie!==null){
		if(!(dpg.PRIVATE_LABEL.value=="AGENT")) {
		if(cityCookie.length==3){
				displayedCity=getCityName(cityCookie);
				fl.origin1.value=cityCookie;
			}
			fl.org1.value=(displayedCity!="")?displayedCity:cityCookie;
		}
	}

	var parameters= new Array();
	var auxParametersList =(document.location.search.split("?"));
	if (auxParametersList[1] != null){
		var attributes= auxParametersList[1].split("&")
		for (var i=0; i< attributes.length; i++){
			var text=attributes[i].split("=");
			parameters[text[0]]=text[1];
		}
	}

	wstriptype = parameters['triptype'];
	wsfrom = parameters['from'];
	wsorign = parameters['dept'];
	wsorign1 = parameters['origin'];

	wsdest = parameters['arrive'];
	wsdest1 = parameters['dest'];

	wsdepday = parameters['deptdateday'];
	wsdepmonth = parameters['deptdatemonth'];
	wsdepyear = parameters['deptdateyear'];
	wsarrday = parameters['arrivedateday'];
	wsarrmonth = parameters['arrivedatemonth'];
	wsarryear = parameters['arrivedateyear'];
	wsnbadult = eval(parameters['adult']);
	wsnbchild = eval(parameters['child']);

    if(typeof(wsorign)!="undefined") e("org1").value = wsorign
    if(typeof(wsdest)!="undefined")  e("dest1").value = wsdest

    if(typeof(wsfrom)!="undefined") e("org1").value = getCityName(wsfrom);
    if(typeof(wsdest1)!="undefined")  e("dest1").value = getCityName(wsdest1);

    if(typeof(wsorign1)!="undefined") e("org1").value = getCityName(wsorign1);

    if(typeof(wsdepday)!="undefined") e("departure1").value = wsdepday + "/" + wsdepmonth + "/20" + wsdepyear;
    if(typeof(wsarrday)!="undefined") e("departure2").value = wsarrday + "/" + wsarrmonth + "/20" + wsarryear;

    if(typeof(wsnbadult)!="undefined"){wsnbadult = wsnbadult-1; e("numberOfAdults").options[wsnbadult].selected = true;}
    if(typeof(wsnbchild)!="undefined") e("numberOfChildren").options[wsnbchild].selected = true;

    if(typeof(wstriptype)!="undefined") wstriptype=="round"? document.flights.tripType[0].checked = true:document.flights.tripType[1].checked = true;
// 2799
//	if(e('moreOptionsTextNA')!=null){
//		if(countryCookie=="CA" || countryCookie=="US"){
//			e('moreOptionsTextNA').style.display='';
//			hide('moreOptionsTextIntl');
//		}else{
//			hide('moreOptionsTextNA');
//			e('moreOptionsTextIntl').style.display='';
//		}
//	}
  } catch(err) {
    logError(err, "initFlightSearch @1730");
  }
	logDebug("citysearch.js initFlightSearch end ");
}
matchAmbiArray=false;
function getDateNumber(index){
	if(index=="Dep") index=1;
	else if(index=="Ret") index=2;
	var datefield=eval("document.flights.departure"+index),dv=datefield.value;
	return dv.substring(6,10)+dv.substring(3,5)+dv.substring(0,2);
}
function getZeroPadded(input,len){
	retString=new String(input);
	while(retString.length<len) retString="0"+retString;
	return retString;
}
function setCookie(cookie_name,cookie_value,cookie_life,cookie_path){
	var today=getGMTServerDate(),expiry=new Date(today.getTime()+cookie_life*24*60*60*1000);
	if(cookie_value!=null&&cookie_value!=""){
		var cookie_string=cookie_name+"="+escape(cookie_value);
		if(cookie_life) cookie_string+="; expires="+expiry.toGMTString();
		if (!cookie_path) cookie_path = "/";
		cookie_string+="; path="+cookie_path;
		document.cookie=cookie_string;
	}
}
function getCookie(name){
	var index=document.cookie.indexOf(name+"=")
	if(index==-1) return null;
	index=document.cookie.indexOf("=",index)+1;
	var end_string=document.cookie.indexOf(";",index);
	if(end_string==-1) end_string=document.cookie.length;
	return unescape(document.cookie.substring(index,end_string));
}
function cookieEnable(){
	var testout="",cookie_enable=false;
	setCookie('cookietest','yes','1','/');
	testout=getCookie('cookietest');
	if(testout!=null) cookie_enable=true;
	return cookie_enable;
}
function classType_onChange(){
	if(fl.searchType&&e('Shop').style.display!='none') searchType_onChange();
}
function searchType_onChange(){
	var searchTyp=fl.searchType[0].value;
	if(fl.searchType[1].checked) searchTyp=fl.searchType[1].value;
  var origApCode=e('origin1').value, destApCode=e('destination1').value;
	var aFlightSegmentType = checkFlightSegmentType(origApCode, destApCode), fareDriven=checkforFareDriven(origApCode, destApCode);
	if(searchTyp=="F"){
		fl.searchType[0].checked=true;
		show('Flexible');
		if(aFlightSegmentType=="International"||!fareDriven){
			hide('Class');
			hide('ClassText');
		}else{
			show('Class');
			show('ClassText');
		}
		if(e('Direct')) hide('Direct');
	}else if(searchTyp=="S"){
		fl.searchType[1].checked=true;
		hide('Flexible');

		show('Class');
		show('ClassText');
		if(e('Direct')) show('Direct');
	}else fl.tripType[0].checked=true;
}
function checkforTyrolean(orgCode,destCode){
	var tyroleanFlightSegment=false;
	if(orgCode=="GRZ"||orgCode=="INN"||orgCode=="KLU"||orgCode=="LNZ"||orgCode=="SZG"||destCode=="GRZ"||destCode=="INN"||destCode=="KLU"||destCode=="LNZ"||destCode=="SZG") tyroleanFlightSegment=true;
	if(tyroleanFlightSegment) displayTyroleanPopup();
}
var tyrolean_window=null;
function displayTyroleanPopup(){
	if(tyrolean_window==null){
		if(Language=="french") tyrolean_window=window.open('/shared/includes/fr/common/city/pop_tyrolean.html','Error','scrollbars=yes,width=300,height=200,resizeable=yes');
		else tyrolean_window=window.open('/shared/includes/en/common/city/pop_tyrolean.html','Error','scrollbars=yes,width=300,height=200,resizeable=yes');
	}
}
function doNothing(){}
function _openWindow(dependant,FileName,windowName,width,height){
	wh=window.open(FileName,windowName,'dependant='+(dependant ? 'yes' : 'no')+',resizable=yes'+',width='+width+',height='+height);
	wh.topwin=self;
	wh.focus();
}
mouseDown=new Array();
function setMouseDown(e,target){mouseDown[target.name]=true;}
function clearMouseDown(e,target){mouseDown[target.name]=false;}
function checkMouseDown(e,target){
	if(mouseDown[target.name]){
		mouseDown[target.name]=false;
		return true;
	}else return false;
}
function openWindow(event,target,FileName,windowName,width,height){
	if(!(width&&height)){
		width=800;
		height=600;
	}
	if(checkMouseDown(event,target)) _openWindow(false,FileName,windowName,width,height);
}
function checkTripType(RoundTrip){e('ReturnTextbar').style.display=(RoundTrip=="O")?"none":"block";}
function setFlightSearchCookie(site){
	logDebug("setFlightSearchCookie start " + site);
	cookieName=(site=="ADO")?"AC-AgentFlightSearch-Cookie":"AC-ConsFlightSearch-Cookie";
	var domain=".aircanada.com",cookiePath="/",TripType="NULL",SearchOptions="NULL",FlightSegment1="NULL",FlightSegment2="NULL";
	var FlightSegment3="NULL",FlightSegment4="NULL",FlightSegment5="NULL",FlightSegment6="NULL",noInfants=0,i=1;

	if(typeof(fl.tripType.value)!="string"){
		TripType=(fl.tripType[0].checked)?TripType="R":TripType="O";
	}else{
		TripType=fl.tripType.value;
	}
if (site == "ADO" || TripType != "M") {
	for(i=1;i<=9;i++){
		eval("hasInfant=document.flightsPlanitgo.HAS_INFANT_"+i+".value;");
		if(hasInfant=="TRUE") noInfants=noInfants+1;
	}
	SearchOptions=fl.numberOfAdults.options[fl.numberOfAdults.selectedIndex].value+"|"+fl.numberOfYouth.options[fl.numberOfYouth.selectedIndex].value+"|"+fl.numberOfChildren.options[fl.numberOfChildren.selectedIndex].value+"|"+noInfants;
	SearchOptions=(fl.countryOfResidence)?SearchOptions+"|"+fl.countryOfResidence.options[fl.countryOfResidence.selectedIndex].value:SearchOptions+"|"+"NULL";
	SearchOptions=SearchOptions+"|"+fl.classType.options[fl.classType.selectedIndex].value;
	SearchOptions=(dpg.SEVEN_DAY_SEARCH.value=="TRUE")?SearchOptions+"|"+"true":SearchOptions=SearchOptions+"|"+"false";
	SearchOptions=(fl.searchType&&fl.searchType[1].checked)?SearchOptions+"|"+"S":SearchOptions+"|"+"F";
	SearchOptions=(dpg.DIRECT_NON_STOP.value=="TRUE")?SearchOptions+"|"+"true":SearchOptions+"|"+"false";
	if(TripType=="O") FlightSegment1=fl.origin1.value+"|"+fl.destination1.value+"|"+dpg.B_DATE_1.value+"|"+"NULL";
	else FlightSegment1=fl.origin1.value+"|"+fl.destination1.value+"|"+dpg.B_DATE_1.value+"|"+dpg.B_DATE_2.value;
	var cookieValue=TripType+"^"+SearchOptions+"^"+FlightSegment1+"^"+FlightSegment2+"^"+FlightSegment3+"^"+FlightSegment4+"^"+FlightSegment5+"^"+FlightSegment6;
	document.cookie=cookieName+"="+cookieValue+"; path="+cookiePath+"; domain="+domain;
}
	logDebug("setFlightSearchCookie end " + site);
}

function getFlightSearchCookie(site){
logDebug("getFlightSearchCookie start " + site);
	cookieName=(site=="ADO")?"AC-AgentFlightSearch-Cookie":"AC-ConsFlightSearch-Cookie";
	populateCookie=getCookie(cookieName);
	var TripType="",SearchOptions="",FlightSegment1="",FlightSegment2="",FlightSegment3="",FlightSegment4="",FlightSegment5="",FlightSegment6="";
	if(populateCookie){
		cookieValue=populateCookie.split('^');
		TripType=cookieValue[0];
if (site == "ADO" || TripType != "M") {
		SearchOptions=cookieValue[1];
		FlightSegment1==cookieValue[2];
		FlightSegment2==cookieValue[3];
		FlightSegment3==cookieValue[4];
		FlightSegment4==cookieValue[5];
		FlightSegment5==cookieValue[6];
		FlightSegment6==cookieValue[7];
		if(TripType=="O"){
			if(typeof(fl.tripType.value)!="string"){
				fl.tripType[1].checked=true;
			}else{
				fl.tripType[1].selected=true;
			}
			checkTripType("O");
		}
		searchValues=cookieValue[1].split('|');
		fl.numberOfAdults.selectedIndex=Number(searchValues[0]);
		fl.numberOfYouth.selectedIndex=searchValues[1];
		fl.numberOfChildren.selectedIndex=searchValues[2];
		fl.numberOfInfants.selectedIndex=searchValues[3];
		flightSegment1Value=cookieValue[2].split('|');
		var OneWayTrip=((fl.tripType[1]&&fl.tripType[1].checked)||(location.href.indexOf("oneway=YES")>-1))?true:false;
		if(OneWayTrip){
			if(flightSegment1Value[0]!=null&&flightSegment1Value[0]!="NULL"){
				if(flightSegment1Value[0].length==3){
					origCity=getCityName(flightSegment1Value[0]);
					if(origCity!=null||origCity!=""){
						origAirport=getAirportFromCode(flightSegment1Value[0]);
						fl.origin1.value=origAirport.code;
					}
				}
				fl.org1.value=(origCity!="")?origCity:flightSegment1Value[0];
			}
			if(flightSegment1Value[1]!=null&&flightSegment1Value[1]!="NULL"){
				if(flightSegment1Value[1].length==3){
					destCity=getCityName(flightSegment1Value[1]);
					if(destCity!=null||destCity!="") {
						destAirport=getAirportFromCode(flightSegment1Value[1]);
						fl.destination1.value=destAirport.code;
					}
				}
				fl.dest1.value=(destCity!="")?destCity:flightSegment1Value[1];
			}
			if(flightSegment1Value[2]!=null&&flightSegment1Value[2]!="NULL"){
				month=flightSegment1Value[2].substring(4,6);
				day=flightSegment1Value[2].substring(6,8);
				val=months[Number(month-1)][1]+flightSegment1Value[2].substring(0,4);
				timeval=flightSegment1Value[2].substring(8,12);
				popSelectionData(fl.departTime1,timeval);
				if(OneWayTrip) popSelectionData(fl.departTime2,timeval);
			}
		}else{
			if(flightSegment1Value[0]!=null&&flightSegment1Value[0]!="NULL"){
				if(flightSegment1Value[0].length==3){
					origCity=getCityName(flightSegment1Value[0]);
					if(origCity!=null||origCity!=""){
						origAirport=getAirportFromCode(flightSegment1Value[0]);
						fl.origin1.value=origAirport.code;
					}
				}
				fl.org1.value=(origCity!="")?origCity:flightSegment1Value[0];
			}
			if(flightSegment1Value[1]!=null&&flightSegment1Value[1]!="NULL"){
				if(flightSegment1Value[1].length==3){
					destCity=getCityName(flightSegment1Value[1]);
					if(destCity!=null||destCity!=""){
						destAirport=getAirportFromCode(flightSegment1Value[1]);
						fl.destination1.value=destAirport.code;
					}
				}
				fl.dest1.value=(destCity!="")?destCity:flightSegment1Value[1];
			}
			if (flightSegment1Value[2] != null && flightSegment1Value[2].length >= 12){
				month=flightSegment1Value[2].substring(4,6);
				day=flightSegment1Value[2].substring(6,8);
				val=months[Number(month-1)][1]+flightSegment1Value[2].substring(0,4);
				setDateField(flightSegment1Value[2],fl.departure1);
				timeval=flightSegment1Value[2].substring(8,12);
				popSelectionData(fl.departTime1,timeval);
			}
			if (flightSegment1Value[3] != null && flightSegment1Value[3].length >= 12) {
				month=flightSegment1Value[3].substring(4,6);
				day=flightSegment1Value[3].substring(6,8);
				val=months[Number(month-1)][1]+flightSegment1Value[3].substring(0,4);
				setDateField(flightSegment1Value[3],fl.departure2);
				timeval=flightSegment1Value[3].substring(8,12);
				popSelectionData(fl.departTime2,timeval);
			}else popSelectionData(fl.departTime2,timeval);
		}
		var i=2,lastSegment=1;
		i=lastSegment+1;
		for(i=lastSegment+1; i<=MAX_CITY_PAIRS; i++) eval("popSelectionData(document.flights.departTime"+i+",timeval);");
		popSelectionData(fl.countryOfResidence,searchValues[4]);
		popSelectionData(fl.classType,searchValues[5]);
		if(searchValues[6]=="true")	fl.Flexible.checked=true;
		(searchValues[7]=="S")?fl.searchType[1].checked=true:fl.searchType[0].checked=true;
		showAndHide();
}
		logDebug("getFlightSearchCookie end (true) " + site);
		return true;
	} else {
		logDebug("getFlightSearchCookie end (false) " + site);
		return false;
	}
}
function IsCaribbean(checkCountry,checkCity){
	for(var i=0;i<CARIBBEAN.length;i++){
		if(checkCountry==CARIBBEAN[i] || IsCaribbeanCity(checkCity)){
			return true;
			break;
		}
	}
	return false;
}

function IsCaribbeanCity(checkCity){
	for(var i=0;i<CARIBBEAN_CITY.length;i++){
		if(checkCity==CARIBBEAN_CITY[i]){
			return true;
			break;
		}
	}
	return false;
}
function setDateField(v,f){f.value=v.substring(6,8)+'/'+v.substring(4,6)+'/'+v.substring(0,4);}

//PKorth from here
function setFareFamily() {
	if (isNBM() == true) {
		doNBM();
	}
}

function isNBM() {
	var depCity = fl.origin1.value;
	var arrCity = fl.destination1.value;
	for (var i = 0; i < FAREFAMILY_NBM.length; i++) {
		for (var j = 1; j < FAREFAMILY_NBM[i].length; j++) {
			var city = FAREFAMILY_NBM[i][j];
			if (depCity == city || arrCity == city) {
				return true;
			}
		}
	}
	return false;
}

function doNBM() {
	var aBookingFlowVal = checkBookingFlow();
	if (typeof(fl.tripType.value) != "string") {
		if (fl.tripType[1].checked) {
			if (aBookingFlowVal != "SCHEDULE")
				dpg.COMMERCIAL_FARE_FAMILY_1.value = "NBMOW";
			dpg.DISPLAY_TYPE.value = "2";
		} else {
			dpg.COMMERCIAL_FARE_FAMILY_1.value = "FLEXIWDREV";
			dpg.DISPLAY_TYPE.value = "3";
		}
	} else {
		if (fl.tripType.value == "O") {
			if (aBookingFlowVal != "SCHEDULE")
				dpg.COMMERCIAL_FARE_FAMILY_1.value = "NBMOW";
			dpg.DISPLAY_TYPE.value = "2";
		} else {
			dpg.COMMERCIAL_FARE_FAMILY_1.value = "FLEXIWDREV";
			dpg.DISPLAY_TYPE.value = "3";
		}
	}
	dpg.COMMERCIAL_FARE_FAMILY_2.value="";
	dpg.CORPORATE_NUMBER_1.value="";
	dpg.CORPORATE_NUMBER_2.value="";
	dpg.TYPE_OF_CORPORATE_FARE.value="";
}
//PKorth to here

function isInvalidCityPair(orig,dest){
	if((orig.length!=3)||(dest.length!=3)) return false;
	var invalidCityArray=new Array("LAXAKL","AKLLAX");
	for(c=0;c<invalidCityArray.length;c++){
		if((orig==invalidCityArray[c].substring(0,3))&&( dest==invalidCityArray[c].substring(3,6))) return true;
	}
	return false;
}

function displayFacadeError(facadeParam) {}

function getAirportCode(countryCityName){
	var acode="";
	var iLen = String(countryCityName).length;
	if(iLen == 3)
		acode=countryCityName;
	else if(iLen > 4){
		subcode = String(countryCityName).substring(iLen,iLen-5);
		if(subcode.substring(0,1) == "(" && subcode.substring(5,4) == ")")
			acode = subcode.substring(1,4);
		else if(countryCityName == fl.org1.value)
			acode = fl.origin1.value;
		else if(countryCityName == fl.dest1.value)
			acode	= fl.destination1.value;
	}
	return acode;
}


// This function will parse the complete country list and get the city codes for select cities
function filterCityList(Domestic, Transborder, Sun, International){
	// we can have combinations - so receiving parameters in order - value Y or N for each
	var CityList1 = "";
	var CityList2 = "";
	var CityList3 = "";
	var cityListA = "";

	if(Domestic == "Y" && Transborder == "N"){
		CityList1 = subCityList("D");
	}else if((Domestic == "Y" && Transborder == "Y") || (Domestic == "N" && Transborder == "Y")){
		CityList1 = subCityList("T");
	}
	if(Sun == "Y")
		CityList2 = subCityList("S");
	if(International == "Y")
		CityList3 = subCityList("I");
	cityListA = CityList1 + CityList2 + CityList3;

	iLen = cityListA.length;
	if(iLen != 0)
		if(cityListA.substring(iLen-1,iLen) == ",")
			cityListA = cityListA.substring(0,iLen-1);
	return cityListA;

}

function subCityList(listType){
	var ObjErr;
	try{
	var cityListA = "";
	var searchCountry = new Array();
	if (listType == "D"){
		searchCountry[0]= "CA";
	}else if(listType == "T"){
		searchCountry[1]= "CA";
		searchCountry[0]= "US";
	}else if(listType == "I"){
		searchCountry[0]= "CA";
		searchCountry[1]= "US";
		searchCountry[2] = "AG";
		searchCountry[3] = "BS";
		searchCountry[4] = "BM";
		searchCountry[5] = "LC";
		searchCountry[6] = "TT";
		searchCountry[7] = "BB";
	}else if(listType == "S"){
		searchCountry[0] = "AG";
		searchCountry[1] = "BS";
		searchCountry[2] = "BM";
		searchCountry[3] = "LC";
		searchCountry[4] = "TT";
		searchCountry[5] = "BB";
	}else
		searchCountry[0] = "";
	if(listType == "I"){
		for (i=0;i<cityList.cities.length;i++){
			foundflag = false;
			for(j=0;j<searchCountry.length;j++){
				if (cityList.cities[i].country ==  searchCountry[j])
					foundflag = true;
			}
			if (foundflag == false)
				cityListA = cityListA + cityList.cities[i].code+",";
		}
	}else{
		for (i=0;i<cityList.cities.length;i++){
			for(j=0;j<searchCountry.length;j++){
				if(cityList.cities[i].country ==  searchCountry[j]){
					cityListA= cityListA + cityList.cities[i].code+",";
				}
			}
		}
	}

	return(cityListA);
	}catch(ObjErr) {
      logError(ObjErr, "subCityList @2127");
    }
}


// new calendar functions

function initNewCalendar() {
	logDebug("initNewCalendar start");
  try {
	if(Language == "english")
		lang = "en";
	else if(Language == "french")
		lang= "fr";
	else if (Language =="de" || Language == "it")
		lang = Language;
	initCalendar("departure1", "departure2");

	registerSelect("departure1", "departTime2");
	registerSelect("departure1", "numberOfAdults");
	registerSelect("departure1", "numberOfYouth");
	registerSelect("departure1", "numberOfChildren");
	registerSelect("departure1", "numberOfInfants");
	registerSelect("departure1", "countryOfResidence");
	registerSelect("departure2", "numberOfAdults");
	registerSelect("departure2", "numberOfYouth");
	registerSelect("departure2", "numberOfChildren");
	registerSelect("departure2", "numberOfInfants");
	registerSelect("departure2", "countryOfResidence");

	setNextFocusField("departure1", "departure2");
	setNextFocusField("departure2", "numberOfAdults");

	initCalendarNtp();
  } catch (err) {
    logError(err, "initNewCalendar @2160");
  }
	logDebug("initNewCalendar end");
}

function initHomeCalendar(){
	logDebug("initHomeCalendar start ");
  try {
	if(Language == "english")
		lang = "en";
	else if(Language == "french")
		lang= "fr";
	else if (Language =="de" || Language == "it")
		lang = Language;
	initCalendar();
	setDisplayFields("departure1", "dl1");
	setDisplayFields("departure2", "dl2");
	setDateAdjustFields("departure1","departure2");

	registerSelect("departure1", "departTime2");
	registerSelect("departure1", "numberOfAdults");
	registerSelect("departure1", "numberOfYouth");
	registerSelect("departure1", "numberOfChildren");
	registerSelect("departure1", "numberOfInfants");
	registerSelect("departure1", "countryOfResidence");
	registerSelect("departure2", "numberOfAdults");
	registerSelect("departure2", "numberOfYouth");
	registerSelect("departure2", "numberOfChildren");
	registerSelect("departure2", "numberOfInfants");
	registerSelect("departure2", "countryOfResidence");
	setNextFocusField("departure1", "departure2");
	setNextFocusField("departure2", "numberOfAdults");
  } catch (err) {
    logError(err, "initHomeCalendar @2191");
  }
	logDebug("initHomeCalendar end ");
}

function initHomeCalendar12(){
	logDebug("initHomeCalendar start ");
  try {
	if(Language == "english")
		lang = "en";
	else if(Language == "french")
		lang= "fr";
	else if (Language =="de" || Language == "it")
		lang = Language;
	initCalendar();
	setDisplayFields("departure11", "dl11");
	setDisplayFields("departure22", "dl22");
	setDateAdjustFields("departure11","departure22");

	registerSelect("departure11", "departTime2");
	registerSelect("departure11", "numberOfAdults");
	registerSelect("departure11", "numberOfYouth");
	registerSelect("departure11", "numberOfChildren");
	registerSelect("departure11", "numberOfInfants");
	registerSelect("departure11", "countryOfResidence");
	registerSelect("departure22", "numberOfAdults");
	registerSelect("departure22", "numberOfYouth");
	registerSelect("departure22", "numberOfChildren");
	registerSelect("departure22", "numberOfInfants");
	registerSelect("departure22", "countryOfResidence");
	setNextFocusField("departure11", "departure22");
	setNextFocusField("departure22", "numberOfAdults");
  } catch (err) {
    logError(err, "initHomeCalendar @2191");
  }
	logDebug("initHomeCalendar end ");
}

// Added to support the valid Travel dates from NTP
function initCalendarNtp(){
	logDebug("initCalendarNtp start ");
  try {
	if(document.flights && document.flights.TravelStartDate && document.flights.TravelStartDate.value != ""){
		var newTSDate = parseDate(document.flights.TravelStartDate.value);
		if(! isDateBeforeToday(newTSDate))
			today = newTSDate;
	}

	if(document.flights && document.flights.TravelEndDate && document.flights.TravelEndDate.value != "" && document.flights.TravelStartDate.value != "")
		daysLimit = daysElapsed(parseDate(document.flights.TravelEndDate.value),today);
  } catch(err) {
        logError(err, "citylist@2236");
  }
	logDebug("initCalendarNtp end  ");
}

function y2k(number) { return (number < 1000) ? number + 1900 : number; }

function daysElapsed(date1,date2) {
    var difference =
        Date.UTC(y2k(date1.getYear()),date1.getMonth(),date1.getDate(),0,0,0)
      - Date.UTC(y2k(date2.getYear()),date2.getMonth(),date2.getDate(),0,0,0);
    return difference/1000/60/60/24;
}


function submitFlightSearch(){
	//var objErr;
	try{
		messagesList.errorMessages=new Array();
		var checkNeeded=fl.tripType[0].checked==true,inpageErrorFlag=false;
		origAirport=fetchAiport("org1","origin1");
		if(origAirport==null){
			processErrors();
			return false;
		}else{
			destAirport=fetchAiport("dest1","destination1");
			if(destAirport==null){
				processErrors();
				return false;
			}
		}
		if(origAirport.code==destAirport.code){
		  messagesList.addMessage("SAMEAIRPORTS",destAirport);
			processErrors();
			fl.dest1.focus();
			return false;
		}
		if(fl.tripType[0].checked==true){
			if(!isDateDefined(fl.departure1)){
				fl.departure1.focus();
				return false;
			}
			if(!isDateDefined(fl.departure2)){
				fl.departure2.focus();
				return false;
			}
		}else{
			if(!isDateDefined(fl.departure1)){
				fl.departure1.focus();
				return false;
			}
		}
		if(!isDatesValidForAirport(origAirport)) inpageErrorFlag=true;
		if(!isDatesValidForAirport(destAirport)) inpageErrorFlag=true;
		if(origAirport.errMsg!=null&&origAirport.errMsg!=""){
			messagesList.addMessage(origAirport.errMsg,origAirport);
			fl.org1.focus();
			inpageErrorFlag=true;
		}
		if(destAirport.errMsg!=null&&destAirport.errMsg!=""){
		  messagesList.addMessage(destAirport.errMsg,destAirport);
			fl.dest1.focus();
			inpageErrorFlag=true;
		}
		if((origAirport.country=="US"||destAirport.country=="US")&&(origAirport.country=="CU"||destAirport.country=="CU")){
			messagesList.addMessage("USACUBA");
			inpageErrorFlag=true;
		}
		if(origAirport.country=="US"&&destAirport.country=="US"){
			messagesList.addMessage("BOTHUSA");
			inpageErrorFlag=true;
		}
		//Added for 97502795
		var totalPassengers = Number(fl.numberOfAdults.options[fl.numberOfAdults.selectedIndex].value)
			+ Number(fl.numberOfYouth.options[fl.numberOfYouth.selectedIndex].value)
			+ Number(fl.numberOfChildren.options[fl.numberOfChildren.selectedIndex].value)
			+ Number(fl.numberOfInfants.options[fl.numberOfInfants.selectedIndex].value);

		if(totalPassengers == 0 || totalPassengers > 9){
			messagesList.addMessage("NBPASSENGERS_NEW");
			inpageErrorFlag=true;
		}
		if(e("Infant").style.display!='none'&&Number(fl.numberOfInfants.options[fl.numberOfInfants.selectedIndex].value)>Number(fl.numberOfAdults.options[fl.numberOfAdults.selectedIndex].value)){
			messagesList.addMessage("NBINFANTS");
			inpageErrorFlag=true;
		}
		if((Number(fl.numberOfInfants.options[fl.numberOfInfants.selectedIndex].value) + Number(fl.numberOfChildren.options[fl.numberOfChildren.selectedIndex].value))>0 && (Number(fl.numberOfAdults.options[fl.numberOfAdults.selectedIndex].value) ==0) ) {
			if(dpg.PRIVATE_LABEL.value=="AGENT") {
			messagesList.addMessage("CHILDNOTPERMITTEDWITHYOUTH");
			}
			else{
			messagesList.addMessage("CHILDNOTPERMITTEDWITHYOUTHACO");
			}
			inpageErrorFlag=true;
		}


		if(e('promotionCode')!=null){
			if(!validatePromotionCode()){
				messagesList.addMessage("PROMOTIONCODEERROR");
				inpageErrorFlag=true;
			}
			if(!validateInfantHomePromotion()){
				messagesList.addMessage("PROMOTIONCODEINFANTSERROR");
				inpageErrorFlag=true;
			}
		}
		if((e("CheckUpgrade").checked) && (e('invalidMessage').style.display == '')){
			if(dpg.PRIVATE_LABEL.value=="AGENT") {
			messagesList.addMessage("INVALIDCERTIFICATE");
			}else{
			messagesList.addMessage("INVALIDCERTIFICATEACO");
			}
			processErrors();
			fl.certificateField.focus();
			return false;
		}
		if ((e("CheckUpgrade").checked) && (fl.certificateField.value.length <7)){
			if(dpg.PRIVATE_LABEL.value=="AGENT") {
			messagesList.addMessage("INVALIDCERTIFICATE");
			}else{
			messagesList.addMessage("INVALIDCERTIFICATEACO");
			}
			processErrors();
			fl.certificateField.focus();
			return false;
		}
		if(inpageErrorFlag){
			processErrors();
			return false;
		}

		//SR97502801-------------------------------------------------------------
		var country_lang=checkLangCookie("new_lang_pref");
		var url ="http://www.aircanada.com/en/customercare/othercountries.html";
		if (document.flights.countryOfResidence.value == "O"){
			if(country_lang == "english" || country_lang == "us")
				url = "http://www.aircanada.com/en/customercare/othercountries.html";
			else if(country_lang == "french")
				url = "http://www.aircanada.com/fr/customercare/othercountries.html";
			else if(country_lang == "de")
				url = "http://www.aircanada.com/de/customercare/othercountries.html";
			else
				url = "http://www.aircanada.com/it/customercare/othercountries.html";
				
		    document.location = url;
		    return;
		}
		//-----------------------------------------------------------------------
		
		// NTP service is initiated to authorize. only if authorized, we send data returned
	// from NTP service to ETV, else display errors
	var countryCookie = getCookie("country_pref");
//2799	if (countryCookie == "CA" || countryCookie == "US"){
    var resCountry = fl.countryOfResidence.options[fl.countryOfResidence.selectedIndex].value;
//2799	   if (resCountry == "CA" || resCountry == "US") {
	    	if (e('Promotion Code')!= null){
	    	   if (checkAgentDetails()) {
		          setNTPFormFields("Flights");
					var objErrNTP;
					try{
			         document.FlightSearchNTPRequestForm.submit();
					}catch(objErrNTP){}
		       }
//2799		    }
	   } else {
			if (dpg.NTP_AUTHORIZATION)
	       		dpg.NTP_AUTHORIZATION.value="true";
		    if (fl.promotionCode != null)
    		   	 fl.promotionCode.value = "";
		}

//2799	}else{
//		if (dpg.NTP_AUTHORIZATION)
//	   	   dpg.NTP_AUTHORIZATION.value="true";
//	   	if (fl.promotionCode != null)
//   		   fl.promotionCode.value = "";
//	}
    	if (!(dpg.NTP_AUTHORIZATION) ||  dpg.NTP_AUTHORIZATION.value=="true") {
			if (e("bodyPage") && e("bodyPage").style.display == 'none')
				show("bodyPage");
			checkforTyrolean();
			setFormFields();
			var cookie_Life= 5*365;
			setCookie("cityCookie", fl.origin1.value, cookie_Life, "/")
			if (dpg.PRIVATE_LABEL.value == "AGENT")
				setFlightSearchCookie("ADO");
			else
				setFlightSearchCookie("ACO");
			var objErr2;
			try{
				dpg.submit();
			}catch(objErr2) {}
			WDSWaitingImage.pleaseWait("anim_waiting-bar");
		} else {
			if (e("bodyPage") && e("bodyPage").style.display == 'none')
				show("bodyPage");
		}
  } catch (err) {
    logError(err, "submitFlightSearch @2368");
  }
}
function displayDate(d)
{
	return formatToTwoDigits(d.getDate()) + "/" + formatToTwoDigits(d.getMonth()+1) + "/" + d.getFullYear();
}

function showWarning() {
  messagesList.errorMessages=new Array();
		var checkNeeded = isUsingTripCheckbox() && isRoundTrip();
		var inpageErrorFlag = false;
		origAirport=fetchAiport("org1","origin1");
		if(origAirport==null){
			processErrors();
			return false;
		}else{
			destAirport=fetchAiport("dest1","destination1");
			if(destAirport==null){
				processErrors();
				return false;
			}
		}
		if(origAirport.code==destAirport.code){
		  messagesList.addMessage("SAMEAIRPORTS",destAirport);
			processErrors();
			fl.dest1.focus();
			return false;
		}
		if(isUsingTripCheckbox() && isRoundTrip()){
			if(getDateNumber(1) > getDateNumber(2)){
				messagesList.addMessage("WRONGDATES");
				fl.departure2.focus();
				processErrors();
				return false;
			}
			else if ( getDateNumber(1) == getDateNumber(2) ) {
				if (!dpg.PRIVATE_LABEL.value == "AGENT"){
					if (fl.departTime1.options[fl.departTime1.selectedIndex].value > dfl.departTime2.options[fl.departTime2.selectedIndex].value) {
						messagesList.addMessage("WRONGDATES");
						processErrors();
						fl.departTime2.focus();
						return false;
					}
				}
			}

		}
		if(!isDatesValidForAirport(origAirport)) inpageErrorFlag=true;
		if(!isDatesValidForAirport(destAirport)) inpageErrorFlag=true;
		if(origAirport.errMsg!=null&&origAirport.errMsg!=""){
			messagesList.addMessage(origAirport.errMsg,origAirport);
			fl.org1.focus();
			inpageErrorFlag=true;
		}
		if(destAirport.errMsg!=null&&destAirport.errMsg!=""){
		  messagesList.addMessage(destAirport.errMsg,destAirport);
			fl.dest1.focus();
			inpageErrorFlag=true;
		}
		if((origAirport.country=="US"||destAirport.country=="US")&&(origAirport.country=="CU"||destAirport.country=="CU")){
			messagesList.addMessage("USACUBA");
			inpageErrorFlag=true;
		}
		if(origAirport.country=="US"&&destAirport.country=="US"){
			messagesList.addMessage("BOTHUSA");
			inpageErrorFlag=true;
		}
		if((Number(fl.numberOfAdults.options[fl.numberOfAdults.selectedIndex].value)+Number(fl.numberOfChildren.options[fl.numberOfChildren.selectedIndex].value))>9){
			messagesList.addMessage("NBPASSENGERS");
			inpageErrorFlag=true;
		}
		if(e("Infant").style.display!='none'&&Number(fl.numberOfInfants.options[fl.numberOfInfants.selectedIndex].value)>Number(fl.numberOfAdults.options[fl.numberOfAdults.selectedIndex].value)){
			messagesList.addMessage("NBINFANTS");
			inpageErrorFlag=true;
		}
		if(e("children").style.display!='none'&& (Number(fl.numberOfInfants.options[fl.numberOfInfants.selectedIndex].value) + Number(fl.numberOfChildren.options[fl.numberOfChildren.selectedIndex].value))>0 && (Number(fl.numberOfAdults.options[fl.numberOfAdults.selectedIndex].value) ==0) ) {
			if(dpg.PRIVATE_LABEL.value=="AGENT") {
			messagesList.addMessage("CHILDNOTPERMITTEDWITHYOUTH");
			}
			else{
			messagesList.addMessage("CHILDNOTPERMITTEDWITHYOUTHACO");
			}
			inpageErrorFlag=true;
		}
		if(e('promotionCode')!=null){
			if(!validatePromotionCode()){
				messagesList.addMessage("PROMOTIONCODEERROR");
				inpageErrorFlag=true;
			}
			if(!validateInfantHomePromotion()){
				messagesList.addMessage("PROMOTIONCODEINFANTSERROR");
				inpageErrorFlag=true;
			}
		}
		if(inpageErrorFlag){
			processErrors();
			return false;
		}
}
function isUsingTripCheckbox() {
	return fl.tripType && typeof(fl.tripType.checked) != "undefined";
}
function isRoundTrip() {
	if (typeof(fl.tripType) == "undefined") return false;
	if (typeof(fl.tripType) == "string")
		return fl.tripType[0].checked;
	else
		return getSelected(fl.tripType) == "R";
}
function isOneWayTrip() {
	if (typeof(fl.tripType) == "undefined") return false;
	if (typeof(fl.tripType) == "string")
		return fl.tripType[0].checked;
	else
		return getSelected(fl.tripType) == "O";
}
function getDateNumber(index)
{
	if (index == "Dep")
		index = 1;
	else if (index == "Ret")
		index = 2;
	//index starts from 1, not 0
	var datefield = eval("document.flights.departure"+index);
	var dv = datefield.value;
	return dv.substring(6,10)+dv.substring(3,5)+dv.substring(0,2);
}
function initAgentHomeCalendar(){

	if(Language == "english")
		lang = "en";
	else if(Language == "french")
		lang= "fr";
	else if (Language =="de" || Language == "it")
		lang = Language;
	initCalendar("departure1", "departure2");
	registerSelect("departure1", "departTime2");
	registerSelect("departure1", "numberOfAdults");
	registerSelect("departure1", "numberOfYouth");
	registerSelect("departure1", "numberOfChildren");
	registerSelect("departure1", "numberOfInfants");
	registerSelect("departure2", "numberOfAdults");
	registerSelect("departure2", "numberOfYouth");
	registerSelect("departure2", "numberOfChildren");
	registerSelect("departure2", "numberOfInfants");
	registerSelect("departure2", "classType");
	setNextFocusField("departure1", "departure2");
	setNextFocusField("departure2", "numberOfAdults");
}

// SR97502207
function isOAL(origCode, destCode){
	var tempOrigAirport=getAirportFromCode(origCode),tempDestAirport=getAirportFromCode(destCode);
	if(tempOrigAirport==null||tempDestAirport==null) return "";
	var depCountry=tempOrigAirport.country,arrCountry=tempDestAirport.country;
	var depAirport=tempOrigAirport.code, arrAirport= tempDestAirport.code;

	var foundOAL = false;
	var airlinelist = "";
	if(typeof(listOAL) == "undefined")
		return "AC";
	for (i=0;i<listOAL.length;i++){
		if(listOAL[i][0] == depAirport || listOAL[i][0] == arrAirport){
			if(listOAL[i][1].length == "3"){
				 if(listOAL[i][1] == depAirport || listOAL[i][1] == arrAirport){
					foundOAL = true;
					airlinelist = listOAL[i][2];
					break;
				 }
			}else if(listOAL[i][1].length == "2"){
				if((listOAL[i][0] == depAirport && listOAL[i][1] == arrCountry)||(listOAL[i][0] == arrAirport && listOAL[i][1] == depCountry)){
					foundOAL = true;
					airlinelist = listOAL[i][2];
					break;
				}
			}else if(listOAL[i][1] == "*"){
				foundOAL = true;
				airlinelist = listOAL[i][2];
				break;
			}
		}
	}
	if (airlinelist == "")
		return "AC"
	else
	return "AC;"+airlinelist;
}

//###############[ SR97502401 ]#################
// Hide 'Shop by' for International flights
//##############################################
function hideShop(x){
	var hasDomestic=false, hasTransborder=false, hasInternational=false, allFaredriven=true, tempFlightType;

	depCity=fl.origin1.value;
	arrCity=fl.destination1.value;
	if(depCity!=""&&arrCity!=""){
		tempFlightType=checkFlightSegmentType(depCity,arrCity);
		if(tempFlightType=="Domestic") hasDomestic=true;
		else if(tempFlightType=="Transborder") hasTransborder=true;
		else if(tempFlightType=="International") hasInternational=true;
		if(!checkforFareDriven(depCity,arrCity)) allFaredriven=false;
	}

	try {
		var pc = e("promotionCode").value;
	}catch(Err){
		pc="";
	}

	if( pc != "" || e("CheckUpgrade").checked ){
		if (fl.searchType)
		fl.searchType[0].checked=true;
		fl.Flexible.checked=false;
		fl.classType.value="E";
		hide("Shop");
	  	hide("Flexible");
	  	hide("Class");
	}else{
		try
		{
			checkFlightType(hasDomestic,hasTransborder,hasInternational,allFaredriven);
			if(isShown("search_button3")){
				hide("search_button1")
				hide("search_button2")
			}
		}catch(objErr4)
		{
  			logError(objErr4, "error in hideShop function @2579");
  		}
	}
}

//#################[ R24-SR97502187 ]#################
// Display Upgradeable Fares
// Show/hide 'More Options' section
//####################################################
function toggleMoreOptions(){
	var el = e("more_options");
	countrydisplay=dpg.PRIVATE_LABEL.value!="AGENT"&&!(getCookie("AC-Signon-Cookie")&&getCookie("AC-Session-Cookie"));

	if (el.style.display != 'none'){
		el.style.display = 'none';
		if(countrydisplay){
			if(e("Shop").style.display != 'none'){
				e("search_button2").style.display = '';
			}else{
				e("search_button1").style.display = '';
			}
		}else{
			hide("search_button1");
			e("search_button2").style.display = '';
		}
	}else{
		hide("search_button1");
		hide("search_button2");
		el.style.display = '';
		if (e("CheckUpgrade").checked){
			show("certificate_number");
		}
		e("search_button3").style.display = '';
		hide("more_options_label1");
		e("more_options_label2").style.display = '';

	}
}

function toggleCertificate(){
	var el = e("certificate_number");

	if(e("CheckUpgrade").checked){
		el.style.display ='block';
		if (e("ar_right_image1"))
			hide("ar_right_image1");
		hide("ar_right_image2");
	}
	else{
		el.style.display ='none';
		hide('invalidMessage');
		hide('invalid_img');
		hide('validMessage');
		hide('valid_img');
		document.flights.certificateField.value = "";
		if (e("ar_right_image1"))
			e("ar_right_image1").style.display = '';
		e("ar_right_image2").style.display = '';
	}
}//last row of every array is the error message of that language
// Ekidev from here
// PKorth 20090107:
// the code following does not recognize the flight types properly
function validateCertificate(idField){
// PKorth 20090107: added as quick fix for ADO Multicity
fl = document.flights;
	var certificateNo = idField.value;
	var invalidCertMsg = null;

	// Basic validation.
	if (isEmpty(certificateNo) || certificateNo.length != 7) {
		e('validMessage').style.display = 'none';
		e('invalidMessage').style.display = 'none';
		e('valid_img').style.display = 'none';
		e('invalid_img').style.display = 'none';
		return false;
	}

	// Set certificate array.
	var certArray;
	var language = document.flightsPlanitgo.LANGUAGE.value;
	switch(language) {
		case 'FR': case'DE': case 'IT':
			certArray = upgradeCertificates[language];
			break;
		default:
			certArray = upgradeCertificates['EN'];
	}

	// Find certificate from entered certificate number.
	var maxIndex = certArray.length - 3;
	var index = 0;
	for(index = 0; index < maxIndex; index++){	        
		if(certArray[index][0] == certificateNo)
			break;
	}
	if (index == maxIndex) {
		// No matching certificates.
		invalidCertMsg =  certArray[certArray.length - 1][0];
		displayInvalidCertMessage(invalidCertMsg);
		return false;
	}

	var startDate = parseDateFromForm(certArray[index][2]);
	var endDate   = parseDateFromForm(certArray[index][3]);

	// Round-trip.
	if(isUsingTripCheckbox() && isRoundTrip()) {
		var departureDate = parseDateFromForm(fl.departure1.value);
		var returnDate = parseDateFromForm(fl.departure2.value);

		if (departureDate == null && returnDate == null) {
			return true;
		}

		if (! isDateBetween(startDate, departureDate, endDate) ||
		    ! isDateBetween(startDate, returnDate, endDate)) {
			invalidCertMsg = isAgency() ? certArray[certArray.length - 2][0] : certArray[certArray.length - 4][0];
		}
	}

	// One-way trip.
	else if(isUsingTripCheckbox() && isOneWayTrip()) {
		var departureDate = parseDateFromForm(fl.departure1.value);

		if (departureDate == null) {
			return true;
		}

		if (! isDateBetween(startDate, departureDate, endDate)) {
			invalidCertMsg = isAgency() ? certArray[certArray.length-3][0] : certArray[certArray.length-5][0];
		}
	}

	// Multi-city.
	else if(fl.departure2) {
		var nbSegments = getNumberOfMulticitySegments();
		var isDateValid = true;
		var num;
		for (num = 1; num <= nbSegments; num++) {
			var d = parseDateFromForm(document.flights["departure" + num].value);
			if (d != null && ! isDateBetween(startDate, d, endDate)) {
				isDateValid = false;
				break;
			}
		}

		if (! isDateValid) 
			invalidCertMsg = isAgency() ? certArray[certArray.length - 2][0] : certArray[certArray.length - 4][0];
	}
	if (invalidCertMsg != null) {
		displayInvalidCertMessage(invalidCertMsg);
		return false;
	}

	displayValidCertMessage(certArray[index][1]);
	return true;
}

function isDateBetween(startDate, checkDate, endDate) {
	if (startDate == null || checkDate == null || endDate == null)
		return false;
	if (! isDate1BeforeDate2(startDate, checkDate) || ! isDate1BeforeDate2(checkDate, endDate))
		return false;
	return true;
}

function displayValidCertMessage(message) {
	e('validMessage').style.display = '';
	e('validMessage').innerHTML = message;
	e('invalidMessage').style.display = 'none';
	e('valid_img').style.display = '';
	e('invalid_img').style.display = 'none';
}

function displayInvalidCertMessage(message) {
	e('validMessage').style.display = 'none';
	e('invalidMessage').style.display = '';
	e('invalidMessage').innerHTML = message;
	e('valid_img').style.display = 'none';
	e('invalid_img').style.display = '';
}

// Get number of populated multi-city segments.
function getNumberOfMulticitySegments() {
	var nbSegments;
	for (nbSegments = MAX_CITY_PAIRS; nbSegments > 1; nbSegments--) {
		var org = e('org' + nbSegments);
		if (org && org.value != "") break;
		var dest = e('dest' + nbSegments);
		if (dest && dest.value != "") break;
	}
	return nbSegments;
}
// Ekidev to here

// upgradeCertificates moved to lookup_data.js

// Script loader indicator.
var jsName = "citysearch.js";
if (typeof logLoaded == "undefined") {
  logLoaded = function(){};
}
logLoaded(jsName);

