/** begin /delta/shared_content/edgecache/js/core/util.js **/
/* Generic Base Object */
function GenObj() {}
GenObj.prototype.setProp = function(prop,value) { this[prop] = value; };
GenObj.prototype.getProp = function(prop) { return this[prop]; };

function get(id) { return document.getElementById(id); }
function getByTagName(tag) { return document.getElementsByTagName(tag); }
function getByClassName(clsName) {
    var retVal = new Array();
    var elements = document.getElementsByTagName("*");
    for(var i = 0;i < elements.length;i++){
        if(elements[i].className.indexOf(" ") >= 0){
            var classes = elements[i].className.split(" ");
            for(var j = 0;j < classes.length;j++){
                if(classes[j] == clsName){
                    retVal.push(elements[i]);
				}
            }
        } else if(elements[i].className == clsName) {
            retVal.push(elements[i]);
		} else {
			
		}
    }
    return retVal;
}
function exists(o) { 
	try {
		if((typeof(o) !== "undefined")&&(o!=undefined)&&(o!=null)&&(o!="null")) { return true; } else { return false; } 
	} catch(error){ return false; }
}
function getInnerHTML(id) { return document.getElementById(id).innerHTML; }
function setInnerHTML(id, d) { var e = get(id); if (e != null) { e.innerHTML = d; } }
function getClassName(id) { return document.getElementById(id).className; }
function setClassName(id, c) {  var e = get(id);if (e != null) { e.className = c; } }
function getStyleAttr(id,p) { var e = get(id);if(e != null) { return e.style[p]; } }
function setStyleAttr(id,p,v) { var e = get(id);if(e != null) { e.style[p] = v; } }
function changeCLS(id,cls) { setClassName(id,cls); }
function formatURL(url){ var formattedURL = unescape(url);window.location = formattedURL;}

function show(id) {
	var display = (arguments.length > 1) ? arguments[1] : "block";
	if (typeof(id) === "string" ) {
		var e = get(id);
		if (e != null) {
			setStyleAttr(id,"display",display);
		}
	} else {
		for (var i=0, j=id.length; i<j; i++) {
			var e = get(id[i]);
			if (e != null) {
				setStyleAttr(e.id,"display",display);
			}
		}
	}
}
function hide(id) {
	var display = (arguments.length > 1) ? arguments[1] : "none";
	if (typeof(id) === "string" ) {
		var e = get(id);
		if (e != null) {
			setStyleAttr(id,"display",display);
		}
	} else {
		for (var i=0, j=id.length; i<j; i++) {
			var e = get(id[i]);
			if (e != null) {
				setStyleAttr(e.id,"display",display);
			}
		}
	}
}

function showInline(id) { show(id,"inline"); }
function hideInline(id) { hide(id,"hidden"); }
function displayInline(id) { show(id,"inline"); }
function hideInline(id) { hide(id,"hidden"); }
function toggle(id) {
	if(get(id)!=null)
	{
		switch(getStyleAttr(id,"display"))
		{
			case "block":
				hide(id);
				break;
			case "inline":
				hideInline(id);
				break;
			case "none":
				show(id);
				break;
			case "hidden":
				displayInline(id);
				break;
			default:
				show(id);
				hide(id);
				break;
		}
	}
}
function showDiv(id) { show(id); }
function hideDiv(id) { hide(id); }
function elementHide(id) { document.getElementById(id).style.visibility='hidden'; }
function elementShow(id) { document.getElementById(id).style.visibility='visible'; }

function getContextPath() {
	var URIBegin = window.location.href.lastIndexOf('.delta.com') + 10;
	var URIEnd = (window.location.href.lastIndexOf('?') > URIBegin) ? window.location.href.lastIndexOf('?') : window.location.href.length;
	var URI = window.location.href.substring(URIBegin, URIEnd);
	var pageArray = URI.split("/");
	if(pageArray.length > 1 && pageArray[1] != "index.jsp") {
		return pageArray[1];
	} else {
		return "home";
	}
}

function getPosition(e) {
	e = e || window.event;
	var cursor = {x:0, y:0};
	if (e.pageX || e.pageY) {
		cursor.x = e.pageX;
		cursor.y = e.pageY + 15;
		//Minus 115 to offset size of header in global.jsp file
	} else {
		if(exists(get('awards')) && isBadBrowser()){
			cursor.x = e.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft) - document.documentElement.clientLeft + 15;
			cursor.y = e.clientY + document.body.scrollTop - 350;
		} else {
			cursor.x = e.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft) - document.documentElement.clientLeft;
			cursor.y = e.clientY + (document.documentElement.scrollTop || document.body.scrollTop) - document.documentElement.clientTop + 15;
		}
	}
	return cursor;
 }
function getElementXAndYPos(element) {
	var curLeft = 0, curTop = 0;
	if(element.offsetParent) {
		while (element.offsetParent) {
			curLeft += element.offsetLeft
			curTop += element.offsetTop
			element = element.offsetParent;
		}
	} else if(element.x) {
		curLeft = element.x;
		curTop = element.y;
	} else {}
	return {x:curLeft, y:curTop};
}

var BrowserLanguageSettings = {
	languageSettings : null, languageCollection : [], languageCollectionCount : 0,
	acceptedLanguageDelimiter : ",", acceptedLanguageQualityIndicator : ";", localeLanguageDelimiter : "-",
	defaults : { browserAccept : "en-us", locale : "us", language : "en" },
	findPreferencesStruct : { browserAccept : 0, language : 1, locale : 2 },
	getLocaleByLanguage : function(languageCode) {
		for (var i=0, j=LanguageOptions.length; i<j; i++) {
			if (LanguageOptions[i].getProp("language_code").toLowerCase() === trimString(languageCode).toLowerCase()) {
				return LanguageOptions[i].getProp("default_country");
			}
		}
		return languageCode;
	},
	parseAcceptedLanguage : function(languagePreference) {
		var splitPreference = languagePreference.split(this.acceptedLanguageQualityIndicator);
		var preferredLanguage = splitPreference.length > 0 ? splitPreference[0] : null;
		if (exists(preferredLanguage)) {
			var preferredLanguageSplit = preferredLanguage.split(this.localeLanguageDelimiter);
			var localeCode = null, languageCode = null;
			switch (preferredLanguageSplit.length) {
				case 2:
					localeCode = preferredLanguageSplit[1];
				case 1:
					languageCode = preferredLanguageSplit[0];
					localeCode = exists(localeCode) ? localeCode : this.getLocaleByLanguage(languageCode);
					break;
			}
			return { browserAccept : languageCode + this.localeLanguageDelimiter + localeCode, language : languageCode, locale : localeCode };
		}
		return null;
	},
	isLanguageSupported : function(languageCode) {
		for (var i=0, j=LanguageOptions.length; i<j; i++) {
			if (trimString(LanguageOptions[i].getProp("language_code")).toLowerCase() === trimString(languageCode).toLowerCase()) {
				return true;
			}
		}
		return false;
	},
	getSupportedPreferenceFromCollection : function() {
		for (var i=0; i<this.languageCollectionCount; i++) {
			var currentPreference = this.parseAcceptedLanguage(this.languageCollection[i]);
			if (exists(currentPreference)) {
				if (this.isLanguageSupported(currentPreference.language)) {
					return currentPreference;
				}
			}
		}
		return this.defaults;
	},
	getPreferenceItem : function(structChoice) {
		switch (structChoice) {
			case this.findPreferencesStruct.browserAccept:
				return this.getSupportedPreferenceFromCollection().browserAccept;
			case this.findPreferencesStruct.language:
				return this.getSupportedPreferenceFromCollection().language;
			case this.findPreferencesStruct.locale:
				return this.getSupportedPreferenceFromCollection().locale;
			default:
				return null;
		}
	},
	init : function(browserAcceptLanguage) {
		this.languageSettings = browserAcceptLanguage;
		this.languageCollection = this.languageSettings.split(this.acceptedLanguageDelimiter);
		this.languageCollectionCount = this.languageCollection.length;
	}
};

/* moved from preferences.js for use with fpe engine */
function getPrefs(){
	var pref=getCookie("pref");
	if ( !exists(pref) && typeof(BrowserLanguageSettings) === "object" && typeof(BrowserLanguageSettings.getPreferenceItem) === "function") { 
		pref = BrowserLanguageSettings.getPreferenceItem(BrowserLanguageSettings.findPreferencesStruct.browserAccept);
	}
	if (!exists(pref)) { 
		pref = getDefault(window.location.toString().match("//[^.]*").toString().split("//")[1]); 
	}
	if (arguments.length==1) { return pref.split("-")[1]; }
	else if(arguments.length==2)
	{
		var rtnString = "lang=" + pref.split("-")[0] + ";";
		rtnString += "loc=" + pref.split("-")[1] + ";";
		return rtnString;
	}
	else { return pref; }
}
function getLang() { return getPrefs().split("-")[0]; }
function getLoc() { return getPrefs().split("-")[1]; }
function showHoverContent(event,w,h,elm,source,scrolling,offX,offY,iFrameId,ignoreXAxis) {
	if(hoverNumber == 0){
		var cursor = getPosition(event);
		var element = get(elm);
		iFrameId = arguments[8] ? iFrameId : "pwm_iframe";	
		//iFrame constructor		
		ifrm = document.createElement("IFRAME");
		ifrm.setAttribute("src", source);
		ifrm.setAttribute("id", iFrameId);
		ifrm.setAttribute("scrolling", scrolling);
		ifrm.style.width = w +"px";
		ifrm.style.height = h +"px";
		element.appendChild(ifrm);
		element.style.display='block';
		element.style.width = w + "px";
		element.style.height = h + "px";
		if((ignoreXAxis != null) && (ignoreXAxis)) {
			element.style.left = offX + "px"; 
		}
		else {
			element.style.left = cursor.x + offX + "px";
		}
		element.style.top = cursor.y + offY + "px";
		hoverNumber = 1;
	} else {
		return;
	}
}
function hideHoverContent(event,elm){
	var element = document.getElementById(elm);
	element.style.display = "none";
	if(element.hasChildNodes()){
		while (element.childNodes.length >= 1){
		element.removeChild(element.firstChild);
		}
	}
	hoverNumber = 0;
	
}
function showDebugMsg(msg) {
	try { console.log(msg); } catch(err) {
		var curHtml = (getInnerHTML("debug") != "" ) ? curHTML + "<hr />" : msg;
		setInnerHTML("debug",curHtml);
		if(getStyleAttr("debug","display") != "block") {
			setStyleAttr("debug","width","200px");
			setStyleAttr("debug","height","250px");
			setStyleAttr("debug","padding","5px");
			setStyleAttr("debug","backgroundColor","#eee");
			setStyleAttr("debug","position","absolute");
			setStyleAttr("debug","top","0");
			setStyleAttr("debug","right","0");
			setStyleAttr("debug","overflow","auto");
			setStyleAttr("debug","display","block");
		}
	}
}

function addScriptTag(src) {
	var replaceStr = "_dyn" + numAddedScripts + "_";
	numAddedScripts++;
	var id = src.replace(/\./,replaceStr);
	//alert(id);
	if(!get(id)) {
		var s= document.createElement('script');
		s.type= 'text/javascript';
		s.onload= helper; /* good browsers */
		s.onreadystatechange= function () { if (this.readyState == 'complete' || this.readyState == 'loaded') { helper(); }}; /* ie */
		s.src= src; s.id = id;
		s.setAttribute('src',src); s.setAttribute('id',id);
		document.getElementsByTagName('head')[0].appendChild(s);
	}
	else {
		// script is already added to the page
	}
}
function helper() { return true; }

function strCompare(a,b) { if(a.toLowerCase()==b.toLowerCase()) { return true; }  else { return false;  } }
function stripHTML(str) { return str.replace(/\<.+?\>/g, ""); }
function trimString (str) { str = this != window? this : str; return str.replace(/^\s+/g, '').replace(/\s+$/g, '');}

/* use with EXTREME caution */
function addEvent(elm, evType, fn, useCapture)
{
	if(elm.addEventListener){ elm.addEventListener(evType, fn, useCapture); return true; }
	else if(elm.attachEvent){ var r = elm.attachEvent('on' + evType, fn); return r; }
	else { elm['on' + evType] = fn; }
}
function removeEvent( elm, evType, fn ) {
	if (elm.removeEventListener) {
		elm.removeEventListener( evType, fn, false );
	}
	else if (elm.detachEvent) {
		elm.detachEvent( "on" + evType, fn );
	}
}

function formatTo(base, precision, quantity) {
	var a = roundTo(base, precision);
	//alert(a + "x" + quantity); 
	var b = a * quantity;
	 	b = roundTo(b,2);
	var s = b.toString();
	
	var decimalIndex = s.indexOf(".");
	if(precision > 0 && decimalIndex < 0){
		decimalIndex = s.length;
		s += '.';
	}
	while (decimalIndex + precision + 1 > s.length){
		s += '0';
	}
	return s;
}
function roundTo(base, precision) {
  var m = Math.pow(10, precision);
  var a = Math.round(base * m) / m;
  return a;
}



/* -------------------- functions found online -------------------- */
// copyright Stephen Chapman 24th March 2006, 10th February 2007
// permission to use this function is granted provided
// that this copyright notice is retained intact
//javascript.about.com/library/blnumfmt.htm
function formatNumber(num,dec,thou,pnt,curr1,curr2,n1,n2) { var x = Math.round(num * Math.pow(10,dec));if (x >= 0) n1=n2='';var y = (''+Math.abs(x)).split('');var z = y.length - dec; if (z<0) z--; for(var i = z; i < 0; i++) y.unshift('0');y.splice(z, 0, pnt); while (z > 3) {z-=3; y.splice(z,0,thou);}var r = curr1+n1+y.join('')+n2+curr2;return r;}

function isComplete() {pageLoaded = true; }

addEvent(window,"load",isComplete,false);
var numAddedScripts = 0;
var pageLoaded = false;
var hoverNumber = 0; /* hoverNumber controls number of rollover popups with a limit of 1 */

function conCatTool() {
	var _self = this;
	this.conCatValue = [];
	this.currentIndex = 0;
	this.disableHTMLTranslationStartTag = "\n<!-- mp_trans_disable_start -->\n";
	this.disableHTMLTranslationEndTag = "\n<!-- mp_trans_disable_end -->\n";
	this.conCat = function(value, disableTranslation) {
		disableTranslation = arguments[1] ? disableTranslation : false;
		_self.conCatValue[_self.currentIndex] = (disableTranslation ? _self.disableHTMLTranslationStartTag : "") + value + (disableTranslation ? _self.disableHTMLTranslationEndTag : "");
		_self.currentIndex ++;
	};
	this.toString = function(doClear, joinValue) {
		var returnValue = _self.conCatValue.join( (exists(joinValue) ? joinValue : "\n") );
		if(exists(doClear) && doClear) {
			_self.clear();
		}
		return returnValue;
	};
	this.clear = function() {
		_self.conCatValue.length = 0;
		_self.currentIndex = 0;
	};
}

var mp_util = {
	startMPTag : "\n<!-- ",
	endMPTag : " -->\n",
	equals : "=",
	quote : "\"",
	emptyString : "",
	disableStart : "mp_trans_disable_start",
	disableEnd : "mp_trans_disable_end",
	partialStart : "mp_trans_partial_start",
	partialEnd : "mp_trans_partial_end",
	enableStart : "mp_trans_enable_start",
	enableEnd : "mp_trans_enable_end",
	removeStart : "mp_trans_remove_start",
	removeEnd : "mp_trans_remove_start",
	addStart : "mp_trans_add ",
	nestedDisableStart : "mp_trans_disable_start --]>",
	nestedDisableEnd : "mp_trans_disable_end --]>",
	transJSStartTag : "mp_trans_textjs_start",
	transJSEndTag : "mp_trans_textjs_start",
	navDisableStart : "mp_trans_navdisable_start",
	navDisableEnd : "mp_trans_navdisable_end",
	enableTransURLJSStart : "mp_trans_urljs_enable_start",
	endableTransURLJSEnd : "mp_trans_urljs_enable_end",
	disableTransURLJSStart : "mp_trans_urljs_disbale_start",
	disableTransURLJSEnd : "mp_trans_urljs_disbale_end",
	processDisableStart : "mp_trans_process_disable_start",
	processDisableEnd : "mp_trans_process_disable_end",
	translate : "mp_trans_translate=\"",
	schedule : "mp_trans_schedule=\"",
	addLanguages : function(languages) {
		return exists(languages) ? this.equals + this.quote + languages + this.quote : this.emptyString;
	},
	returnContent : function(content) {
		return exists(content) ? content : this.emptyString;
	},
	returnDisableStartTag : function(languages) {
		return this.startMPTag + this.disableStart + this.addLanguages(languages) + this.endMPTag;
	},
	returnDisableEndTag : function() {
		return this.startMPTag + this.disableEnd + this.endMPTag;
	},
	doDisable : function(content, languages) {
		return this.returnDisableStartTag(languages) + this.returnContent(content) + this.returnDisableEndTag();
	},
	returnStartPartialTag : function(languages) {
		return this.startMPTag + this.partialStart + this.addLanguages(languages) + this.endMPTag;
	},
	returnEndPartialTag : function() {
		return this.startMPTag + this.partialEnd + this.endMPTag;
	},
	doPartial : function(content, languages) {
		return this.returnStartPartialTag(languages) + this.returnContent(content) + this.returnEndPartialTag();
	},
	returnEnableStartTag : function(languages) {
		return this.startMPTag + this.enableStart + this.addLanguages(languages) + this.endMPTag;
	},
	returnEnableEndTag : function() {
		return this.startMPTag + this.enableEnd + this.endMPTag;
	},
	doEnable : function(content, languages) {
		return this.returnEnableStartTag(languages) + this.returnContent(content) + this.returnEnableEndTag();
	},
	returnRemoveStartTag : function(languages) {
		return this.startMPTag + this.removeStart + this.addLanguages(languages) + this.endMPTag;
	},
	returnRemoveEndTag : function() {
		return this.startMPTag + this.removeEnd + this.endMPTag;
	},
	doRemove : function(content, languages) {
		return this.returnRemoveStartTag(languages) + this.returnContent(content) + this.returnRemoveEndTag();
	},
	add : function(content, languages, nestedContent) {
		return this.startMPTag + this.addStart + this.addLanguages(languages) + this.returnContent(content) + this.nestedDisable(nestedContent) + this.endMPTag;
	},
	nestedDisable : function(content) {
		return exists(content) ? this.startMPTag + this.nestedDisableStart + content + this.startMPTag + this.nestedDisableEnd : this.emptyString;
	},
	disableNav : function(content) {
		return this.startMPTag + this.navDisableStart + this.endMPTag + this.returnContent(content) + this.startMPTag + this.navDisableEnd + this.endMPTag;
	},
	enableTransURLJS : function(content) {
		return this.startMPTag + this.enableTransURLJSStart + this.endMPTag + this.returnContent(content) + this.startMPTag + this.endableTransURLJSEnd + this.endMPTag;
	},
	disableTransURLJS : function(content) {
		return this.startMPTag + this.disableTransURLJSStart + this.endMPTag + this.returnContent(content) + this.startMPTag + this.disableTransURLJSEnd + this.endMPTag;
	},
	processDisable : function(content) {
		return this.startMPTag + this.processDisableStart + this.endMPTag + this.returnContent(content) + this.startMPTag + this.processDisableEnd + this.endMPTag;
	},
	translateTag : function(isDoTranslate) {
		return this.startMPTag + this.translate + isDoTranslate + this.quote + this.endMPTag;
	},
	scheduleTag : function(isDoSchedule) {
		return this.startMPTag + this.schedule + isDoSchedule + this.quote + this.endMPTag;
	}
};

var jsObjectArraySortUtil = {
	sortProperty : null,
	doSort : function(one, two) {
		if (exists(jsObjectArraySortUtil.sortProperty)) {
			var valueOne = one[jsObjectArraySortUtil.sortProperty];
			var valueTwo = two[jsObjectArraySortUtil.sortProperty];
			if (exists(valueOne) && exists(valueTwo)) {
				if (typeof(valueOne) === "string" && typeof(valueTwo) === "string") {
					valueOne = valueOne.toLowerCase();
					valueTwo = valueTwo.toLowerCase();
				}
				if (valueOne < valueTwo) {
					return -1;
				} else if (valueOne > valueTwo) {
					return 1; 
				} else {
					return 0;
				} 
			}
		}
		return 0;
	}
}

function collapseTable(elemId){
	if(elemId != null && elemId != ""){
		if(elemId.indexOf('_') > -1){
			elemId = elemId.split('_')[1];
		}
		setClassName(elemId + "_table_control", "display_ctl_closed");
		hide(elemId + "_table_container");		
	} else {
		return;
	}
}
function expandTable(elemId){
	if(elemId != null && elemId != ""){
		if(elemId.indexOf('_') > -1){
			elemId = elemId.split('_')[1];
		}
		setClassName(elemId + "_table_control", "display_ctl_open");
		show(elemId + "_table_container");
	} else {
		return;
	}
}

function isBadBrowser() { 
	return ( !exists(window.opera) && exists(window.ActiveXObject) && exists(document.all) ) ? true : false; 
}

function isDesktopAgent(){
	var accessType = navigator.platform;
		accessType = accessType.toLowerCase();
	var desktopAgent = false;
	
	if(accessType.indexOf('win') > -1 
			|| accessType.indexOf('mac') > -1
			|| accessType.indexOf('linux') > -1){
		
		desktopAgent = true;	
	}
	
	return desktopAgent;
}

var monthUtility = {
	months:['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
	monthsLong:['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
	getMonths : function(monthIndex){
		return monthUtility.months[monthIndex];
	},
	getMonthsFull : function(monthIndex){
		return monthUtility.monthsLong[monthIndex];
	}
};


/*
 * Date Format 1.2.3
 * (c) 2007-2009 Steven Levithan <stevenlevithan.com>
 * MIT license
 *
 * Includes enhancements by Scott Trenda <scott.trenda.net>
 * and Kris Kowal <cixar.com/~kris.kowal/>
 *
 * Accepts a date, a mask, or a date and a mask.
 * Returns a formatted version of the given date.
 * The date defaults to the current date/time.
 * The mask defaults to dateFormat.masks.default.
 */

var dateFormat = function () {
	var	token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZA]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (val, len) {
			val = String(val);
			len = len || 2;
			while (val.length < len) val = "0" + val;
			return val;
			
		};

	// Regexes and supporting functions are cached through closure
	return function (date, mask, utc) {
		var dF = dateFormat;

		// You can't provide utc if you skip other args (use the "UTC:" mask prefix)
		if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
			mask = date;
			date = undefined;
		}

		// Passing date through Date applies Date.parse, if necessary
		date = date ? new Date(date) : new Date;
		if (isNaN(date)) throw SyntaxError("invalid date");

		mask = String(dF.masks[mask] || mask || dF.masks["default"]);

		// Allow setting the utc argument via the mask
		if (mask.slice(0, 4) == "UTC:") {
			mask = mask.slice(4);
			utc = true;
		}

		var	_ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
				d:    d,
				dd:   pad(d),
				ddd:  dF.i18n.dayNames[D],
				dddd: dF.i18n.dayNames[D + 7],
				m:    m + 1,
				mm:   pad(m + 1),
				mmm:  dF.i18n.monthNames[m],
				mmmm: dF.i18n.monthNames[m + 12],
				yy:   String(y).slice(2),
				yyyy: y,
				h:    H % 12 || 12,
				hh:   pad(H % 12 || 12),
				H:    H,
				HH:   pad(H),
				M:    M,
				MM:   pad(M),
				s:    s,
				ss:   pad(s),
				l:    pad(L, 3),
				L:    pad(L > 99 ? Math.round(L / 10) : L),
				t:    H < 12 ? "a"  : "p",
				tt:   H < 12 ? "am" : "pm",
				T:    H < 12 ? "A"  : "P",
				TT:   H < 12 ? "AM" : "PM",
				Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
				o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
				S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10],
				A:    ["0", ""][d < 10 ? 0 : 1] //this option appends 0 if desired
			};

		return mask.replace(token, function ($0) {
			return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
		});
	};
}();

// Some common format strings
dateFormat.masks = {
	"default":      "ddd mmm dd yyyy HH:MM:ss",
	shortDate:      "m/d/yy",
	mediumDate:     "mmm d, yyyy",
	longDate:       "mmmm d, yyyy",
	fullDate:       "dddd, mmmm d, yyyy",
	shortTime:      "h:MM TT",
	mediumTime:     "h:MM:ss TT",
	longTime:       "h:MM:ss TT Z",
	isoDate:        "yyyy-mm-dd",
	isoTime:        "HH:MM:ss",
	isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
	isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
	dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
	monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

// For convenience...
Date.prototype.format = function (mask, utc) {
	return dateFormat(this, mask, utc);
};



/** end /delta/shared_content/edgecache/js/core/util.js **/

function currentPage() {
	var pageURL = "";
	var pageArray = window.location.toString().split("?");
	var re = new RegExp(/https?:\/\/(([a-zA-z]{2})\.)?delta.com/);
	if(pageArray.length>1)
	{
		if (pageArray[0].match(re)) 
		{
			re = new RegExp(/https?:\/\/((si|pl|qa)\.)?delta.com/);
			if(!pageArray[0].match(re)) { pageArray.shift(); }
		}
	}
	re.compile(/\d+;/);
	pageURL = pageArray[0].toString();
	pageURL = pageURL.replace(re,'');
	re.compile(/https?:\/\/[a-zA-Z]*\.?delta.com/);
	pageURL = pageURL.replace(re,"");
	return pageURL;
}
function addBehaviors() {
	var pageURL = currentPage();
	if(exists(get("menu1Container"))) { setStyleAttr("menu1Container","display","block"); }
	if(exists(get("menu2Container"))) { setStyleAttr("menu2Container","display","block"); }
	if(exists(get("menu3Container"))) { setStyleAttr("menu3Container","display","block"); }
	if(exists(get("menu4Container")))
	{
		if(get("nonjs_Worldwide")!=null&&get("nonjs_Worldwide")!="null") { setStyleAttr("nonjs_Worldwide","display","none"); }
		if(get("lang_loc")!=null&&get("lang_loc")!="null") { setStyleAttr("lang_loc","display","inline"); }
		setStyleAttr("menu4Container","display","block");
	}
//	switch(pageURL)
//	{
//		case ("/home/index.jsp"||"/home/index.jsp#"||"/home/"||"/home/#"):
	//		setStyleAttr('hpApplications','display','block');
//			break;
//		default:
//			break;
//	}
	asiaMarkets.isAsianCountry();
}

// function: left nav rollover
function navRoll(item) {
	// if the nav item is not defaulted to the rollover state then change the nav item class
	if(item.parentNode.className != 'navHot')
	{
		// if the nav item is in the hover state change it to the default state
		if(item.parentNode.className == 'navHover') { item.parentNode.className = ''; }
		// if the navitem is not in the hover state change it to the hover state
		else { item.parentNode.className = 'navHover'; }
	}
}

function gotoAnchorLink(index) {
	if(index != null && index != "")
	{
		var locationString = document.location.href;
		var locationArray = locationString.toString().split('#');
		document.location.href = locationArray[0] + "#" + index;
	}
}

//jump to tab URL when user clicks on tab
function goURL(theUrl) { document.location.href = theUrl; }


function initScreenOverlay() { 
    var msgbox = document.getElementById('popupDiv');
    if (msgbox == null
          || msgbox.style.display == 'none') {
       return;
    }

    var footerdiv = document.getElementById('Footer');
    var bottomOffset = document.body.clientWidth;
    if (footerdiv != null) {
       bottomOffset =  footerdiv.offsetTop;
    }
    bottomOffset = eval(bottomOffset - 80);
    if (msgbox.style.display != 'none') {
        var offsetht = msgbox.offsetHeight;
        var offsetwd = msgbox.offsetWidth;

        var toppos =  Math.round(((document.body.clientHeight - offsetht) / 2.5) + document.body.scrollTop);
        var leftpos =  Math.round((document.body.clientWidth - offsetwd) / 4);

        var totalht = toppos +  offsetht;
        if (totalht > bottomOffset ) {
           toppos = eval(toppos - (totalht - bottomOffset));
        }
        if (toppos < 188) {
           toppos = 188;
        }
        msgbox.style.top = toppos + "px";

        var totalwd = leftpos +  offsetwd;
        if (totalwd > 750) {
           leftpos = eval(leftpos -(totalwd - 750));
        }
        if (leftpos < 0) {
           leftpos = 0;
        }
        msgbox.style.left  = leftpos + "px" ;
    }
} 
 

function resetPopupFrame() { 
    var msgbox = document.getElementById('popupFrame');
    if (msgbox != null) {
       document.getElementById('popupFrame').src = '/shared/components/blank.jsp';
    }

}

function openHelp(url,e) {
 w = 474;
 h = 408;
 openWin(url, e, w, h, "yes");
}

function openHelp2(url,e,v) {

   w = 474;
   h = v;
   openWin(url, e, w, h, "yes");
}


var cWin;
function openNewWin(url,name,w,h,scroll,chrome) {
	if(!arguments[5])  {
		chrome = 'no';
	}
	var att = 'width='+ w +',height='+ h +',left=50,top=50,scrollbars='+ scroll +',resizable=yes,toolbar=' + chrome + ',location=' + chrome + ',status=' + chrome + ',menubar=' + chrome;
	cWin = window.open(url,name,att);
	self.name="Main";
}

function openWin(url,name,wd,ht,scroll) {
	openNewWin(url, "deltaPopup", wd, ht, scroll);
	//DeltaOverlayUtil.showPopupOverlay(url, name, wd, ht, scroll);
}


function closeWin() {
   if (window.opener) { 
	   self.close();
   } else if (window.parent != window) {
      DeltaOverlayUtil.hideOverlay();
    } else if(cWin != null) { 
         cWin.close(); 
         cWin = null; 
   }
}

function closeNewWin() {
      self.close();
}

function hidePopupHeader() {
    var divArea = document.getElementById('popHeader');
    if (divArea != null) {
        divArea.style.display = 'none';
    }
}

function hidePopupFrameHeader() {
   try {
      var popupframe = document.getElementById('popupFrame');   
      if (popupframe && popupframe.contentWindow) {
            popupframe.contentWindow.hidePopupHeader();
      }
   } catch (e) {}
}

function closePopupDiv() {
    var divArea = document.getElementById('popupDiv');
    if (divArea != null) {
        divArea.style.display = 'none';
    }
   resetPopupFrame();
}


function closeMe() {
	try { 
	if (window.opener) { 
		self.close();
   }
		
	if(cWin != null){ cWin.close(); cWin = null; } }
	catch(e) {}
	try { if(childwin != null){ childwin.close(); childwin = null; } }
	catch(e) {}
}

// this will open a context-sensitive help window
function openNewHelpWin(url,e)
{
	w = screen.width-470;
	h = screen.height-370;
	x = e.screenX;
	y = e.screenY;
	if(x > w) { x = x-470; }
	if(y > h) { y = y-370; }
	childwin=window.open(url, "childwin", "width=470,height=370,top="+y+",left="+x+",scrollbars=yes,resizable=yes");
}
// this will open a pop-up help window
function openNewHelp2win(url,e,v)
{
	w = screen.width-470;
	h = screen.height-v;
	x = e.screenX;
	y = e.screenY;
	if(x > w) { x = x-470; }
	if(y > h) { y = y-v; }
	childwin=window.open(url, "childwin", "width=470,height="+v+",top="+y+",left="+x+",scrollbars=yes,resizable=yes");
}

function openDesc(title,desc,e)
{
	w = screen.width-470;
	h = screen.height-150;
	x = e.screenX;
	y = e.screenY;
	if(x >  w) { x = x-470; }
	if(y >  h) { y = y-150; }
	var dWin = window.open('','movieDesc', 'width=470,height=150,top='+y+',left='+x+',scrollbars=yes,resizable=yes');
	var head = '<html><head><title>Movies</title><link rel="stylesheet" type="text/css" href="/components/css/global.css" />\n<link rel="stylesheet" type="text/css" href="/components/css/forms.css" />\n<script type="text/javascript" src="/components/js/global.js"></script>'
	+'<script language="JavaScript">\nwindow.onLoad = window.focus();\n</script></head>';
	var banner = '<div id="popHeader">'
	+'<table cellspacing="0" cellpadding="0" border="0">'
	+'<tr>'
	+'<td class="left"><img src="http://delta.m7z.net/delta/delta/backgrounds/headers/popup_header_left.jpg" alt="Delta" title="Delta" /></td>'
	+'<td class="right"><a href="javascript:self.close();"><nobr>Close Window</nobr></a></td>'
	+'</tr>'
	+'</table>'
	+'</div>';
	dWin.document.open();
	dWin.document.write('');
	dWin.document.write(head+'<body>\n'+banner+'<div class="popContainer">\n<p><b>'+title+'</b><br>\n'+desc+'</p></div></body></html>');
	dWin.document.close();
}

function logAction(string)
{
	var trackingPixelSrc = "http://www.delta.com/tracking/htmltag.gif?Log=1";
	if(document.getElementById("trackingPixel")!=null) { document.getElementById("trackingPixel").src = trackingPixelSrc+string.replace("amp;","")+"&rand="+Math.round(Math.random()*100000000); }
}
function setActiveTab(triggerID,type)
{
	var tabsID = type+"Tabs";
	var tabContentClass = type+"TabsContent";
	var activeTab = triggerID.split("_")[0];
	var tabs = get(tabsID);
	var tabCollection = tabs.getElementsByTagName('li');
	var tempCollection = document.getElementsByTagName('div');
	var tabContentCollection = new Array();
	for(var i=0;i<tempCollection.length;i++) { if(tempCollection[i].className.toString().split(" ")[0]==tabContentClass){tabContentCollection.push(tempCollection[i]);}}
	for(var i=0;i<tabCollection.length;i++)
	{
		setClassName(tabCollection[i].id,"");
		if(tabCollection[i].id==triggerID) { setClassName(tabCollection[i].id,"active"); }
		setClassName(tabContentCollection[i].id,tabContentCollection[i].className.toString().split(" ")[0]+" inactive");
		if(tabCollection[i].id==triggerID) { setClassName(tabContentCollection[i].id,tabContentCollection[i].className.toString().split(" ")[0]+" active"); }
	}
	if(document.getElementById(triggerID.split("_")[0]+"_tracking")!=null) { logAction(document.getElementById(triggerID.split("_")[0]+"_tracking").innerHTML); }
	if((document.getElementById(triggerID.split("_")[0]+"_additional")!=null)&&(document.getElementById("additional")!=null)) { document.getElementById("additional").innerHTML = document.getElementById(triggerID.split("_")[0]+"_additional").innerHTML; }
	else if(document.getElementById("additional")!=null) { document.getElementById("additional").innerHTML = ""; }
	else { /*doNothing()*/ }
}
function openPhotoViewer(title,path,imageRoot,numItem,numTotal)
{
	var winPath = "/components/popups/photo_viewer.jsp";
	var query = "?title="+title.replace(" ","_")+"&path="+path+"&imageRoot="+imageRoot+"&numItem="+numItem+"&numTotal="+numTotal;
	openWin(winPath+query,"PhotoViewer",450,450,'no');
}
function openClose(id1,id2)
{
	if (document.getElementById(id1).style.display=="none") { setClassName(id2,"active"); show(id1); }
	else { setClassName(id2,"inactive"); hide(id1); }
}

// this opens window with customizable dimensions, chrome (controls), scroll bar and spawn location; used when content is whole page, not pop-up content
function openWinfull( url, name, width, height, xpos, ypos, chrome, scroll ) {
	var x, y, w, h, moveX=0, moveY=0, features="";
	chrome = chrome ? "yes" : "no";
	scroll = scroll ? "yes" : "no";
	features += "toolbar="+chrome+",location="+chrome+",status="+chrome+",menubar="+chrome;
	features += ",scrollbars="+scroll+",resizable="+scroll;
	if(width) features += ",width="+width;
	if(height) features += ",height="+height;
	if(xpos && window.screen) {
		w = window.screen.availWidth;
		width = parseInt(width);
		switch(xpos){
			case "left": x = 0; break;
			case "center": x = (w-width)/2; break;
			case "right": x = w-width; break;
			default: x = xpos;
		}
		features += ",screenX="+x+",left="+x;
		var moveX = x;
	}
	if(ypos && window.screen){
		h = window.screen.availHeight;
		height = parseInt(height);
		switch(ypos){
			case "top": y = 0; break;
			case "middle": y = (h-height)/2; break;
			case "bottom": y = h-height; break;
			default: y = ypos;
		}
		features += ",screenY="+y+",top="+y;
		var moveY = y;
	}
	var openWinReference = window.open(url,name,features);
	if(moveX || moveY){
		// position the window for browsers that don't recognize screenX, screenY
		openWinReference.moveTo(moveX,moveY);
	}
}
openFull = function(url,name){ openWinfull(url,name,"640","480","center","middle",false,"scroll"); }
openAll = function(url,name,width,height){ openWinfull(url,name,"640","480","center","middle","chrome","scroll"); }




var cWin = null;
var childwin = null;
var home_containers = new Array("primary_messaging","secondary_messaging","group_one","group_two_top","group_two_bottom");
var left_pos = 378;
var url_lang = window.location.toString().split(".")[0].split("//")[1];


function formatURL(url){
	var formattedURL = unescape(url);
	window.location = formattedURL;
}


function getDomainFromURL(url){
	var domain = null;
	if (url.length > 10 
		&& (url.substring(0,4) == 'http'))  {
		domain = url.substring(0, url.indexOf('/', 7));
}
return domain;
}
// Javascript Code for TeaLeaf Technology, Inc.
// Round Trip calculation function

function tltRoundTrip() {
//	var pos;
//	var GIF = "tlt_rt.gif";
//	var QueryString = "?TeaLeafRoundTrip=Yes&";
//	var PageTime = 0;
//	var d = new Date()
//	if (d.getTimezoneOffset) { QueryString += "TZ=" + -(d.getTimezoneOffset()/60) + "&"; }
//	PageTime = Math.round((new Date())/1000);
//	pos = document.cookie.indexOf("TLTSID=");
//	if (pos != -1) { QueryString += document.cookie.substring(pos,document.cookie.indexOf(";",pos)) + "&"; }
//	pos = document.cookie.indexOf("TLTUID=");
//	if (pos != -1) { QueryString += document.cookie.substring(pos,document.cookie.indexOf(";",pos)); }
//	QueryString += "&PageTime=" + PageTime
//	document.write("<img src=\"\/\/images.delta.com/delta/thirdparty/" + GIF + QueryString + "\" height=\"1\" width=\"1\" border=\"0\">");
//	return;
}
function SelectRadioButton(id){
	var tagRef = get(id);
	var radioList  = document[tagRef.form.name][tagRef.name];
	if(parseInt(radioList.length).toString() === 'NaN') {
		tagRef.checked = true;
	} else {
		for(var i = 0, j = radioList.length; i<j; i++) {
			radioList[i].checked = (radioList[i].value === tagRef.value);
		}
	}
}

function urlEncode(stringToEncode) {
	stringToEncode = stringToEncode.toString();  
	var encodedString = escape(stringToEncode);
	encodedString = encodedString.replace(/\+/g, "%2B").replace(/\//g, "%2F"); 
	return encodedString;
}

function doNWAInterstitial() {
	var qs = [];
	for(var i=0, j=arguments.length; i<j; i++) {
		var qsDefinition = arguments[i];
		if(typeof(qsDefinition) === 'object' && exists(qsDefinition.qsProp) && exists(qsDefinition.value) ) {
			qs[qs.length] = qsDefinition.qsProp + '=' + urlEncode(qsDefinition.value);
		}
	}
	openNewWin('/shared/components/interstitial/nwa/index.jsp' + (qs.length !== 0 ? '?' + qs.join('&') : ''), 'nwaWait', 750, 600, 'yes', 'yes');
	cWin.focus();
}

function buildGraph(){
var tableRows = get("milesGraph").getElementsByTagName("tr").length-1;
var tableHeight = (20 * tableRows) + 34;
get("milesGraph").style.height = tableHeight;
var offsetMiles = 0;
var offsetSegments = 0;
var welcomeContainerHeight = 10;
	if(isFromHome || isFromHome == null){
		welcomeContainerHeight = 70;
	}
	if(navigator.appName.indexOf("Microsoft") != -1){
		var ver = navigator.appVersion;
		var thestart = parseFloat(ver.indexOf("MSIE"))+1;
		var brow_ver = parseFloat(ver.substring(thestart+4,thestart+7));
			if(brow_ver == 6){
				if(milesHeight > 10){
					offsetMiles = 0;
				}
				else{
					offsetMiles = 4;
				}
				if(segmentsHeight > 10){
					offsetSegments = 0;
				}
				else{
					offsetSegments = 4;
				}
			}
			else{
				offsetMiles = 1;
				offsetSegments = 0;
			}
	}
	if(milesHeight > 0){
		get("milesBar").style.height = milesHeight+"px";
		get("milesBar").style.top = (tableHeight - milesHeight + welcomeContainerHeight - offsetMiles)+"px";
	}
	else{
		get("milesBar").style.display = "none";
	}
	if(segmentsHeight > 0){
		get("segmentsBar").style.height = segmentsHeight+"px";
		get("segmentsBar").style.top = (tableHeight - segmentsHeight + welcomeContainerHeight - offsetSegments)+"px";
	}
	else{
	get("segmentsBar").style.display = "none";
	}
}

/******* marketing Asian markets and change url ********/
var asiaMarkets = {
	country : "",
	dealsOffersId : "deals",
	dealsOffersIdAlt : "dealsOffers",
	isDealsOffersPage : false,
	asiaCountryCodes : ["jp","cn","hk","tw","kr","ph","sg","th","gu","mp","au","nz","vn","id","my"],
	asiaDealsOffersUrl : "/planning_reservations/deals_offers/fare_sales/asia_pacific/deals/index.jsp",
	getCountry : function() {
		var cntry = getLoc();
		for(i=0; i<CountryOptions.length; i++){
			if(cntry == CountryOptions[i].getProp("country_code")){
				this.country = CountryOptions[i].getProp("country_code");
			}
		}
	},
	isAsianCountry : function() {
		this.getCountry();
		for(i=0; i<this.asiaCountryCodes.length; i++) {
			if(this.country == this.asiaCountryCodes[i]) {
				if(get(this.dealsOffersIdAlt)){
					updateURL(this.dealsOffersIdAlt,this.asiaDealsOffersUrl);
				}
				return;
			}
		}
	},
	updateDealsPageLink : function() {
		updateURL(asiaMarkets.dealsOffersIdAlt,asiaMarkets.asiaDealsOffersUrl);
	}
}
function updateURL(id,newUrl) {
	try {
		get(id).href = newUrl;
	} catch(e){}
}

var dashboardUtil = {
	skyMilesInputId : null,
	pinInputId : null,
	lnameInputId : null,
	skyMilesRadioId : null,
	skyMilesInputRef : null,
	pinInputRef : null,
	lnameInputRef : null,
	skyMilesProgram : null,
	isSkyMilesLogin : true,
	skymilesLoginAction : null,
	deltaContainerId : null,
	loginFormId : null,
	skyMilesFormTarget : null,
	inErrorState : false,
	webapp : null,
	dashboardContainerId : "dashboard",
	offsetContainerId : "genLoginSpacer",
	minimumOffset : 30,
	unitOfMeasure : "px",
	isBadBrowser : isBadBrowser(),
	currentAction : null,
	zeroClientHeightOffsetHeight : 120,
	skymilesIEResetOpenHeight : 120,
	skymilesIEMinimumOffsetHeight : 30,
	status : null,
	smErr : false,
	pinErr : false,
	lnameErr : false,
	origUserName : "",
	capturedUserName : false,
	loginMethod : "",
	
	offset : function() {
		var dashboardElement = get(this.dashboardContainerId);
		var offsetElement = get(this.offsetContainerId);
		var computedHeight;
		if( exists(dashboardElement) && exists(offsetElement) ) {
			show(this.dashboardContainerId);
			show(this.offsetContainerId);
			var offsetCords = getElementXAndYPos(offsetElement);
			var dashboardCords = getElementXAndYPos(dashboardElement);
			if(dashboardCords.y <= 0) { dashboardCords.x = 10; dashboardCords.y = 70;}
			if( (dashboardCords.y + dashboardElement.clientHeight) <= offsetCords.y ) {
				if( dashboardElement.clientHeight == 0 ) { 
					/* houston we have a problem in ie6 */
					if(this.isBadBrowser) {
						if(getContextPath() == "myitinerary"){
							offsetElement.style.height = "20px";
						}
						else{
					   		this.zeroClientHeightOffsetHeight = this.skymilesIEResetOpenHeight;
					   		this.minimumOffset = this.skymilesIEMinimumOffsetHeight;
						}
					}
					if(this.currentAction == "expand") {
						offsetElement.style.height = this.zeroClientHeightOffsetHeight + this.unitOfMeasure;
					} else if (this.currentAction == "collapse") {
						offsetElement.style.height = this.minimumOffset + this.unitOfMeasure;
					} else {
						offsetElement.style.height = this.zeroClientHeightOffsetHeight + this.unitOfMeasure;
					}
				} else {
					offsetElement.style.height = this.minimumOffset + this.unitOfMeasure;
				}
			} else {
				if( getContextPath() == "home" || getContextPath() == "" || getContextPath() == "schedules") {
					computedHeight = ((dashboardCords.y + dashboardElement.clientHeight) - offsetCords.y) + this.unitOfMeasure;
				} else {
					computedHeight = ((dashboardCords.y + dashboardElement.clientHeight) - offsetCords.y + this.minimumOffset) + this.unitOfMeasure;
				}
				offsetElement.style.height = computedHeight;
			}
			show(this.dashboardContainerId);
		}
		try { show(this.dashboardContainerId); } catch(error) { /*for the new netscape 4: ie6 */ }
	},
	
	validateHomepageLogin : function(){
		this.clearHomepageErrors();
		var isError = false;
		var isValidSM = false;
		var isValidEM = false;
		var tmp = get("skyMilesNumber").value.replace(/\s+/g,'');
		if(tmp.length != 11){
			if(tmp.match(/^\d{9,12}/) != null){
				isValidSM = true;
				this.loginMethod = "sky miles number";
			}
		}
		if(tmp.match(/^[\w-]+(?:\.[\w-]+)*@([a-z0-9-]+\.)+[a-z]{2,4}$/i) != null){
			isValidEM = true;
			this.loginMethod = "email address";
		}
		if(!isValidSM && !isValidEM){
			isError = true;
			setClassName("skyMilesNumber","homepageError");
			setClassName("skyMilesNumber_label","homepageError");
		}
		if(get("pin").value.match(/^\d{4}/) == null){
			isError = true;
			setClassName("pin","homepageError");
			setClassName("pin_label","homepageError");
		}
		if(get("lastName").value.match(/^[a-zA-Z]{2,}/) == null){
			isError = true;
			setClassName("lastName","homepageError");
			setClassName("lastName_label","homepageError");
		}
		if(isError){
			show("login_errorMsg");
			return false;	
		}
	},
	
	clearHomepageErrors : function(){
		setClassName("skyMilesNumber","");
		setClassName("skyMilesNumber_label","");
		setClassName("pin","");
		setClassName("pin_label","");
		setClassName("lastName","");
		setClassName("lastName_label","");
		hide("login_errorMsg");		
	},
	
	validateDashboardLogin : function(){
		if(get("userFullName")){
			if(!this.capturedUserName){
				this.origUserName = get("userFullName").innerHTML;
				this.origUserName = this.origUserName.substring(0,this.origUserName.length-3);
				this.capturedUserName = true;
			}
		}
		this.clearDashboardErrors();
		var isError = false;
		var isValidSM = false;
		var isValidEM = false;
		var errorCount = 0;
		var tmp = get("skyMilesNumber").value.replace(/\s+/g,'');
		if(tmp.match(/^\d{10}/) != null){
			isValidSM = true;
			this.loginMethod = "sky miles number";
		}
		if(tmp.match(/^[\w-]+(?:\.[\w-]+)*@([a-z0-9-]+\.)+[a-z]{2,4}$/i) != null){
			isValidEM = true;
			this.loginMethod = "email address";
		}
		if(!isValidSM && !isValidEM){
			isError = true;
			errorCount++;
			setClassName("skyMilesNumber","error");
			show("skyMilesErrorArrow","inline");
		}
		if(get("dashpin").value.match(/^\d{4}/) == null){
			isError = true;
			errorCount++;
			setClassName("dashpin","error");
			setClassName("dashpinText","error");
			show("pinErrorArrow","inline");
		}
		if(get("lastName").value.match(/^[a-zA-Z]{2,}/) == null || get("lastName").value == "Last Name"){
			isError = true;
			errorCount++;
			setClassName("lastName","error");
			show("lnameErrorArrow","inline");
		}
		if(isError){
			get("dashboard_errorMsg").innerHTML = "Please correct your entries in the highlighted field(s).";
			show("dashboard_errorMsg");
			get("dashboard").style.height = "55px";
				if(get("userFullName") && this.origUserName.length > 11){
					var userName;
						switch(errorCount){
							case 1:
							userName = this.origUserName.substr(0,15);
							break;
							case 2:
							userName = this.origUserName.substr(0,13);
							break;
							case 3:
							userName = this.origUserName.substr(0,11);
							break;
							default:
							userName = this.origUserName;
						}
					get("userFullName").innerHTML = userName+"...";
				}
			return false;	
		}
	},	
	
	clearDashboardErrors : function(){
		setClassName("skyMilesNumber","");
		setClassName("dashpin","");
		setClassName("dashpinText","");
		setClassName("lastName","");
		get("dashboard").style.height = "35px";
		hide("dashboard_errorMsg");
		hide("skyMilesErrorArrow");
		hide("pinErrorArrow");
		hide("lnameErrorArrow");
	},
	
	swapPinFields : function(){
		hide("dashpinText");
		show("dashpin","inline");
		get("dashpin").focus();
	},
	
	goToPin : function(){
		var pinField = "dashpinText";
			if(get(pinField).style.display == "none"){
				pinField = "dashpin";
			}
		get(pinField).focus();
	},
	
	clearContent : function(fld){
		if(get(fld).value == "SkyMiles# or Email" || get(fld).value == "Last Name"){
			get(fld).value = "";
		}
		get(fld).focus();
	}

};
var DeltaOverlayUtil = {
	followPopupClass : "screenPopup_follow",
	followIframClass : "popupFrame_follow",
	noFollowPopupClass : "screenPopup_noFollow",
	noFollowIframClass : "popupFrame_noFollow",
	popupId : "popupDiv",
	iFrameId : "popupFrame",
	iFrameName : "popupFrame",
	overlayBgId : "modalOverlayBgDiv",
	pathToBlank : "java" + "script:'<html></html>';",
	idMapping : { headerContent : "defaultPopHeaderTitle", headerClose : "defaultPopheaderClose"},
	isIe : function() { return ( !exists(window.opera) && exists(window.ActiveXObject) && exists(document.all) ) ? true : false;},
	isBadBrowser : isBadBrowser(),
	isUsingOverlay : false,
	setIframeSrc : function(src) {
		var windowRef = window.parent != window ? window.parent : window;
		windowRef.get(DeltaOverlayUtil.iFrameId).src = src;
	},
	setClassNames : function(modalDiv, popupHeight, popupWidth, pageHeight, pageWidth) {
//		if(DeltaOverlayUtil.isIe() || (popupHeight > pageHeight) || (popupWidth > pageWidth)) {
			setClassName(modalDiv.id, DeltaOverlayUtil.noFollowPopupClass);
//			setClassName(DeltaOverlayUtil.iFrameId, DeltaOverlayUtil.noFollowIframClass);
//		} else {
//			modalDiv.className = DeltaOverlayUtil.followPopupClass;
//			setClassName(modalDiv.id, DeltaOverlayUtil.followPopupClass);
//			setClassName(DeltaOverlayUtil.iFrameId, DeltaOverlayUtil.followIframClass);
//		}
	},
	showPopupOverlay : function(url, name, width, height, scroll, Overrides) {
		try {
			var modalDiv = get(DeltaOverlayUtil.popupId);
			var overlayBgDiv = get(DeltaOverlayUtil.overlayBgId);
			var overlayIframe = get(DeltaOverlayUtil.iFrameId);
			if( exists(modalDiv) && exists(overlayBgDiv) && exists(overlayIframe) ) {
				if (arguments[5] && typeof(arguments[5] === "object")) {
					if (exists(Overrides.headerReplaceContent)) {
						setInnerHTML(this.idMapping.headerContent, Overrides.headerReplaceContent);
					}
					if (exists(Overrides.linkCloseContent)) {
						setInnerHTML(this.idMapping.headerClose, Overrides.linkCloseContent);
					}
					if (typeof(Overrides.linkCloseAction) === "function") {
						this.hideOverlay = Overrides.linkCloseAction;
					}
				}
				var pageSize = DeltaOverlayUtil.getPageSize();
				overlayBgDiv.style.height = pageSize.pageHeight + 'px';
				overlayBgDiv.style.width = pageSize.pageWidth + 'px';
				var modalDivStyle = modalDiv.style;
				modalDivStyle.height = height + 50 + 'px';
				modalDivStyle.width = width + 'px';
				DeltaOverlayUtil.centerElement(pageSize, modalDiv, height, width);
				var iFramStyle = overlayIframe.style;
				overlayIframe.width = (width - 10) + 'px';
				overlayIframe.height = height + 'px';
				DeltaOverlayUtil.setIframeSrc(url);
				DeltaOverlayUtil.setClassNames(modalDiv, height, width, pageSize.pageHeight, pageSize.pageWidth);
				show(DeltaOverlayUtil.popupId);
				show(DeltaOverlayUtil.overlayBgId);
				show(DeltaOverlayUtil.iFrameId);
				DeltaOverlayUtil.isUsingOverlay = true;
			} else {
				openNewWin(url, name, width, height, scroll);
				DeltaOverlayUtil.isUsingOverlay = false;
			}
		} catch(generalError) {
			openNewWin(url, name, width, height, scroll);
			DeltaOverlayUtil.isUsingOverlay = false;
		}
	},
	hideOverlay : function(id) {
		try {
			var windowRef = window.parent != window ? window.parent : window;
			windowRef.hide(DeltaOverlayUtil.popupId);
			windowRef.hide(DeltaOverlayUtil.overlayBgId);
			windowRef.hide(DeltaOverlayUtil.iFrameId);
			DeltaOverlayUtil.setIframeSrc(DeltaOverlayUtil.pathToBlank);
		} catch(noOverlayError) {
			try {
				cWin.close(); 
				cWin = null;
			} catch(noWindowError) {}
		}
	},
	getPageSize : function() {
		var pageSize = { xScroll: 0, yScroll : 0, pageWidth : 0, pageHeight : 0, windowWidth : 0, windowHeight: 0 };
		var docBody = document.body;
		var docElem = document.documentElement;
		if (window.innerHeight && window.scrollMaxY) {	
			pageSize.xScroll = docBody.scrollWidth;
			pageSize.yScroll = window.innerHeight + window.scrollMaxY;
		} else if (docBody.scrollHeight > docBody.offsetHeight){
			pageSize.xScroll = docBody.scrollWidth;
			pageSize.yScroll = docBody.scrollHeight;
		} else {
			pageSize.xScroll = docBody.offsetWidth;
			pageSize.yScroll = docBody.offsetHeight;
		}
		if (self.innerHeight) {
			pageSize.windowWidth = self.innerWidth;
			pageSize.windowHeight = self.innerHeight;
		} else if (docElem && docElem.clientHeight) {
			pageSize.windowWidth = docElem.clientWidth;
			pageSize.windowHeight = docElem.clientHeight;
		} else if (docBody) {
			pageSize.windowWidth = docBody.clientWidth;
			pageSize.windowHeight = docBody.clientHeight;
		}
		pageSize.pageHeight = pageSize.yScroll < pageSize.windowHeight ? pageSize.windowHeight : pageSize.yScroll;
		pageSize.pageWidth = pageSize.xScroll < pageSize.windowWidth ? pageSize.windowWidth : pageSize.xScroll;
		if (self.pageYOffset) {
			pageSize.yScroll = self.pageYOffset;
		} else if (docElem && docElem.scrollTop){
			pageSize.yScroll = docElem.scrollTop;
		} else if (docBody) {
			pageSize.yScroll = docBody.scrollTop;
		}
		if (self.pageXOffset) {
			pageSize.xScroll = self.pageXOffset;
		} else if (docElem && docElem.scrollLeft){
			pageSize.xScroll = docElem.scrollLeft;
		} else if (docBody) {
			pageSize.xScroll	= docBody.scrollLeft;
		}
		return pageSize;
	},
	centerElement : function(pageSize, objToCenter, height, width) {
		if(typeof pageSize != "object") {
			pageSize = DeltaOverlayUtil.getPageSize();
		}
		var objStyle = objToCenter.style;
		var prevVisible = objStyle.visibility;
		var preDisplay = objStyle.display;	
		objStyle.display = "none";
		objStyle.visibility = "hidden";
		objStyle.display = "block";
		var objTop = pageSize.yScroll + (( pageSize.windowHeight - 35 - objToCenter.offsetHeight) / 2);
		var objLeft = (pageSize.windowWidth - objToCenter.offsetWidth) / 2;
		objStyle.top = (objTop < 0) ? "0px" : objTop + "px";
		objStyle.left = (objLeft < 0) ? "0px" : objLeft + "px";
		objStyle.display = preDisplay;
		objStyle.visibility = "visible";
	}
};

/* these are for OA flights when certs are selected */
function removeCertificates() {
	DeltaOverlayUtil.showPopupOverlay('/shared/components/modal_overlay/remove_certificates.jsp', 'remove_certs', 600, 190, 'yes');
}
function continueWithoutCertificates() {
	hide('comp_cert_icon');
	hide('comp_cert');
	hide('certs_not_applied');
	hide('document_total');
	
	DeltaOverlayUtil.hideOverlay();
}
function iFrameUtility() {
	this.name = null;
	this.id = null;
	this.tagReference = null;
	this.documentBody = null;
	this.tagReferenceForForms = null;
	this.tagReferenceForJS = null;
	this.useContentDocument = null;
	this.timeoutId = null;
	this.isInitialized = false;
	this.isParentToChild = true;
	this.parentReference = window;
	this.iframePadding = 20;
	this.childObjectToSet = null;
}
iFrameUtility.prototype.init = function(Definition) {
	this.name = Definition.name;
	this.id = Definition.id;
	this.isParentToChild = Definition.isParentToChild;
	this.parentReference = window.opener != null ? window.opener : window.parent != null ? window.parent :  window.top != null ? window.top : window;
	this.setTagReferences(Definition.id);
	this.childObjectToSet = Definition.childObjectToSet;
	this.timeoutId = Definition.timeoutId;
};
iFrameUtility.prototype.setTagReferences = function(Reference) {
	if (Reference !== this.tagReference) {
		if (this.isParentToChild) {
			this.tagReference = typeof(Reference) === "object" ? Reference : get(Reference);
		} else {
			this.tagReference = typeof(Reference) === "object" ? Reference : this.parentReference.get(Reference);
		}
	}
	if (exists(this.tagReference)) {
		try {
			this.useContentDocument = exists(this.tagReference.contentDocument);
			this.documentBody = !this.useContentDocument ? this.tagReference.Document.body : this.tagReference.contentDocument.body;
			this.tagReferenceForForms = !this.useContentDocument ? window.frames[this.tagReference.name] : this.tagReference.contentDocument;
			this.tagReferenceForJS = window.frames[this.tagReference.name];
			this.isInitialized = true;
		} catch(accessDeniedError) { /* YOU ARE TRYING TO GO HTTP PARENT TO HTTPS IFRAME, NOT ALLOWED */}
	}
};
iFrameUtility.prototype.clearTimeoutEvent = function() {
	if (exists(this.timeoutId)) {
		window.clearTimeout(this.timeoutId);
		this.timeoutId = null;
	}
};
iFrameUtility.prototype.setSrc = function(src) {
	if (this.isInitialized) {
		this.tagReference.src = src;
	}
};
iFrameUtility.prototype.setWidth = function(width) {
	if (this.isInitialized) {
		this.tagReference.width = width;
	}
};
iFrameUtility.prototype.setHeight = function(height) {
	if (this.isInitialized) {
		this.tagReference.height = height;
	}
};
iFrameUtility.prototype.resize = function(width, height) {
	this.setWidth(height);
	this.setHeight(height);
};
iFrameUtility.prototype.getFullHeight = function() {
	if (this.isInitialized) {
		if (this.isParentToChild) {
			return this.iframePadding + (!this.useContentDocument ? this.documentBody.scrollHeight : this.documentBody.offsetHeight);
		} else {
			return DeltaOverlayUtil.getPageSize().pageHeight;
		}
	}
};
iFrameUtility.prototype.fullySize = function(heightOffset) {
	if (this.isInitialized) {
		this.setWidth("100%");
		this.setHeight(this.getFullHeight() + (arguments[0] ? arguments[0]  : 0));
		this.clearTimeoutEvent();
	}
};
iFrameUtility.prototype.fullySizeByReference = function(iFrameReference, heightOffset) {
	this.setTagReferences(iFrameReference);
	this.fullySize(heightOffset);
	this.clearTimeoutEvent();
	if (exists(this.childObjectToSet)) { this.setJavascriptValue(this.childObjectToSet, this); }
};
iFrameUtility.prototype.runJavascriptFunction = function(functionName, parameters) {
	if (this.isInitialized) {
		if (this.isParentToChild) {
			eval('window.frames["' + this.tagReference.name + '"].' + functionName + '(' + parameters + ');');
		} else {
			eval('this.parentReference.' + functionName + '(' + parameters + ');');
		}
	}
};
iFrameUtility.prototype.setJavascriptValue = function(variableName, value) {
	if (this.isInitialized) {
		if (this.isParentToChild) {
			this.tagReferenceForJS[variableName] = value;
		} else {
			this.parentReference[variableName] = value;
		}
	}
};
iFrameUtility.prototype.getJavascriptValue = function(variableName) {
	if (this.isInitialized) {
		if (this.isParentToChild) {
			return this.tagReferenceForJS[variableName];
		} else {
			return this.parentReference[variableName];
		}
	}
	return null;
};
iFrameUtility.prototype.getFormReference = function(formId, formName) {
	if (this.isParentToChild) {
		return !this.useContentDocument ? this.tagReferenceForForms[formName] : this.tagReferenceForForms.getElementById(formId);
	} else {
		return this.parentReference.document.getElementById(formId);
	}
};
iFrameUtility.prototype.getFieldReference = function(formId, formName, fieldName) {
	var formReference = this.getFormReference(formId, formName);
	if (exists(formReference)) {
		return formReference[fieldName];
	}
	return null;
};
iFrameUtility.prototype.setFormValue = function(formId, formName, fieldName, value) {
	if (this.isInitialized) {
		var fieldReference = this.getFieldReference(formId, formName, fieldName);
		if (exists(fieldReference) && fieldReference.length > 0) {
			var fieldType = fieldReference[0].type;
			switch(fieldType) {
				case "text":
				case "textarea":
				case "hidden":
					fieldReference[0].value = value;
					break;
				case "checkbox":
					fieldReference[0].checked = true;
					break;
				case "select-one": 
					for (var i=0, j=fieldReference.length; i<j; i++) {
						if (fieldReference[i].value == value) { fieldReference.selectedIndex = i; } 
					}
					break;
				case "radio":
					for (var i=0, j=fieldReference.length; i<j; i++) {
						if (fieldReference[i].value == value) { fieldReference[i].checked = true; } 
					}
					break;
			}
		}
	}
};
iFrameUtility.prototype.getFormValue = function(formId, formName, fieldName) {
	if (this.isInitialized) {
		var fieldReference = this.getFieldReference(formId, formName, fieldName);
		if (exists(fieldReference) && fieldReference.length > 0) {
			var fieldType = fieldReference[0].type;
			switch(fieldType) {
				case "text":
				case "textarea":
				case "hidden":
					return fieldReference[0].value;
				case "checkbox":
					return fieldReference[0].checked ? fieldReference.value : null;
				case "select-one": 
					return fieldReference[0].options[fieldReference[0].selectedIndex].value;
				case "radio":
					for (var i=0, j=fieldReference.length; i<j; i++) {
						if (fieldReference[i].checked) { return fieldReference[i].value; } 
					}
					return null;
			}
		}
	}
	return null;
};
iFrameUtility.prototype.submitForm = function(formName, formId) {
	if (this.isInitialized) {
		var formReference = this.getFormReference(formId, formName);
		if (exists(formReference)) {
			formReference.submit();
		}
	}
};
iFrameUtility.prototype.removeIframe = function() {
	if (this.isInitialized) {
		this.tagReference.parentNode.removeChild(this.tagReference);
	}
}

function killFrameInclude() {
	if (top != self) { 
		top.location=self.location;
	}
}
//customerprofile/dwr/interface/FlightPreferenceProcessor.js
if(dwr==null)var dwr={};if(dwr.engine==null)dwr.engine={};if(DWREngine==null)var DWREngine=dwr.engine;if(FlightPreferenceProcessor==null)var FlightPreferenceProcessor={};FlightPreferenceProcessor._path='/customerprofile/dwr';FlightPreferenceProcessor.getFlightPreferences=function(callback){dwr.engine._execute(FlightPreferenceProcessor._path,'FlightPreferenceProcessor','getFlightPreferences',false,callback);}

var PreferredTrips = {
	trips : null,
	recentSearches : null,
	hasDefaultTrip : false,
	defaultTripIndex : "",
	isLoggedIn : false,
	preferredTripsSelectId : "preferenceItinId",
	cookieName : "recentSearches",
	cookieLife : 30,
	maxRecentSearches : 4,

	FormFields : {
		OOO : "departureCity_0",
		DDD : "destinationCity_0",
		DDATE : "departureDate_0",
		RDATE : "departureDate_1",
		DTIME : "departureTimeOptions_0",
		RTIME : "departureTimeOptions_1",
		mcOOO : "mc_departureCity_0",
		mcDDD : "mc_destinationCity_0",
		mcDDATE : "mc_departureDate_0",
		mcRDATE : "mc_departureDate_1",
		mcDTIME : "mc_departureTimeOptions_0",
		mcRTIME : "mc_departureTimeOptions_1",

		PAXCOUNT : "passengers",
		CLASS: "cabinChoice_booking",
		REFUNDABLE: "searchRefundableFlights" // awards actually doesn't have this option
	},
	timePeriodMappings : {
		Revenue : [
			{ timePeriod : "anytime", formValue : "AT"},
			{ timePeriod : "morning", formValue : "AM"},
			{ timePeriod : "noon", formValue : "MD"},
			{ timePeriod : "afternoon", formValue : "PM"},
			{ timePeriod : "evening", formValue : "PT"}
		],
		Awards : [
			{ timePeriod : "anytime", formValue : "12M"},
			{ timePeriod : "morning", formValue : "MON"},
			{ timePeriod : "noon", formValue : "MDY"},
			{ timePeriod : "afternoon", formValue : "DAY"},
			{ timePeriod : "evening", formValue : "NGT"}
		]
	},
	timeMappings : {
		Revenue : [
			{dwrValue : "0100", formValue : "01A", timePeriod : "morning"},
			{dwrValue : "0200", formValue : "02A", timePeriod : "morning"},
			{dwrValue : "0300", formValue : "03A", timePeriod : "morning"},
			{dwrValue : "0400", formValue : "04A", timePeriod : "morning"},
			{dwrValue : "0500", formValue : "05A", timePeriod : "morning"},
			{dwrValue : "0600", formValue : "06A", timePeriod : "morning"},
			{dwrValue : "0700", formValue : "07A", timePeriod : "morning"},
			{dwrValue : "0800", formValue : "08A", timePeriod : "morning"},
			{dwrValue : "0900", formValue : "09A", timePeriod : "morning"},
			{dwrValue : "1000", formValue : "10A", timePeriod : "noon"},
			{dwrValue : "1100", formValue : "11A", timePeriod : "noon"},
			{dwrValue : "1200", formValue : "12N", timePeriod : "noon"},
			{dwrValue : "1300", formValue : "01P", timePeriod : "noon"},
			{dwrValue : "1400", formValue : "02P", timePeriod : "noon"},
			{dwrValue : "1500", formValue : "03P", timePeriod : "afternoon"},
			{dwrValue : "1600", formValue : "04P", timePeriod : "afternoon"},
			{dwrValue : "1700", formValue : "05P", timePeriod : "afternoon"},
			{dwrValue : "1800", formValue : "06P", timePeriod : "afternoon"},
			{dwrValue : "1900", formValue : "07P", timePeriod : "evening"},
			{dwrValue : "2000", formValue : "08P", timePeriod : "evening"},
			{dwrValue : "2100", formValue : "09P", timePeriod : "evening"},
			{dwrValue : "2200", formValue : "10P", timePeriod : "evening"},
			{dwrValue : "2300", formValue : "11P", timePeriod : "evening"},
			{dwrValue : "2400", formValue : "12M", timePeriod : "evening"}
		],
		Awards : [
			{dwrValue : "0100", formValue : "MON", timePeriod : "morning"},
			{dwrValue : "0200", formValue : "MON", timePeriod : "morning"},
			{dwrValue : "0300", formValue : "MON", timePeriod : "morning"},
			{dwrValue : "0400", formValue : "MON", timePeriod : "morning"},
			{dwrValue : "0500", formValue : "MON", timePeriod : "morning"},
			{dwrValue : "0600", formValue : "MON", timePeriod : "morning"},
			{dwrValue : "0700", formValue : "MON", timePeriod : "morning"},
			{dwrValue : "0800", formValue : "MON", timePeriod : "morning"},
			{dwrValue : "0900", formValue : "MON", timePeriod : "morning"},
			{dwrValue : "1000", formValue : "MDY", timePeriod : "noon"},
			{dwrValue : "1100", formValue : "MDY", timePeriod : "noon"},
			{dwrValue : "1200", formValue : "MDY", timePeriod : "noon"},
			{dwrValue : "1300", formValue : "MDY", timePeriod : "noon"},
			{dwrValue : "1400", formValue : "MDY", timePeriod : "noon"},
			{dwrValue : "1500", formValue : "DAY", timePeriod : "afternoon"},
			{dwrValue : "1600", formValue : "DAY", timePeriod : "afternoon"},
			{dwrValue : "1700", formValue : "DAY", timePeriod : "afternoon"},
			{dwrValue : "1800", formValue : "DAY", timePeriod : "afternoon"},
			{dwrValue : "1900", formValue : "NGT", timePeriod : "evening"},
			{dwrValue : "2000", formValue : "NGT", timePeriod : "evening"},
			{dwrValue : "2100", formValue : "NGT", timePeriod : "evening"},
			{dwrValue : "2200", formValue : "NGT", timePeriod : "evening"},
			{dwrValue : "2300", formValue : "NGT", timePeriod : "evening"},
			{dwrValue : "2400", formValue : "NGT", timePeriod : "evening"}
		]
	},
	getCabinCode : function(trip) {
		var cabinCode = trip.cabinClass;
		if(trip.refundableIndicator == null || trip.refundableIndicator == "null") { 
			cabinCode += "N"; 
		} else {
			cabinCode += trip.refundableIndicator;
		}
		return cabinCode;
	},
	clearFields : function() {
		get(PreferredTrips.FormFields.OOO).value = "";
		get(PreferredTrips.FormFields.DDD).value = "";
		get(PreferredTrips.FormFields.DTIME).selectedIndex = 0;
		get(PreferredTrips.FormFields.RTIME).selectedIndex = 0;
		get(PreferredTrips.FormFields.PAXCOUNT).selectedIndex = 0;
		get(PreferredTrips.FormFields.CLASS).selectedIndex = 0;
		try{
			get(PreferredTrips.FormFields.REFUNDABLE).checked = false;
		}catch(error) { /* /ignore */ }
	},
	setTime : function(fieldId,storedValue){
		/*
		var selectInput = get(fieldId);
		var formValue;
		var timePeriod;
		var timePeriodValue;
		for( var i=0;i<PreferredTrips.timeMappings.length;i++){
			if(storedValue == PreferredTrips.timeMappings[i].dwrValue){
				formValue = PreferredTrips.timeMappings[i].formValue;
				timePeriod = PreferredTrips.timeMappings[i].timePeriod;
				for(var j=0; j < PreferredTrips.timePeriodMappings.length; j++) {
					if(PreferredTrips.timePeriodMappings[j].timePeriod == timePeriod) {
						timePeriodValue = PreferredTrips.timePeriodMappings[j].formValue;
						break;
					}
				}
				for (var k=0; k<selectInput.length; k++){
					if(selectInput[k].value == formValue || selectInput[k].value == timePeriod || selectInput[k].value == timePeriodValue) {
						selectInput[j].selected = true;
						return;
					}
				}
			}
		}
		*/
	},
	isRefundable : function (cabinCode){
		if(cabinCode.match(/1R|2R|3R|4R|5R|GR|HR|IR|XR|YR|ZR/)) {	
			return true;
		}
		return false;
	},
	setCabin : function(cabinCode, form) {
		var cabin;
		var value;
		var selectInput;
		if(cabinCode.length >1 ) {
			if(cabinCode.match(/CN|CR|UR|UN|8R|8N/)) {
				cabin = "Coach";
				value = "B5-Coach"
			}
		} else {
			value = cabinCode;
			if(cabinCode.match(/[ULKQHMBY]/)) {
				cabin = "Coach";
			} else if (cabinCode.match(/[ISDACJF]/)) {
				cabin = "First/Business"
			} else {}
		}
		selectInput = get(PreferredTrips.FormFields.CLASS);
		if(selectInput.length == 2) {
			for(var i=0; i< selectInput.length; i++) {
				if(selectInput[i].text == cabin) {
					selectInput[i].selectedIndex = i;
				}
			}
		}
	},
	changePreferredTrip : function(source) {
		var tripSelected = source.options[source.selectedIndex].value;
		var optionOffset = 0;
		try{
		if(this.recentSearches.length != null){
			var optionOffset = 	this.recentSearches.length;
		}

		if(tripSelected.match(/recent_/)){
			if(source.selectedIndex == 0){
				PreferredTrips.clearFields();
			}
			
			var trip = this.recentSearches[source.selectedIndex-1];
			get(PreferredTrips.FormFields.OOO).value = trip.origin;
			get(PreferredTrips.FormFields.DDD).value = trip.destination;
			get(PreferredTrips.FormFields.DDATE).value = trip.leaveDate;
			get(PreferredTrips.FormFields.RDATE).value = trip.returnDate;
			PreferredTrips.setTime(PreferredTrips.FormFields.DTIME,trip.departureTime);
			PreferredTrips.setTime(PreferredTrips.FormFields.RTIME,trip.returnTime);
			
			// add for multicity copy
			try{
			get(PreferredTrips.FormFields.mcOOO).value = trip.origin;
			get(PreferredTrips.FormFields.mcDDD).value = trip.destination;
			}catch(error){}

			get(PreferredTrips.FormFields.mcDDATE).value = trip.leaveDate;
			get(PreferredTrips.FormFields.mcRDATE).value = trip.returnDate;
			PreferredTrips.setTime(PreferredTrips.FormFields.mcDTIME,trip.departureTime);
			PreferredTrips.setTime(PreferredTrips.FormFields.mcRTIME,trip.returnTime);

		}
		
		} catch (error){}
		if(tripSelected.match(/preferred_/)){
		if(source.selectedIndex == 0){
			PreferredTrips.clearFields();
		} else {
				var trip = PreferredTrips.trips[source.selectedIndex-optionOffset-1];
			get(PreferredTrips.FormFields.OOO).value = trip.origin;
			get(PreferredTrips.FormFields.DDD).value = trip.destination;
			PreferredTrips.setTime(PreferredTrips.FormFields.DTIME,trip.departureTime);
			PreferredTrips.setTime(PreferredTrips.FormFields.RTIME,trip.returnTime);
				// start add for multicity copy
				try{
				get(PreferredTrips.FormFields.mcOOO).value = trip.origin;
				get(PreferredTrips.FormFields.mcDDD).value = trip.destination;
				}catch(error){}
				// end add for multicity copy
			get(PreferredTrips.FormFields.PAXCOUNT).selectedIndex = trip.numOfPassengers-1;
			PreferredTrips.setCabin(PreferredTrips.getCabinCode(trip));
			try{
				if(PreferredTrips.isRefundable(PreferredTrips.getCabinCode(trip))) {
					get(PreferredTrips.FormFields.REFUNDABLE).checked = true;
				} else {
					get(PreferredTrips.FormFields.REFUNDABLE).checked = false;
				}
				
			}catch(error) { /* /ignore */ }
		}
		
		}
	},
	createOptionSet : function(type) {
		var option;

		var optgroup;
		var testgroup;
		var trip;
		var oSelect = get(PreferredTrips.preferredTripsSelectId);
		
		if(type == "preferred") {
			optgroup = document.createElement("optgroup");
			optgroup.label = "\u2014 Saved Searches \u2014";
			trips = this.trips;
		} else if (type == "recent") {
			optgroup = document.createElement("optgroup");
			optgroup.label = "\u2014 Recent Searches \u2014";

			trips = this.recentSearches;
		}
		oSelect.appendChild(optgroup);
		for(var i=0;i<trips.length;i++){
			option = document.createElement("option");
			option.text = trips[i].itinAlias;
			option.value = (type=="preferred") ? "preferred_" + i : "recent_" + i;
				oSelect.options.add(option);
			}

	},
	createOptions : function() {
	try{
		var option;
		oSelect = get(PreferredTrips.preferredTripsSelectId);
			option = document.createElement("option");
		option.text = "";
		if(this.recentSearches.length > 0) {
			if(this.isLoggedIn) {
					if(this.trips.length > 0){
						option.text = "Recent/Saved Searches";
					}
					else{
						option.text = "Recent Searches";
					}
				option.value = "blank";
			oSelect.options.add(option);

				}
			else{
				option.text = "Recent Searches";
				option.value = "blank";
				oSelect.options.add(option);
			}
			this.createOptionSet("recent");	
			show("PreferredTrips");

		}
	} catch (error){}
		if (this.trips.length > 0){
			if(option.text == ""){
				if(this.recentSearches){
					option.text = "Recent/Saved Searches";
				}
				else{
					option.text = "Saved Searches";
				}
			option.value = "blank";
			oSelect.options.add(option);
		}
			this.createOptionSet("preferred");
			show("PreferredTrips");
			elementShow("PreferredTrips");
			
		}
		if(PreferredTrips.hasDefaultTrip) {
			oSelect.selectedIndex = this.defaultTripIndex;
			if(get(PreferredTrips.FormFields.OOO).value == "") {
				PreferredTrips.changePreferredTrip(get(PreferredTrips.preferredTripsSelectId));
			}
		}
	},
	init : function(Definition) {
		var recentSearches;
		var recentSearchItins = [];
		var recentSearchItin = {};
		var recentSearchArray;
		this.trips = Definition;
		if(RecentSearches.hasRecentSearches){
			elementShow("PreferredTrips");
			// format returned is: fromAirport + ":" + toAirport + ":" + leaveDate + ":" + returnDate;
			recentSearches = RecentSearches.getRecentSearches();
			for(var i=0; i<recentSearches.length; i++){
				recentSearchArray = recentSearches[i].toString().split(":");
				recentSearchItin = {
					"itinAlias" : recentSearchArray[0] + " to " + recentSearchArray[1] + " [" + recentSearchArray[6] + "]",
					"origin" : recentSearchArray[0],
					"destination" : recentSearchArray[1],
					"leaveDate" : recentSearchArray[2],
					"returnDate" : recentSearchArray[3],
					"departureTime" : recentSearchArray[4],
					"returnTime" : recentSearchArray[5],
					"abbrLeaveDate" : recentSearchArray[6],
					"abbrReturnDate" : recentSearchArray[7]
				};

				recentSearchItins.push(recentSearchItin);
				
			}
			this.recentSearches = recentSearchItins;
			var trip = PreferredTrips.recentSearches[0];
			get(PreferredTrips.FormFields.OOO).value = trip.origin;


		}
		// isLoggedIn defined in page
		try {
		if(isLoggedIn) {this.isLoggedIn = true; }
		} catch(e) { }
		PreferredTrips.createOptions();
	}
}

function createPrefItinsObj(data) {
	var prefItins = [];
	var prefItin = {};
	if (data != null) {
		for(var i=0;  i<data.flightPreferences.length;  i++) {
			prefItin = {
				"itinAlias" : data.flightPreferences[i].itinAlias,
				"origin" : data.flightPreferences[i].origin,
				"destination" : data.flightPreferences[i].destination,
				"departureTime" : data.flightPreferences[i].departureTime,
				"returnTime" : data.flightPreferences[i].returnTime,				
				"defaultItinInd" : data.flightPreferences[i].defaultItinInd,
				"itinPreferenceId" : data.flightPreferences[i].itinPreferenceId,
				"numOfPassengers" : data.flightPreferences[i].numOfPassengers,
				"cabinClass" : data.flightPreferences[i].cabinClass,
				"refundableIndicator" : data.flightPreferences[i].refundableIndicator
			};
			prefItins.push(prefItin);
		}
		PreferredTrips.init(prefItins);
	} else { 
		PreferredTrips.init(prefItins);
	}

}
function getPreferredTrips() {
	try {
		if (!isLoggedIn) {
			createPrefItinsObj(null);
		} else {
		FlightPreferenceProcessor.getFlightPreferences({callback:createPrefItinsObj, errorHandler:handlePrefItinsError, timeout:6000});
		}
	} catch(e){}
}

function handlePrefItinsError() {
}

function changePreferredTrip(source) {
	PreferredTrips.changePreferredTrip(source);
}

//delta/shared_content/edgecache/js/core/RecentSearches.js
var RecentSearches = {
	searchFields : [],
	recentSearchesArray : [],
	hasRecentSearches : false,
	isDebugEnabled : true,
	cookieName : "recentSearches",
	preferredTripsSelectId : "preferenceItinId",
	cookieLife : 30,
	maxRecentSearches : 4,
	fromAirport:"",
	toAirport:"",
	leaveDate:"",
	returnDate:"",
	logMessage : function(message) {
		if(this.isDebugEnabled){
			try {
				console.log(message);
			} catch (error){
				// silently ignored
			}
		}
	},
	createRecentSearchesCookie : function() {
		var value = this.recentSearchesArray.join("~");
		createCookie(this.cookieName, value, this.cookieLife);
	},
	getRecentSearches : function(){
		return this.recentSearchesArray;
	},
	formatData : function(fromAirport, toAirport, leaveDate, returnDate, departureTime,returnTime, abbrLeaveDate, abbrReturnDate){
		var returnString = fromAirport + ":" + toAirport + ":" + leaveDate + ":" + returnDate + ":" + departureTime + ":" + returnTime + ":" + abbrLeaveDate + ":" + abbrReturnDate ;
		return returnString;
		
	},
	getRecentSearchCookie : function(){
		var tempCookie;
		var cookieValue;
		if(getCookie(this.cookieName) != null){
			tempCookie = getCookie(this.cookieName);
			cookieValue = tempCookie.substring(0, tempCookie.length-1);
			this.recentSearchesArray = cookieValue.split("~");
			//alert('this.recentSearchesArray ' + this.recentSearchesArray);
			this.hasRecentSearches = true;
		}
	},
	getCurrentSearch : function(){
		var fromAirport = RecentSearches.fromAirport.toUpperCase();
		var toAirport = RecentSearches.toAirport.toUpperCase();
		var leaveDate = RecentSearches.leaveDate;
		var returnDate = RecentSearches.returnDate;
		var departureTime = "";
		var returnTime = "";
		var tempLeaveDate = leaveDate;
		var tempReturnDate = returnDate;
		var abbrLeaveDate = dateFormat(tempLeaveDate, "ddd Ad mmm");
		var abbrReturnDate = dateFormat(tempReturnDate, "ddd Ad mmm");
			this.recentSearchesArray.unshift(this.formatData(fromAirport, toAirport, leaveDate, returnDate, departureTime, returnTime, abbrLeaveDate, abbrReturnDate));
	},
	setRecentSearchCookie : function() {
		var tempCookie;
		var cookieValue;
		var numRecentSearches;
		var recentSearchesArray;
		deleteCookie(this.cookieName, "/");
		if(this.recentSearchesArray.length > this.maxRecentSearches) {
			var numToRemove = this.recentSearchesArray.length - this.maxRecentSearches;
			for(var i=0; i<numToRemove; i++){
				this.recentSearchesArray.pop();
			}
		}
		this.createRecentSearchesCookie();
	},
	init : function(cookieName){
		this.getRecentSearchCookie();
	},
	setRecentSearches:function(searchObj){
		try{
		if(searchObj != null){
			RecentSearches.fromAirport = searchObj.depCity;
			RecentSearches.toAirport = searchObj.arrCity;
			RecentSearches.leaveDate = searchObj.depDate;
			RecentSearches.returnDate = searchObj.arrDate;
		}
		}catch(error){}

		this.getCurrentSearch();
		if(this.hasRecentSearches){
			this.setRecentSearchCookie();
		} else {
		this.createRecentSearchesCookie();
		}
	},
	verifyValidSearch:function(){
	
	}
	

};
RecentSearches.init();



/*
	/delta/shared_content/edgecache/js/core/FlightSearch.js
*/
var FlightSearch = {
	revenueFormId : "RevenueSearch",
	awardsFormId : "AwardSearch",
	isSimpleSearch : true,
	isHomepageLayout : true, //D9208617
	isBookTripError : false, //D9208617
	isUpgradable : false,
	searchFormat : "",
	travelType : "",
	searchType : "",
	postToAdvancedSearch : false,
	errorContainer :  "FlightSearchError",
	isDebugEnabled : true,
	mpInjectedFields : { act_url : "mp_act_url" },
	revenueExceptionsRegex : /roundtrip|oneway|flexAirports|flexDatesOption|departureAirportMilesRange|flexDates|flex_DatesPlusMinus|searchRefundableFlights|searchByCabin|searchByFare|search_price|search_schedule|cabinChoice|rtr_MUUpgrade/,
	// D9258295 added awardExceptionsRegex for AwardMUUpgrade
	awardExceptionsRegex : /roundtrip|oneway|departureDate|cabin|TimeOptions|flex_DatesPlusMinus|flexDates|search_price|search_schedule|searchOnlyDeltaFlights|rtr_awardMUUpgrade|travellingOnItinerary/,
	FormFieldMappings : {
		tripTypes : { rtr : "roundtrip", revenue : "booking_tripType", award : "awards_oneWayOrRTR" },
		tripTypesOneWay : { rtr : "oneway", revenue : "booking_tripType", award : "awards_oneWayOrRTR" },
		origin : { rtr : "departureCity_0", revenue : "booking_mc_departureCity_0", award : "awards_deptCity_0" },
		destination : { rtr : "destinationCity_0", revenue : "booking_mc_destinationCity_0", award : "awards_returnCity_0" },
		originRadius : [
			{ rtr : "flexAirportsDeparture_0", revenue : "booking_departureAirportMilesRange" },
			{ rtr : "flexAirportsDeparture_1", revenue : "booking_departureAirportMilesRange" },
			{ rtr : "flexAirportsDeparture_2", revenue : "booking_departureAirportMilesRange" },
			{ rtr : "flexAirportsDeparture_4", revenue : "booking_departureAirportMilesRange" }
		],
		destinationRadius : [
			{ rtr : "flexAirportsDestination_0", revenue : "booking_destinationAirportMilesRange" },
			{ rtr : "flexAirportsDestination_1", revenue : "booking_destinationAirportMilesRange" },
			{ rtr : "flexAirportsDestination_2", revenue : "booking_destinationAirportMilesRange" },
			{ rtr : "flexAirportsDestination_4", revenue : "booking_destinationAirportMilesRange" }
		],
		departureDates : [
			{ rtr : "departureDate_0", revenue : "booking_mc_departureDate_0", award : "awards_deptMonth_0" },
			{ rtr : "departureDate_1", revenue : "booking_mc_departureDate_1", award : "awards_deptMonth_1" }
		],
		originFlexDays : [
			{ rtr : "flexDaysBeforeDeparture", revenue : "booking_flexEarlierDepartureDays" },
			{ rtr : "flexDaysAfterDeparture", revenue : "booking_flexLaterDepartureDays" }
		],
		destinationFlexDays : [
			{ rtr : "flexDaysBeforeDestination", revenue : "booking_flexEarlierDestinationDays" },
			{ rtr : "flexDaysAfterDestination", revenue : "booking_flexLaterDestinationDays" }
		],
		departureTimes : [
			{ rtr : "departureTimeOptions_0", revenue : "booking_mc_departureTimeOptions_0", award : "awards_deptTime_0" },
			{ rtr : "departureTimeOptions_1", revenue : "booking_mc_departureTimeOptions_1", award : "awards_deptTime_1" }
		],
		multicity_origins : [
			{ rtr : "mc_departureCity_0", revenue : "booking_mc_departureCity_0", award : "awards_deptCity_0" },
			{ rtr : "mc_departureCity_1", revenue : "booking_mc_departureCity_1", award : "awards_deptCity_1" },
			{ rtr : "mc_departureCity_2", revenue : "booking_mc_departureCity_2", award : "awards_deptCity_2" },
			{ rtr : "mc_departureCity_3", revenue : "booking_mc_departureCity_3", award : "awards_deptCity_3" },
			{ rtr : "mc_departureCity_4", revenue : "booking_mc_departureCity_4", award : "awards_deptCity_4" },
			{ rtr : "mc_departureCity_5", revenue : "booking_mc_departureCity_5", award : "awards_deptCity_5" }
		],
		multicity_destinations : [
			{ rtr : "mc_destinationCity_0", revenue : "booking_mc_destinationCity_0", award : "awards_returnCity_0" },
			{ rtr : "mc_destinationCity_1", revenue : "booking_mc_destinationCity_1", award : "awards_returnCity_1" },
			{ rtr : "mc_destinationCity_2", revenue : "booking_mc_destinationCity_2", award : "awards_returnCity_2" },
			{ rtr : "mc_destinationCity_3", revenue : "booking_mc_destinationCity_3", award : "awards_returnCity_3" },
			{ rtr : "mc_destinationCity_4", revenue : "booking_mc_destinationCity_4", award : "awards_returnCity_4" },
			{ rtr : "mc_destinationCity_5", revenue : "booking_mc_destinationCity_5", award : "awards_returnCity_5" }
		],
		multicity_departureDates : [
			{ rtr : "mc_departureDate_0", revenue : "booking_mc_departureDate_0", award : "awards_deptMonth_0" },
			{ rtr : "mc_departureDate_1", revenue : "booking_mc_departureDate_1", award : "awards_deptMonth_1" },
			{ rtr : "mc_departureDate_2", revenue : "booking_mc_departureDate_2", award : "awards_deptMonth_2" },
			{ rtr : "mc_departureDate_3", revenue : "booking_mc_departureDate_3", award : "awards_deptMonth_3" },
			{ rtr : "mc_departureDate_4", revenue : "booking_mc_departureDate_4", award : "awards_deptMonth_4" },
			{ rtr : "mc_departureDate_5", revenue : "booking_mc_departureDate_5", award : "awards_deptMonth_5" }
		],
		multicity_departureTimes : [
			{ rtr : "mc_departureTimeOptions_0", revenue : "booking_mc_departureTimeOptions_0", award : "awards_deptTime_0" },
			{ rtr : "mc_departureTimeOptions_1", revenue : "booking_mc_departureTimeOptions_1", award : "awards_deptTime_1" },
			{ rtr : "mc_departureTimeOptions_2", revenue : "booking_mc_departureTimeOptions_2", award : "awards_deptTime_2" },
			{ rtr : "mc_departureTimeOptions_3", revenue : "booking_mc_departureTimeOptions_3", award : "awards_deptTime_3" },
			{ rtr : "mc_departureTimeOptions_4", revenue : "booking_mc_departureTimeOptions_4", award : "awards_deptTime_4" },
			{ rtr : "mc_departureTimeOptions_5", revenue : "booking_mc_departureTimeOptions_5", award : "awards_deptTime_5" }
		],
		cabinOrClassOption : [
			{ rtr: "searchByCabin", revenue : "booking_cabinClassOption" },
			{ rtr: "searchByFare", revenue : "booking_cabinClassOption" }
		],
		cabinBooking : { rtr : "cabinChoice_booking", revenue : "booking_cabinclass", award : "awards_cabin" },
		cabinAward : { rtr : "cabinChoice_award", award : "awards_cabin" },
		fareClass : { rtr : "fareClass", revenue : "booking_cabinFareClass"},
		passengers : { rtr : "passengers", revenue : "booking_passengers", award : "awards_numPax" },
		//D9258295 added award : awards_MUUpgrade and requestAwardUpgrade : and updated showUpgrade :
		requestUpgrade : { rtr : "rtr_MUUpgrade", revenue : "booking_MUUpgrade" },
		requestAwardUpgrade : { rtr: "rtr_awardMUUpgrade", award : "awards_MUUpgrade" },
		showUpgrade : { rtr : "showMUUpgrade", revenue : "booking_showMUUpgrade", award : "awards_showMUUpgrade" },
		memberTravelingInItinerary : { rtr : "travellingOnItinerary", award : "awards_medallionTraveler" },
		price : { rtr : "search_price", revenue : "booking_price_schedule", award : "awards_pricingSearch" },
		schedule : { rtr : "search_schedule", revenue : "booking_price_schedule", award : "awards_pricingSearch" },
		refundable : { rtr : "searchRefundableFlights", revenue : "booking_refundable" },
		flexOption : [
			{ rtr : "flexAirports", revenue : "booking_flexSearchOption" },
			{ rtr : "flexDates", revenue : "booking_flexSearchOption", award : "awards_calendarSearch" }
		],
		plusMinusOne : { rtr : "flex_DatesPlusMinus", revenue : "booking_plusMinus", award : "awards_calendarSearch" },
		flexibleDays : { rtr : "flexDatesOption_days", revenue : "booking_nearByDateFlexOption" },
		flexibleWeekends : { rtr : "flexDatesOption_weekends", revenue : "booking_nearByDateFlexOption" },
		flexWeekendSelection : { rtr : "flexDatesWeekends", revenue : "booking_flexMonthForWeekendSearch"},
		calendar : { rtr : "flexDates", award : "awards_calendarSearch"},
		deltaOnly : { rtr : "searchOnlyDeltaFlights", award : "awards_displayPreferredOnly" }
	},
	FormFieldValueMappings : {
		flexOptionMappings : {
			Revenue : [
				{ flexOptionValue : "flexAirports", formValue : "flex_airports" },
				{ flexOptionValue : "flexDates", formValue : "flex_dates" }
			]
		},
		timePeriodMappings : {
			Awards : [
				{ timePeriodValue : "AT", formValue : "12M"},
				{ timePeriodValue : "AM", formValue : "MON"},
				{ timePeriodValue : "MD", formValue : "MDY"},
				{ timePeriodValue : "PM", formValue : "DAY"},
				{ timePeriodValue : "NT", formValue : "NGT"},
				{ timePeriodValue : "01A", formValue : "MON"},
				{ timePeriodValue : "02A", formValue : "MON"},
				{ timePeriodValue : "03A", formValue : "MON"},
				{ timePeriodValue : "04A", formValue : "MON"},
				{ timePeriodValue : "05A", formValue : "MON"},
				{ timePeriodValue : "06A", formValue : "MON"},
				{ timePeriodValue : "07A", formValue : "MON"},
				{ timePeriodValue : "08A", formValue : "MON"},
				{ timePeriodValue : "09A", formValue : "MON"},
				{ timePeriodValue : "10A", formValue : "MON"},
				{ timePeriodValue : "11A", formValue : "MON"},
				{ timePeriodValue : "12N", formValue : "MDY"},
				{ timePeriodValue : "1P", formValue : "DAY"},
				{ timePeriodValue : "2P", formValue : "DAY"},
				{ timePeriodValue : "3P", formValue : "DAY"},
				{ timePeriodValue : "4P", formValue : "DAY"},
				{ timePeriodValue : "5P", formValue : "DAY"},
				{ timePeriodValue : "6P", formValue : "DAY"},
				{ timePeriodValue : "7P", formValue : "NGT"},
				{ timePeriodValue : "8P", formValue : "NGT"},
				{ timePeriodValue : "9P", formValue : "NGT"},
				{ timePeriodValue : "10P", formValue : "NGT"},
				{ timePeriodValue : "11P", formValue : "NGT"},
				{ timePeriodValue : "12M", formValue : "NGT"}
			]
		}
	},
	RequiredFields : {
		roundtrip : [ "departureCity_0", "destinationCity_0", "departureDate_0", "departureDate_1" ],
		oneway : [ "departureCity_0", "destinationCity_0", "departureDate_0" ],
		multicity : [ "mc_departureCity_", "mc_destinationCity_", "mc_departureDate_" ]
	},
	ErrorMessages : {
		departureCityMissingError : "You must enter a departure city.",
		destinationCityMissingError : "You must enter a destination city.",
		departureDateMissingError : "You must enter a departure date.",
		destinationDateMissingError : "You must enter a return date.",
		departureDateOutOfRangeError : "Departure date must not be further than 331 days from today.",
		destinationDateOutOfRangeError : "Return date must not be further than 331 days from today.",
		incompatibleDatesError : "Departure date must be before return date."
	},
	logMessage : function(message) {
		if(this.isDebugEnabled){
			try {
				console.log(message);
			} catch (error){
				// silently ignored
			}
		}
	},
	isExceptionField : function(id){
		if(this.searchType != "award") {
			return id.match(this.revenueExceptionsRegex);
		} else {
			return id.match(this.awardExceptionsRegex);
		}
	},
	checkAwardsDates : function() {
		try {
			var monthsTagFormat = "awards_deptMonth_", dayTagFormat = "awards_deptDay_", maxTags = 5;
			for (var i=0; i<maxTags; i++) {
				var currentMonthTag = get(monthsTagFormat + i);
				var currentDayTag = get(dayTagFormat + i);
				try {
					var monthTagValue = currentMonthTag.value;
					if (exists(monthTagValue) && monthTagValue !== "") {
						if (isNaN(monthTagValue)) {
							monthTagValue = monthTagValue.split("/")
							if (monthTagValue.length >= 1) {
								if (!isNaN(monthTagValue[0]) && !isNaN(monthTagValue[1])) {
									currentMonthTag.value = parseInt(monthTagValue[0], 10) - 1;
									currentDayTag.value = parseInt(monthTagValue[1], 10);
								} else {
									currentMonthTag.value = monthTagValue[0];
									currentDayTag.value = monthTagValue[1];
								}
							} else {
								throw { errorNumber : 1, errorDescription : "invalid month format"};
							}
						}
					}
				} catch(tagValueFormatError) {
					if (exists(currentMonthTag)) {
						currentMonthTag.value = "";
					}
					if (exists(currentDayTag)) {
						currentDayTag.value = "";
					}
				}
			}
		} catch(generalError) {}
	},
	handleFieldExceptions : function(sourceId, targetId, value){
		this.logMessage("handleFieldException for sourceId: " + sourceId + ", targetId: " + targetId + ", value: " + value);
		var numOptions;
		var tempValue;
		var tempString;
		var numLegs = 0;
		/* ******************** Revenue Search Exceptions ******************** */
		if(this.searchType != "award"){
			if (targetId == "booking_tripType" && get(sourceId).checked) {
				if(!this.postToAdvancedSearch) {
					get(targetId).value = value;
					this.travelType = value;
					return;
				} else {
					get(targetId).value = this.travelType;
					return;
				}
			}else if(targetId == "booking_departureAirportMilesRange"){
				for(var i=0; i<this.FormFieldMappings.originRadius.length; i++){
					if(get(this.FormFieldMappings.originRadius[i].rtr).checked) {
						get(targetId).value = get(this.FormFieldMappings.originRadius[i].rtr).value;
						return;
					}
				}
			} else if(targetId == "booking_destinationAirportMilesRange" ){
				for(var i=0; i<this.FormFieldMappings.destinationRadius.length; i++){
					if(get(this.FormFieldMappings.destinationRadius[i].rtr).checked) {
						get(targetId).value = get(this.FormFieldMappings.destinationRadius[i].rtr).value;
						return;
					}
				}
			} else if (targetId.match("flexSearchOption")) {
				if(this.searchFormat == "simple" || this.searchFormat == "revision") {
					get(this.FormFieldMappings.plusMinusOne.revenue).value = (get(this.FormFieldMappings.plusMinusOne.rtr).checked) ? "on" : "";
					return;
				} else {
					for(var i=0; i< this.FormFieldMappings.flexOption.length; i++){
						if(sourceId.match(this.FormFieldMappings.flexOption[i].rtr)){
							for(var j=0; j< this.FormFieldValueMappings.flexOptionMappings.Revenue.length; j++){
								if(value == this.FormFieldValueMappings.flexOptionMappings.Revenue[j].flexOptionValue && get(sourceId).checked) {
									get(targetId).value = this.FormFieldValueMappings.flexOptionMappings.Revenue[j].formValue;
									return;
								}
							}
							/* not sure where best to store this value */
							get(targetId).value = "exact";
							return;
						}
					}
				}
			} else if(targetId.match("booking_plusMinus")) {
				get(this.FormFieldMappings.plusMinusOne.revenue).value = (get(this.FormFieldMappings.plusMinusOne.rtr).checked) ? "on" : "";
				return;
			}else if (targetId.match("booking_nearByDateFlexOption")) {
				if(sourceId == "flexDatesOption_days" && get(sourceId).checked) {
					get(targetId).value = "flex_dates";
					return;
				} else if(sourceId == "flexDatesOption_weekends" && get(sourceId).checked) {
					get(targetId).value = "flex_weekends";
					return;
				}
			} else if( targetId == "booking_flexMonthForWeekendSearch") {
				/* technically not an exception, but the regex needs to be updated */
				get(targetId).value = value;
			} else if (targetId == "booking_refundable"){
				get(targetId).value = (get(sourceId).checked) ? "on" : "";
				return;
			} else if(targetId == "booking_cabinClassOption" || targetId == "booking_cabinclass" || targetId == "booking_cabinFareClass" ) {
				if((this.searchFormat == "simple" || this.searchFormat == "schedules") && targetId.match("booking_cabinclass")) {
					if(this.searchFormat == "schedules") { targetId = "schedules_cabin"; }
					// get( targetId ).value = (this.searchFormat != "schedules") ? value : value.split("-")[1];
					get( targetId ).value = value;
					if(this.searchFormat == "schedules"){
						var returnTripSet = false;
						for(var i=0; i<4; i++){
							tempString = "itinSegment[" + i + "]";
							tempValue = get(tempString).value;
							if(tempValue != "") {
								tempValue = (value.match(/Coach/)) ? "0:L" + tempValue :  "0:I" + tempValue
								get(tempString).value = tempValue;
								numLegs++;
							} else if(!returnTripSet && this.travelType.toLowerCase() == "roundtrip") {
								var outboundString = get('itinSegment[0]').value;
								var	departureCity = outboundString.split(':')[2];
								var returnString = get('itinSegment[' + (i-1) + ']').value;
								var returnCity = returnString.split(':')[3];
								var travelClass = (value.match(/Coach/)) ? "1:L" :  "1:I";
								var returnDate = get(this.FormFieldMappings.departureDates[1].rtr).value;
								var returnTime = get(this.FormFieldMappings.departureTimes[1].rtr).value;
								var returnMonth = returnDate.split('/')[0];
								returnMonth = parseInt(returnMonth, 10) - 1;
								returnMonth = monthUtility.getMonths(returnMonth);
								var returnDay = returnDate.split('/')[1];
								var returnYear = returnDate.split('/')[2];
								var returnTime = (returnTime == "AT") ? "7A" : (returnTime == "AM") ? "7A" : (returnTime == "MD") ? "12P" : (returnTime == "PM") ? "5P" : (returnTime == "NT") ? "7P" : "7A";
								var itinSegmentString = travelClass + ":" + returnCity + ":" + departureCity + ":::" + returnMonth + ":" + returnDay + ":" + returnYear + ":" + returnTime;
								
								get(tempString).value = itinSegmentString;
								returnTripSet = true;
								numLegs++;									
							}
						}
						get("schedules_numOfSegments").value = numLegs;
					}
					return;
				} else {
					if(targetId == "booking_cabinclass" ) {
						if( exists(get("searchByCabin")) ) {
							get( targetId ).value = (get("searchByCabin").checked) ? value : "";
						} else {
							get( targetId ).value = value;
						}
						return;
					} else if( get(sourceId).checked && (targetId == "booking_cabinClassOption" || targetId == "booking_cabinFareClass") ){ 
						get(targetId).value = value;
						return;
					}
				}
			} else if( targetId.match("booking_price_schedule") && sourceId.match("search_price")) {
				get( targetId ).value = (sourceId.match("search_price") && get(sourceId).checked) ? "price" : "schedule";
				return;
			} else if( targetId.match("booking_MUUpgrade")) {
				get(this.FormFieldMappings.requestUpgrade.revenue).value = (get(this.FormFieldMappings.requestUpgrade.rtr).checked) ? "on" : "off";
				get("booking_MUUpgrade").value = (get(this.FormFieldMappings.requestUpgrade.rtr).checked) ? "on" : "off";
			}

		/* ******************** Awards Search Exceptions ******************** */
		} else {
			if (targetId == "awards_oneWayOrRTR" && get(sourceId).checked) {
				//get(targetId).value = value;
				return;
			} else if( targetId.match("deptMonth") ){
				tempValue = value.split("/");
				get( targetId ).value = parseInt(tempValue[0], 10)-1;
				targetId = targetId.replace("deptMonth", "deptDay");
				get( targetId ).value = parseInt(tempValue[1], 10);
				return;
			} else if ( targetId.match("cabin") ){
				get( targetId ).value = value.split("-")[1];
				return;
			} else if( targetId.match("deptTime") ) {
				var timeMappingFound = false;
				numOptions = this.FormFieldValueMappings.timePeriodMappings.Awards.length;
				for(var i=0; i<numOptions; i++) {
					if(value == this.FormFieldValueMappings.timePeriodMappings.Awards[i].timePeriodValue) {
						get( targetId ).value = this.FormFieldValueMappings.timePeriodMappings.Awards[i].formValue;
						timeMappingFound = true;
						return;
					}
				}
				if (!timeMappingFound) {
					get( targetId ).value = value;
				}
			} else if( targetId == "awards_calendarSearch" ) {
				get( targetId ).value = (get(sourceId).checked) ? "true" : "false";
				return;
			} else if( targetId == "awards_pricingSearch" ) {
				if(sourceId == "search_price" && get(sourceId).checked) {
					get( targetId ).value = (this.travelType.toLowerCase() != "multicity") ? "true" : "false";
				} else if(sourceId == "search_schedule" && get(sourceId).checked){
					get( targetId ).value = "false";
				}
				return;
			} else if( targetId == "awards_medallionTraveler" || targetId == "awards_displayPreferredOnly" ) {
				get( targetId ).value = (get(sourceId).checked) ? "1" : "0";
				return;
					// D9258295 added awards_MUUpgrade
			} else if( targetId.match("awards_MUUpgrade")) {
				get(this.FormFieldMappings.requestAwardUpgrade.award).value = (get(this.FormFieldMappings.requestAwardUpgrade.rtr).checked) ? "on" : "off";
			}
		}
	},
	getAndSetField : function(id) {
		var numOptions;
		var formField;
		var targetId;
		var dayValue;
		var monthValue;
		try {
			for(fieldSet in this.FormFieldMappings){
				numOptions = this.FormFieldMappings[fieldSet].length;
				if(numOptions != undefined && numOptions != "undefined"){
					for(var i=0; i < numOptions; i++){
						if(this.FormFieldMappings[fieldSet][i].rtr == id && this.FormFieldMappings[fieldSet][i][this.searchType] != "undefined"){
							this.logMessage("fieldSet is: " + fieldSet);
							// targetId = this.FormFieldMappings[fieldSet][this.searchType]; /* ie fails out on this */
							targetId = (this.searchType == "revenue") ? this.FormFieldMappings[fieldSet][i]["revenue"] : this.FormFieldMappings[fieldSet][i]["award"];
							value= get(id).value
//							if(value=="mm/dd/yyyy") { break; }
							if(!this.isExceptionField(id)) {
								get( targetId ).value = value;
								break;
							} else {
								this.handleFieldExceptions(id, targetId, value);
								break;
							}
							break;
						}
					}
				} else {
					if( this.FormFieldMappings[fieldSet].rtr == id ) {
						formField = get(id);
						value = formField.value;
						// targetId = this.FormFieldMappings[fieldSet][this.searchType]; /* ie fails out on this */
						targetId = (this.searchType == "revenue") ? this.FormFieldMappings[fieldSet]["revenue"] : this.FormFieldMappings[fieldSet]["award"];
						if(value == "mm/dd/yyyy") { break; }
						if(!this.isExceptionField(id)) {
							get( targetId ).value = value;
							break;
						} else {
							this.handleFieldExceptions(id, targetId, value);
							break;
						}
					}
				}
			}
		} catch(error) { 
			this.logMessage("Error occured with id: " + id + ", Error is: " + error);
			return false;
		}
	},
	searchRoundTrip : function() {
		this.travelType = (this.searchType == "revenue") ? "roundtrip" : "roundTrip";
		if(isSimpleSearch) {
			show("departureDate_1_Fieldset");
		} else {
			setClassName("roundtrip","active");
			setClassName("oneway","");
			setClassName("multicity","");
			hide("FlightSearch_TravelComplex");
			show("FlightSearch_Travel");
			show("FlightSearch_Travel_Dates_Return");
		}
	},
	searchOneWay : function() {
		this.travelType = (this.searchType == "revenue") ? "oneway" : "oneWay";
		if(isSimpleSearch) {
			hide("departureDate_1_Fieldset");
		} else {
			setClassName("roundtrip","");
			setClassName("oneway","active");
			setClassName("multicity","");
			hide("FlightSearch_TravelComplex");
			hide("FlightSearch_Travel_Dates_Return");
			show("FlightSearch_Travel");
		}
	},
	searchMultiCity : function() {
		this.travelType = "multicity";
		setClassName("roundtrip","");
		setClassName("oneway","");
		setClassName("multicity","active");
		hide("FlightSearch_Travel");
		hide("FareClassMessage");
		show("FlightSearch_TravelComplex");

	},
	searchWithFlexAirports : function(isChecked) {
		if(isChecked) {
			hide("FlightSearch_Travel_FlexDates");
			hide("FlightSearch_FareOptions");
			hide("AwardSearchOption");
			show("FareClassMessage");
			show("FlightSearch_Travel_FlexAirports_Options");
			show("FlightSearch_Travel_FlexAirports_Options");
			setClassName("FlightSearch_Travel_Airports", "active");
			setClassName("FlightSearch_Travel_FlexAirports_Options", "active");
		} else {
			hide("FareClassMessage");
			hide("FlightSearch_Travel_FlexAirports_Options");
			show("FlightSearch_Travel_FlexDates");
			show("FlightSearch_FareOptions");
			show("AwardSearchOption");
			setClassName("FlightSearch_Travel_Airports", "");
			setClassName("FlightSearch_Travel_FlexAirports_Options", "");
		}
	},
	searchWithFlexDates : function(isChecked) {
		if(exists(get("searchForAwards"))) {
			if(!get("searchForAwards").checked){
				if(isChecked) {
					hide("FlightSearch_Travel_FlexAirports");
					hide("FlightSearch_FareOptions");
					hide("AwardSearchOption");
					show("FareClassMessage");
					show("FlightSearch_Travel_FlexDates_Options");
					setClassName("FlightSearch_Travel_Dates", "active");
					setClassName("FlightSearch_Travel_FlexDates", "active");
					setClassName("FlightSearch_Travel_FlexDates_Options", "active");
				} else {
					hide("FareClassMessage");
					hide("FlightSearch_Travel_FlexDates_Options");
					show("FlightSearch_Travel_FlexAirports");
					show("FlightSearch_FareOptions");
					show("AwardSearchOption");
					setClassName("FlightSearch_Travel_Dates", "");
					setClassName("FlightSearch_Travel_FlexDates", "");
					setClassName("FlightSearch_Travel_FlexDates_Options", "");
				}
			}
		}
	},
	searchWithMiles : function(isChecked) {
		if(isChecked) {
			this.searchType = "award";
			try {
				get("searchByCabin").checked = true;
			} catch(error){}
			
			hide("FlightSearch_Travel_FlexAirports");
			hide("FlightSearch_Travel_FlexAirports_Options");
			hide("FlightSearch_FareOptions");
			hide("FareClassMessage");
			hide("FlightSearch_Travel_FlexDates_Options");
			hide("RefundableOption");
			if(this.searchFormat == "simple"){
				hide("cabinChoiceLabel_wlink");
				show("cabinChoiceLabel_wolink");
			}
			if(this.searchFormat == "full") {
				show("cabinChoice_award");
				hide("cabinChoice_booking");
				hide("cabinHelp");
			}
			/*Commented for defect#10525*/
			/*if(exists(get("UpgradeOption"))) {
				hide("UpgradeOption");
			}*/ 
			// D9258295 added AwardUpgradeOption
			show("DeltaOnlyOption");
			if(exists(get("TravelingOnItineraryOption"))) {
				show("TravelingOnItineraryOption");
				/*Added for defect#10525*/
				if(get("travellingOnItinerary").checked)
				{
					hide("UpgradeOption");
					show("AwardUpgradeOption");
				}
				else
				{	
					hide("AwardUpgradeOption");
					show("UpgradeOption");
				}
				//if(exists(get("AwardUpgradeOption"))) {
					//show("AwardUpgradeOption");
				//}
			}
			
		} else {
			this.searchType = "revenue";
			if(exists(get("TravelingOnItineraryOption"))) {
				hide("TravelingOnItineraryOption");
				}
				// D9258295 added AwardUpgradeOption
			if(exists(get("AwardUpgradeOption"))) {
				hide("AwardUpgradeOption");
				}
			if(this.searchFormat == "simple"){
				show("cabinChoiceLabel_wlink");
				hide("cabinChoiceLabel_wolink");
			}
			if(this.searchFormat == "full") {
				show("cabinChoice_booking");
				hide("cabinChoice_award");
				show("cabinHelp");
			}
			// D9258295 added AwardUpgradeOption
			hide("DeltaOnlyOption");
			show("FlightSearch_Travel_FlexAirports");
			show("FlightSearch_FareOptions");
			show("RefundableOption");
			if(exists(get("UpgradeOption"))) {
				show("UpgradeOption");
			}
			if(exists(get("AwardUpgradeOption"))) {
				hide("AwardUpgradeOption");
			}
		}
	},
	searchByPrice : function(isChecked) {
		if(this.searchType == "revenue"){
			if(isChecked){
				show("FlightSearch_Travel_FlexDates");
				show("FlightSearch_Travel_FlexAirports");
			} else {
				hide("FlightSearch_Travel_FlexDates");
				hide("FlightSearch_Travel_FlexAirports");
			}
		}
	},
	searchBySchedule : function(isChecked) {
		if(this.searchType == "revenue"){
			if(isChecked){
				hide("FlightSearch_Travel_FlexDates");
				hide("FlightSearch_Travel_FlexAirports");
			} else {
				show("FlightSearch_Travel_FlexDates");
				show("FlightSearch_Travel_FlexAirports");
			}
		}
	},
	moreOptions : function() {
		hide("FlightSearch_MoreOptionsSimple");
		show("FlightSearch_LessOptionsSimple");
		show("AdditionalOptions");
	},
	lessOptions : function() {
		hide("AdditionalOptions");
		hide("FlightSearch_LessOptionsSimple");
		show("FlightSearch_MoreOptionsSimple");
	},
	moreFlights : function() {
		hide("mc_addMoreFlights");
		show("mc_leg_4");
		show("mc_leg_5");
	},
	
	//added requestAwardUpgrade function
	travellingOnItinerary : function(isChecked) {
		if(this.searchType == "award"){
			if(isChecked){
				hide("UpgradeOption"); //Added for defect#10525
				show("AwardUpgradeOption");
			} else {
				hide("AwardUpgradeOption");
				show("UpgradeOption"); //Added for defect#10525  
			}
		}
	},	
	requestAwardUpgrade : function(id){
		if(this.searchType == "award"){
			if(get(id).checked) {
				hide("UpgradeOption"); //Added for defect#10525
				show("AwardUpgradeOption"); 
				
			} else {
			hide("AwardUpgradeOption");
			show("UpgradeOption"); //Added for defect#10525
			}
		}
	},

	gotoAdvancedSearch : function(id) {
		if(id == "multicitySearchLink" ) { 
			this.travelType = "multicity"; 
			this.postToAdvancedSearch = true;
		} else if(id == "advancedBookingSearch"){
			this.postToAdvancedSearch = true;
		}
		var formAction = '/booking/searchFlights.do?displayTripType=';
		formAction = formAction + this.travelType.toLowerCase();
		document.forms['RevenueSearch'].action = formAction;
		this.validateFlightSearchForm("FlightSearch");
	} ,
	updateForm : function(id) {
		var isChecked;
		switch(id) {
			case "roundtrip":
				this.searchRoundTrip();
				break;
			case "oneway":
				this.searchOneWay();
				break;
			case "multicity":
				this.searchMultiCity();
				break;
			case "MoreFlights":
				this.moreFlights();
				break;
			case "flexAirports":
				isChecked = (get(id).checked != null) ? get(id).checked : false;
				this.searchWithFlexAirports(isChecked);
				break;
			case "flexDates":
				isChecked = (get(id).checked != null) ? get(id).checked : false;
				this.searchWithFlexDates(isChecked);
				break;
			case "cabinChoice_booking":
				try{
					if(!get("searchByCabin").checked) {
						get("searchByCabin").checked = true;
					}
				} catch(error){}
				break;
			case "fareClass":
				if(!get("searchByFare").checked) {
					get("searchByFare").checked = true;
				}
				break;
				//added requestAwardUpgrade
			case "travellingOnItinerary":
				this.requestAwardUpgrade(id);
				break;
			
			case "AwardUpgradeOption":
				isChecked = (get(id).checked) ? true : false;
				this.travellingOnItinerary(isChecked);
				break;
	
			case "searchForAwards":
				isChecked = (get(id).checked) ? true : false;
				this.searchWithMiles(isChecked);
				break;
			case "search_price":
				isChecked = (get(id).checked) ? true : false;
				this.searchByPrice(isChecked);
				break;
			case "search_schedule":
				isChecked = (get(id).checked) ? true : false;
				this.searchBySchedule(isChecked);
				break;
			case "FlightSearch_MoreOptionsSimple":
				this.moreOptions();
				break;
			case "FlightSearch_LessOptionsSimple":
				this.lessOptions();
				break;
			default:
				break;
		}
	},
	resetHiddenForm : function() {
		return;
		var formObj;
		var numFormFields;
		if(this.searchType == "revenue") {
			formObj = get(this.shoppingFormId);
			numFormFields = formObj.length;
		}else if(this.searchType == "awards"){
			formObj = get(this.awardsFormId);
			numFormFields = formObj.length;
		}
		for(var i=0; i < numFormFields; i++){
			if(formObj[i].type != undefined && get(formObj[i].id) != null && 
				get(formObj[i].id).offsetWidth != 0){
				this.getAndSetField(formObj[i].id);
			}
		}
	},
	formatErrorMessage : function(errorMessage){
		var formattedError = '<div class="error">' + errorMessage + '</div>';
		return formattedError;
	},
	getDateDifference : function(date1, date2) {
		var daysDiff = ((date1 - date2) / (1000*60*60*24) );
		return Math.round(daysDiff);
	},
	isAirportCodeEntered : function(id) {
		if(get(id).value.length == 3) {
			return true;
		}
		return false;
	},
	isDateEntered : function(id) {
		var domElement = get(id);
		if(domElement.value != "mm/dd/yyyy" && domElement.value.length != 0) {
			return true;
		}
		return false;
	},
	isDateInRange : function(id) {
		var today = new Date().getTime();
		var domElement = get(id);
		var flightDate = new Date(domElement.value).getTime();
		if(this.getDateDifference(flightDate, today) < 332){
			return true;
		}
		return false;
	},
	areDatesCompatible : function() {
		var leaveDate;
		var returnDate;
		if(this.travelType.toLowerCase() == "roundtrip") {
			leaveDate = new Date(get(this.RequiredFields.roundtrip[2]).value).getTime();
			returnDate = new Date(get(this.RequiredFields.roundtrip[3]).value).getTime();
			if(returnDate >= leaveDate ) { 
				return true ; 
			}
		} else if(this.travelType.toLowerCase() == "multicity") {
		}
		return false;
	},
	markError : function( id ) {
		setClassName( id, "error" )
		setClassName( id + "_label", "error" )
	},
	clearError : function(id){
		setClassName( id, "" )
		setClassName( id + "_label", "" )
	},
	isErrorFound : function() {
		var isError = false;
		var errorText = '';
		var currentRequiredFieldId;
		if(this.postToAdvancedSearch || this.travelType.toLowerCase() == "multicity") { return false; }
		hide(this.errorContainer);
		var requiredFieldArray = (this.travelType.toLowerCase() == "roundtrip") ? this.RequiredFields["roundtrip"] : this.RequiredFields["oneway"];
		for(var i=0; i< requiredFieldArray.length; i++ ){
			currentRequiredFieldId = requiredFieldArray[i];
			switch (currentRequiredFieldId) {
				case "departureCity_0":
					if(!this.isAirportCodeEntered(currentRequiredFieldId)) {
						isError = true;
						errorText += this.formatErrorMessage(this.ErrorMessages.departureCityMissingError);
						this.markError( requiredFieldArray[i] );
					} else {
						this.clearError( requiredFieldArray[i] );
					}
					break;
				case "destinationCity_0":
					if(!this.isAirportCodeEntered(currentRequiredFieldId)) {
						isError = true;
						errorText += this.formatErrorMessage(this.ErrorMessages.destinationCityMissingError);
						this.markError( requiredFieldArray[i] );
					} else {
						this.clearError( requiredFieldArray[i] );
					}
					break;
				case "departureDate_0":
					if(exists(get("flexDatesOption_weekends")) && get("flexDatesOption_weekends").checked) { break; }
					if(!this.isDateEntered(currentRequiredFieldId)) {
						isError = true;
						errorText += this.formatErrorMessage(this.ErrorMessages.departureDateMissingError);
						this.markError( currentRequiredFieldId );
					} else {
						this.clearError( currentRequiredFieldId );
					}
					if(!this.isDateInRange(currentRequiredFieldId)) {
						isError = true;
						errorText += this.formatErrorMessage(this.ErrorMessages.departureDateOutOfRangeError);
						this.markError( currentRequiredFieldId );
					} else {
						this.clearError( currentRequiredFieldId );
					}
					break;
				case "departureDate_1":
					if(this.travelType.toLowerCase() == "oneway" || (exists(get("flexDatesOption_weekends")) && get("flexDatesOption_weekends").checked)){ 
						break; 
					} else if(this.travelType.toLowerCase() == "roundtrip") {
						if(!this.isDateEntered(currentRequiredFieldId)){
							isError = true;
							errorText += this.formatErrorMessage(this.ErrorMessages.destinationDateMissingError);
							this.markError( currentRequiredFieldId );
						} else {
							this.clearError( currentRequiredFieldId );
						}
						if(!this.isDateInRange(currentRequiredFieldId)){
							isError = true;
							errorText += this.formatErrorMessage(this.ErrorMessages.destinationDateOutOfRangeError);
							this.markError( currentRequiredFieldId );
						} else {
							this.clearError( currentRequiredFieldId );
						}
						if(!this.areDatesCompatible()) {
							isError = true;
							errorText += this.formatErrorMessage(this.ErrorMessages.incompatibleDatesError);
							this.markError( currentRequiredFieldId );
						} else {
							this.clearError( currentRequiredFieldId );
						}
						break;
					}
					break;
				default:
					break;
			}
		}
		if(isError){
			if(isHomepageLayout){
				show('booktrip_errorMsg');
				this.isBookTripError = true;
				hide(this.errorContainer);
				return true;
			} else {
			setInnerHTML(this.errorContainer, errorText);
			show(this.errorContainer);
			return true;	
			}
		} else {
			if(isHomepageLayout){
				hide('booktrip_errorMsg');
				return false;
			} else {

			setInnerHTML(this.errorContainer, "");
			hide(this.errorContainer);
			return false;	
		}
		}
	},
	isMPInjectedField : function(fieldName) {
		return exists(fieldName) && fieldName.match(this.mpInjectedFields.act_url) != null;
	},
	validateFlightSearchForm : function(id){
		var formObj = get(id);
		var computedStyle;
		var numFormFields;
		var tmp;
		if(this.isErrorFound() && !this.postToAdvancedSearch) { 
			return false; 
		} else {
			if(this.searchType != "award"){
				get(this.FormFieldMappings.tripTypes.revenue).value = this.travelType;
			} else {
	//			get(this.FormFieldMappings.tripTypes.award).value = this.travelType;
				if(this.travelType.toLowerCase() == "roundtrip") {
					get(this.FormFieldMappings.tripTypes.award).value = "roundTrip";
				} else if(this.travelType.toLowerCase() == "oneway") {
					get(this.FormFieldMappings.tripTypes.award).value = "oneWay";
				} else if(this.travelType.toLowerCase() == "multicity") {
					get(this.FormFieldMappings.tripTypes.award).value = "multiCity";
				}
				if(this.postToAdvancedSearch) {
					this.searchType = "revenue";
					this.logMessage("switching awards to revenue search to post to full search");
				} else {
					this.logMessage("awards " + this.travelType + " search");
				}
			}
			try{
				if(exists(formObj)){
		//			this.resetHiddenForm();
					numFormFields = formObj.length
					for(var i=0; i < numFormFields; i++){
						if(!this.isMPInjectedField(formObj[i].name)) {
							if (
								(formObj[i].type != undefined && get(formObj[i].id) != null && get(formObj[i].id).offsetWidth != 0) ||
								(formObj[i].type != undefined && get(formObj[i].id) != null && formObj[i].id == "cabinChoice")
							){
								this.logMessage("formObj[" + i + "] is: " + formObj[i].id);
								this.getAndSetField(formObj[i].id);
							}
						} 
					}
				}
				try {
					if (this.searchType != "award" && this.travelType.toLowerCase() == "multicity") {
						get("booking_flexSearchOption").value = "exact";
					}
				} catch(error) {}
				try {
					if(get("booking_cabinClassOption").value == "cabin" && this.searchFormat != "simple"){
						get("booking_cabinFareClass").value = "";
					} else if(get("booking_cabinClassOption").value == "class" && this.searchFormat != "simple") {
						get("booking_cabinclass").value = "";
					}
				} catch(error){}
				if (this.searchType == "award") {
					this.checkAwardsDates();
				}
				this.submitSearchForm();
			}catch(error){
				this.logMessage("Error in validateFlightSearchForm of: " + error); 
				return false;
			}
			return false;
		}
	},
	hideSubmitButton : function(buttonId, waitMsgId) {
		try {
			hide(buttonId);
			show(waitMsgId, 'inline');
		} catch(e){
			
		}
	},
	submitSearchForm : function() {
		var formId;
		var action;
		formId = (this.searchType == "revenue") ? this.revenueFormId : this.awardsFormId;
		get(formId).submit();
	},
	init : function(isSimpleSearch, searchFormat, searchType, travelType, isUpgradable, isHomepageLayout) {
		this.isSimpleSearch = (isSimpleSearch != "") ? isSimpleSearch : true;
		this.isHomepageLayout = (isHomepageLayout != "") ? isHomepageLayout : true;
		this.searchFormat = (searchFormat != "") ? searchFormat : "simple";
		this.searchType = (searchType != "") ? searchType : "revenue";
		this.travelType = (travelType != "") ? travelType : "roundtrip";
		this.isUpgradable = isUpgradable;
			try {
				if(get("travellingOnItinerary").checked) { 
					show("AwardUpgradeOption");
				}
			} catch(error) {} 
		}
	}


/*****************************************************
 * ypSlideOutMenu
 * http://ypslideoutmenus.sourceforge.net/
 *
 * Licensed under AFL 2.0
 * http://www.opensource.org/licenses/afl-2.0.php
 *****************************************************/
var isie8 = false;
if(document.documentMode != undefined){
	if(document.documentMode == 8){
		isie8 = true;	
	}
}

ypSlideOutMenu.Registry = [];
ypSlideOutMenu.aniLen = 250;
ypSlideOutMenu.hideDelay = 1000;
ypSlideOutMenu.minCPUResolution = 10;
function ypSlideOutMenu(menu_name, direction_of_animation, left_position, top_position, width, height, isHome) {
	this.ie = '\v' == 'v' ? 1 : 0;
	this.ie6 = this.ie && typeof(navigator.appVersion) === "string" && navigator.appVersion.indexOf("MSIE 6") !== -1 ? 1 : 0;
	this.ns4 = document.layers ? 1 : 0;
	this.dom = document.getElementById ? 1 : 0;
	this.css = "";
	this.ie6IFrameId = 'ypSlideOutMenu_IE6IFrame';
	this.useIE6Iframe = false;
	if(this.ie || this.ns4 || this.dom) {
		this.id = menu_name;
		this.dir = direction_of_animation;
		this.orientation = direction_of_animation == "left" || direction_of_animation == "right" ? "h" : "v";
		this.dirType = direction_of_animation == "right" || direction_of_animation == "down" ? "-" : "+";
		this.dim = this.orientation == "h" ? width : height;
		this.left_position = left_position;
			if(isie8 && isHome){
				left_position = left_position - 9;	
			}
		this.top_position = top_position;
			if(isie8){
				top_position = top_position + 50;	
			}
		this.width = width;
		this.height = height;
		this.isHome = isHome;
		this.hideTimer = false;
		this.aniTimer = false;
		this.open = false;
		this.over = false;
		this.startTime = 0;
		this.gRef = "ypSlideOutMenu_" + menu_name;
		eval(this.gRef+"=this");
		ypSlideOutMenu.Registry[menu_name] = this;
		var d = document;
		var styleRules = "";
		styleRules += "#" + this.id + "Container{visibility:hidden;";
		styleRules += "left:" + left_position + "px;";
		styleRules += "top:" + top_position + "px;";
		styleRules += "overflow:hidden;z-index:10000;}";
		styleRules += "#" + this.id + "Container,#" + this.id + "Content{position:absolute;";
		styleRules += "width:" + width + "px;";
		styleRules += "height:" + height + "px;";
		styleRules += "clip:rect(0 " + width + " " + height+" 0);";
		styleRules += "}";
		this.css=styleRules;
		this.load();
	}
}
ypSlideOutMenu.writeCSS = function() {
	document.writeln("<style type=\"text/css\">");
	for(var id in ypSlideOutMenu.Registry) {
		document.writeln(ypSlideOutMenu.Registry[id].css);
	}
	document.writeln("</style>");
}
ypSlideOutMenu.prototype.load = function() {
	var d = document;
	var containerId = this.id + "Container";
	var contentId = this.id + "Content";
	var containerElement = this.dom ? d.getElementById(containerId) : this.ie ? d.all[containerId] : d.layers[containerId];
	if (containerElement) {
		var currentMenu = this.ns4 ? containerElement.layers[contentId] : this.ie ? d.all[contentId] : d.getElementById(contentId);
	}
	if (!containerElement||!currentMenu) {
		window.setTimeout(this.gRef+".load()",100);
	} else {
		this.container = containerElement;
		this.menu = currentMenu;
		this.style = this.ns4 ? this.menu : this.menu.style;
		this.homePos = eval("0" + this.dirType + this.dim);
		this.outPos=0;
		this.accelConst= (this.outPos - this.homePos)/ypSlideOutMenu.aniLen/ypSlideOutMenu.aniLen;
		if(this.ns4) {
			this.menu.captureEvents(Event.MOUSEOVER|Event.MOUSEOUT);
		}
		if (this.id !== "menu4") {
			this.menu.onmouseover = new Function("ypSlideOutMenu.showMenu('" + this.id + "')");
			this.menu.onmouseout = new Function("ypSlideOutMenu.hideMenu('" + this.id + "')");
		}
		this.endSlide();
		this.setIE6IFrameVisibility(false);
	}
}
ypSlideOutMenu.showMenu = function(id) {
	if (id == "menu1" || id=="menu2" || id=="menu3") {
		isOpening[id] = true;
		setMenuState(id);
	}
	var reg=ypSlideOutMenu.Registry;
	var obj=ypSlideOutMenu.Registry[id];
	/* for some reason this is needed in order to get IE6 to display the submit button */
	if (id == "menu4" && obj.ie6) {
		document.pref.go_button.style.clear = "none";
	}
	if (obj.container) {
		obj.over=true;
		for (menu in reg) {
			if (id != menu) {
				ypSlideOutMenu.hide(menu);
			}
		}
		if (obj.hideTimer) {
			reg[id].hideTimer = window.clearTimeout(reg[id].hideTimer);
		}
		if (!obj.open && !obj.aniTimer) {
			reg[id].startSlide(true);
		}
	}
}
ypSlideOutMenu.hideMenu = function(id) {
	var obj=ypSlideOutMenu.Registry[id];
	if (id!="menu4") {
		isOpening[id] = false;
		if (obj.container) {
			if (obj.hideTimer) {
				window.clearTimeout(obj.hideTimer);
			}
			obj.hideTimer = window.setTimeout("ypSlideOutMenu.hide('" + id + "')", ypSlideOutMenu.hideDelay);
		}
	}
}
ypSlideOutMenu.hideAll = function() {
	var reg=ypSlideOutMenu.Registry;
	for (menu in reg) {
		ypSlideOutMenu.hide(menu);
		if (menu.hideTimer) {
			window.clearTimeout(menu.hideTimer);
		}
	}
}
ypSlideOutMenu.hide = function(id) {
	var obj=ypSlideOutMenu.Registry[id];
	obj.over=false;
	if (obj.hideTimer) {
		window.clearTimeout(obj.hideTimer);
	}
	obj.hideTimer = 0;
	if (obj.open && !obj.aniTimer) {
		obj.startSlide(false);
	}
	/* for some reason this is needed in order to get IE6 to display the submit button */
	if (id == "menu4" && obj.ie6) {
		document.pref.go_button.style.clear = "";
	}
}
ypSlideOutMenu.prototype.startSlide = function(isOpen) {
	this[isOpen?"onactivate":"ondeactivate"]();
	this.open = isOpen;
	if (isOpen) {
		this.setVisibility(true);
	}
	this.startTime=(new Date()).getTime();
	this.aniTimer = window.setInterval(this.gRef+".slide()", ypSlideOutMenu.minCPUResolution);
}
ypSlideOutMenu.prototype.slide = function() {
	var currentTime = (new Date()).getTime()-this.startTime;
	if (currentTime > ypSlideOutMenu.aniLen) {
		this.endSlide(false);
		this.setIE6IFrameVisibility(this.open);
	} else {
		var d = Math.round(Math.pow(ypSlideOutMenu.aniLen-currentTime, 2)*this.accelConst);
		if( this.open && this.dirType == "-") {
			d = -d;
		} else {
			if (this.open && this.dirType=="+") {
				d = -d;
			} else {
				if (!this.open && this.dirType == "-") {
					d =- this.dim+d;
				} else {
					d = this.dim + d;
				}
			}
		}
		this.moveTo(d);
	}
}
ypSlideOutMenu.prototype.endSlide = function() {
	this.aniTimer=window.clearTimeout(this.aniTimer);
	this.moveTo(this.open?this.outPos:this.homePos);
	if (!this.open) {
		this.setVisibility(false);
		if (this.id == "menu4") {
			checkPrefTab(); /* see preferences.js */
		} else {
			setMenuState(this.id);
		}
	}
	if((this.open && !this.over) || (!this.open&&this.over)) {
		this.startSlide(this.over);
	}
}
ypSlideOutMenu.prototype.createHTMLElement = function(Definition) {
	var Element = document.createElement(Definition.elementType);
	Element.id = Definition.id;
	if(Definition.className) { Element.className = Definition.className; }
	if(Definition.position) { Element.style.position = Definition.position; }
	if(Definition.width) { Element.style.width = Definition.width; }
	if(Definition.zIndex) { Element.style.zIndex = Definition.zIndex; }
	if(Definition.frameborder) { Element.setAttribute('frameborder', Definition.frameborder); }
	if(Definition.scrolling) { Element.setAttribute('scrolling', Definition.scrolling); }
	if(Definition.src) { Element.setAttribute('src', Definition.src); }
	Definition.appendChildTo.appendChild(Element);
	return Element;
}

ypSlideOutMenu.prototype.setIE6IFrameVisibility = function(isVisible) {
	if(this.isHome){
		if (this.useIE6Iframe) {
			if (isVisible) {
				var ie6Iframe = get(this.ie6IFrameId);
				if (!ie6Iframe) {
					ie6Iframe = createPTextHTMLElement({elementType:'iframe', id:this.ie6IFrameId, zIndex:101, className:'ypSlideOutMenuIE6IFrameShim', position:'absolute', frameborder:'0', scrolling:'no', width:this.width, appendChildTo:get('siteNav'),src:'java' + 'script:\'<html></html>\';'});
				}
				ie6Iframe.style.height = this.height + 'px';
				ie6Iframe.style.top = this.top_position;
				ie6Iframe.style.left = this.left_position;
				show(this.ie6IFrameId)
			} else {
				hide(this.ie6IFrameId);
			}
		}
	}
}
ypSlideOutMenu.prototype.setVisibility = function(isVisible) {
	var s = this.ns4 ? this.container : this.container.style;
	s.visibility = isVisible ? "visible" : "hidden";
	if (!isVisible && exists(get(this.id + "_trigger"))) {
//		setClassName(get(this.id + "_trigger").parentNode.id, "");
	}
}
ypSlideOutMenu.prototype.moveTo = function(p) {
	this.style[this.orientation=="h"?"left":"top"] = this.ns4 ? p:p + "px";
}
ypSlideOutMenu.prototype.getPos=function(c) {
	return parseInt(this.style[c]);
}
ypSlideOutMenu.prototype.onactivate=function(){}
ypSlideOutMenu.prototype.ondeactivate=function(){}

/*****************************************************
 * added for handling of menu states
 *****************************************************/
function setMenuState(id) {
	var menuTrigger = id + "_trigger";
	if( isOpening[id]) {
		/* reset menus to original state on page load */
		if (isActivated["menu1"]) { 
			isActivated["menu1"] = false;
			setClassName(menuTrigger, getClassName(menuTrigger).split("_")[0]);
		}
		if (isActivated["menu2"]) {
			isActivated["menu2"] = false;
			setClassName(menuTrigger, getClassName(menuTrigger).split("_")[0]);
		}
		if (isActivated["menu3"]) {
			isActivated["menu3"] = false;
			setClassName(menuTrigger, getClassName(menuTrigger).split("_")[0]);
		}
		isActivated[id] = true;
		if (getClassName(menuTrigger) == "active") {
			setClassName(menuTrigger, getClassName(menuTrigger) + "_activated");
		} else {
			setClassName(menuTrigger, "activated");
			setClassName(get(menuTrigger).parentNode.id, "menu_trigger_parent_active");
		}
	} else {
		isActivated[id] = false;
		if (exists(get(menuTrigger).parentNode.id) && get(menuTrigger).parentNode.id !== "") {
			setClassName(get(menuTrigger).parentNode.id, "");
		}
		if (getClassName(menuTrigger) != "active") {
			if (getClassName(menuTrigger).split("_").length > 1) {
				setClassName(menuTrigger,"active");
			} else {
				setClassName(menuTrigger, "");
			}
		}
	}
}
var isActivated = { menu1:false, menu2:false, menu3:false };
var isOpening = { menu1:false, menu2:false, menu3:false };
function GenObj() {}
GenObj.prototype.setProp = function(prop,value) { this[prop] = value; }
GenObj.prototype.getProp = function(prop) { return this[prop]; }
/* Country Object */
function Country(display,country_code, supported_languages, region_code) {
	this.oProps = new GenObj();
	this.setProp("display", display);
	this.setProp("country_code", country_code);
	this.setProp("supported_languages", supported_languages);
	this.setProp("region_code",region_code);
}
Country.prototype.setProp = function(prop,value) { this.oProps.setProp(prop,value); }
Country.prototype.getProp = function(prop) { var rtn = this.oProps.getProp(prop); if(rtn==undefined) {} return rtn; }
Country.prototype.toString = function() { return this.oProps.getProp("display"); }
/* Language Object */
function Language(display, language_code, default_country) {
	this.oProps = new GenObj();
	this.setProp("display", display);
	this.setProp("language_code", language_code);
	this.setProp("default_country", default_country);
}
Language.prototype.setProp = function(prop,value) { this.oProps.setProp(prop,value); }
Language.prototype.getProp = function(prop) { var rtn = this.oProps.getProp(prop); if(rtn==undefined) {} return rtn; }
Language.prototype.toString = function() { return this.oProps.getProp("display"); }

function isEnglishURL(str) {
	var re = new RegExp(/www\d*|delta|draft\d*|si\d*|st\d*|qa\d*|ddwa\d*|dswa\d*|dtwa\d*|dpwa\d*|\d*|.*as\d*|localhost/);
	return str.match(re)[0] != "";
}

function getCountry(code) {
	code = code.toLowerCase();
	for (var i=0; i<CountryOptions.length; i++) {
		if (CountryOptions[i].getProp("country_code") == code) {
			return CountryOptions[i].toString();
		}
	}
}
function getLanguage(code) {
	var rtnString;
	for (var i=0; i<LanguageOptions.length; i++) {
		if (LanguageOptions[i].getProp("language_code") == code) {
			return LanguageOptions[i].toString();
		}
	}
}
function getCountryLanguages(code) {
	for (var i=0; i<CountryOptions.length; i++) {
		if (CountryOptions[i].getProp("country_code") == code) {
			return CountryOptions[i].getProp("supported_languages");
		}
	}
}
function getProxy() {
	var rtn = window.location.href.split(";");
	if(rtn.length >1) { rtn = rtn[0] + ";" }
	else { rtn = rtn[0]; }
	return rtn;
}

/* function for creating country select */
function writeAvailableCountries() {
	var rtnString = '<select id="loc" name="loc" onChange="writeAvailableLanguages(this.value);" style="width:100%;">';
	rtnString += '<option value="none" selected="true">Select One</option>';
	for(var i=0;i<CountryOptions.length;i++) {
		rtnString += '<option value="'+ CountryOptions[i].getProp("country_code");
		rtnString +='">' + CountryOptions[i].toString()+'</option>';
	}
	rtnString += '</select>';
	return rtnString;
}
/* function for creating language select */
function writeAvailableLanguages(code) {
	var rtnString;
	if (code != "none" && code!="") {
		var supported = getCountryLanguages(code);
		rtnString = '<select id="lang" name="lang" style="width:100%;">';
		rtnString += '<option value="none">Select One</option>';
		for(var i=0;i<supported.length;i++) {
			rtnString += '<option value="'+ supported[i];
			if(supported.length==1) { rtnString += '" selected="selected' }
			rtnString +='">' + getLanguage(supported[i])+'</option>';
		}
		document.getElementById("lang_select").innerHTML = rtnString;
	} else {
		rtnString = '<select id="lang" name="lang" style="width:100%;" disabled>';
		rtnString += '<option value="none" selected="selected">Select One</option>';
	}
	rtnString += '</select>';
	return rtnString;
}
function refreshPage(oForm, lang, loc) {
	var curURL = window.location.toString();
	var name = curURL.match("//[^.]*").toString().split("//")[1];
	var locatn;
	if(isEnglishURL(name)) {
		curURL = curURL.replace(name, "www");
		name = "www"; 
	}
	if ( ((lang=="en")&&(name=="www" || name=="si"))||(lang==name) ) {
			if(curURL.indexOf("#")!=-1) { window.location.href=curURL.replace(/#/,""); }
			else { window.location.href=curURL+"#"; }
	} else {
		if (lang == "en") {
			if(curURL.indexOf("https")!=-1) { locatn = curURL.match("[^:]*") + curURL.split(";")[1].replace(/https/,""); }
			else { locatn = curURL.match("[^:]*") + curURL.split(";")[1].replace(/http/,""); }
		} else {
			if(isEnglishURL(name)) { locatn = curURL.match("[^:]*") + "://"+lang+".delta.com/delta/en"+lang+"/?24;"+curURL; }
			else { locatn = curURL.match("[^:]*") + "://"+lang+".delta.com/delta/en"+lang+"/?24;"+curURL.split(";")[1]; }
		}
		window.location = locatn;
	}
}
/* form handler */
function doLanguageChoice(language, location) {
	var pref = language + "-" + location;
	setPref(pref);
	refreshPage(null, language, location);
}
function submitPreferences(oForm) {
	var lang = document.getElementById(oForm).lang.value;
	var loc = (document.getElementById(oForm).loc.value!="none") ? document.getElementById(oForm).loc.value : "us";
	var oForm = document.getElementById(oForm);
	if (lang == "none") {
		var curLang = window.location.toString().match("//[^.]*").toString().split("//")[1];
		lang = (isEnglishURL(curLang)) ? "en" : curLang;
	}
	doLanguageChoice(lang, loc);
}

// language and location cookie stuff
function createCookie(name, value, days) {
	var expires = "";
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		expires = "; expires=" + date.toGMTString();
	}
	document.cookie = name+"="+value+expires+"; path=/" + "; domain=delta.com";
}
function deleteCookie(name, path) {
	var value = getCookie(name);
	if (exists(value)) {
		document.cookie = name + "=;path=/;domain=delta.com;expires=Thu, 01-Jan-1970 00:00:01 GMT";
	}
}
function getCookie(name) {
	var nameEQ = name + "=";
	var cookieArray = document.cookie.split(';');
	for (var i=0;i < cookieArray.length; i++) {
		var c = cookieArray[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
function setPref(value) { createCookie('pref',value,30); }
function checkPrefTab() { if(prefTabActive) { togglePrefTab("hide"); prefTabActive=false; } }
function togglePrefTab(state) {
	if (state == "hide") { document.getElementById("lang_loc").className = 'pref_inactive'; }
	else if( state == "show") { document.getElementById("lang_loc").className = 'pref_active';prefTabActive=true; }
	return true;
}
function getDefault(lang) {
	var rtnString = "en-us";
	if (isEnglishURL(lang)) { return rtnString; }
	for (var i=0; i<LanguageOptions.length; i++) {
		if (LanguageOptions[i].getProp("language_code") == lang) {
			rtnString = LanguageOptions[i].getProp("language_code") + "-" + LanguageOptions[i].getProp("default_country");
			return rtnString;
		}
	}
	return rtnString;
}
function getLangLoc() {
	var prefString = getPrefs();
	var rtnString = '<span style="display:block;">';
	if (prefString == "null" || prefString == null) {
		prefString=getDefault(window.location.toString().match("//[^.]*").toString().split("//")[1]);
		rtnString += getCountry(prefString.split("-")[1]);
		rtnString += "<br />" + getLanguage(prefString.split("-")[0]);
	} else {
		rtnString += getCountry(prefString.split("|")[0].split("-")[1]);
		rtnString += "<br />" + getLanguage(prefString.split("|")[0].split("-")[0]);
	}
	rtnString += "</span>";
	return rtnString;
}
function autoRedirect() {
	var windowLocation = window.location.toString();
	if(windowLocation.match("business_programs_services") || windowLocation.match("business_programs_services")) { return true; }
	var prefLang=getPrefs().split("|")[0].split("-")[0];
	var curLang;
	if (prefLang != null && prefLang != "null") {
      var browserLang = windowLocation.match("//[^.]*").toString().split("//")[1];
		for (var i=0; i<LanguageOptions.length; i++) {
			curLang = LanguageOptions[i].getProp("language_code");
			if (prefLang==curLang && browserLang!=curLang) {
				if( strCompare(curLang,"en") ) { break; }
				else {
               var redirectURL = windowLocation;
               if (document.title == "Page Not Found") {
                  redirectURL = "http://delta.delta.com/";
               }
               window.location.href = "http://" + curLang + ".delta.com/delta/en" + curLang + "/?24;" + redirectURL; 
            }
			}
		}
	}
}
var prefTabActive = false;
var CountryOptions = [
	/****** Country, code, [ary lang codes], 3c region code ******/
	new Country("Antigua &amp; Barbuda", "ag", ["en"], "CAR"),
	new Country("Argentina", "ar", ["en", "es"], "SAM"),
	new Country("Aruba & Antilles","aw", ["en"], "CAR"),
	new Country("Austria", "at", ["en", "de"], "ENT"),
	new Country("Australia", "au", ["en"], "PS"),
	new Country("Bahamas", "bs", ["en"], "CAR"),
	new Country("Barbados", "bb", ["en"], "CAR"),
	new Country("Belgium", "be", ["en", "fr"], "ENT"),
	new Country("Belize",  "bz", ["en", "es"], "CAM"),
	new Country("Bermuda",  "bm", ["en"], "CAR"),
	new Country("Brazil",  "br", ["en", "pt"], "BR"),
	new Country("Canada",  "ca", ["en", "fr"], "CA"),
	new Country("Cayman Islands",  "ky", ["en"], "CAR"),
	new Country("Chile",  "cl", ["en", "es"], "SAM"),
	new Country("China",  "cn", ["en", "zh"], "GC"),
	new Country("Colombia",  "co", ["en", "es"], "SAM"),
	new Country("Costa Rica",  "cr", ["en", "es"], "CAM"),
	new Country("Croatia", "hr", ["en"], "EET"),
	new Country("Cyprus", "cy", ["en"], "EZT"),
	new Country("Czech Republic", "cz", ["en"], "EET"),
	new Country("Denmark", "dk", ["en"], "ENT"),
	new Country("Dominican Republic", "do", ["en", "es"], "CAR"),
	new Country("Ecuador", "ec", ["en", "es"], "SAM"),
	new Country("Egypt", "eg", ["en"], "ME"),
	new Country("El Salvador", "sv", ["en", "es"], "CAM"),
	new Country("Finland", "fi", ["en"], "ENT"),
	new Country("France", "fr", ["en", "fr"], "FR"),
	new Country("Germany", "de", ["en", "de"], "DE"),
	new Country("Greece", "gr", ["en"], "EZT"),
	new Country("Guadeloupe", "gp", ["en", "fr"], "CAR"),
	new Country("Guam", "gu", ["en"], "MI"),
	new Country("Guatemala", "gt", ["en", "es"], "CAM"),
	new Country("Honduras", "hn", ["en", "es"], "CAM"),
	new Country("Hong Kong", "hk", ["en", "zt"], "GC"),
	new Country("Hungary", "hu", ["en"], "EET"),
	new Country("India", "in", ["en"], "IN"),
	new Country("Indonesia", "id", ["en"], "AS"),
	new Country("Ireland", "ie", ["en"], "IE"),
	new Country("Israel", "il", ["en"], "ME"),
	new Country("Italy", "it", ["en", "it"], "IT"),
	/* new Country("Jamaica", "jm", ["en"], "CAR"), */
	new Country("Japan", "jp", ["en",  "ja"], "JP"),
	new Country("Kuwait", "kw", ["en"], "ME"),
	new Country("Luxembourg", "lu", ["en"], "ENT"),
	new Country("Malaysia", "my", ["en"], "AS"),
	new Country("Martinique", "mq", ["en", "fr"], "CAR"),
	new Country("Mexico", "mx", ["en", "es"], "MX"),
	new Country("Netherlands", "nl", ["en"], "ENT"),
	new Country("Netherlands Antilles", "an", ["en"], "CAR"),
	new Country("New Zealand", "nz", ["en"], "PS"),
	new Country("Nicaragua", "ni", ["en", "es"], "CAM"),
	new Country("Norway", "no", ["en"], "ENT"),
	new Country("Panama", "pa", ["en", "es"], "CAM"),
	new Country("Peru", "pe", ["en", "es"], "SAM"),
	new Country("Philippines", "ph", ["en"], "AS"),
	new Country("Poland", "pl", ["en"], "EET"),
	new Country("Portugal", "pt", ["en"], "ES"),
	new Country("Puerto Rico", "pr", ["en", "es"], "CAR"),
	new Country("Qatar", "qa", ["en"], "ME"),
	new Country("Romania", "ro", ["en"], "EET"),
	new Country("Russia", "ru", ["en", "ru"], "EE"),
	new Country("Saudi Arabia", "sa", ["en"], "ME"),
	new Country("Singapore", "sg", ["en"], "AS"),
	new Country("South Africa", "za", ["en"], "AF"),
	new Country("South Korea", "kr", ["en", "ko"], "AN"),
	new Country("Spain", "es", ["en", "es"], "ES"),
	new Country("St. Croix", "vi", ["en"], "CAR"),
	new Country("St. Lucia", "lc", ["en"], "CAR"),
	new Country("St. Maarten", "an", ["en"], "CAR"),
	new Country("St. Thomas", "vi", ["en"], "CAR"),
	new Country("Sweden", "se", ["en"], "ENT"),
	new Country("Switzerland", "ch", ["en", "fr", "de", "it"], "ENT"),
	new Country("Taiwan", "tw", ["en", "zt"], "GC"),
	new Country("Thailand", "th", ["en"], "AS"),
	new Country("Trinidad &amp Tobago", "tt", ["en"], "CAR"),
	new Country("Turkey", "tr", ["en"], "EZT"),
	new Country("Turks &amp; Caicos", "tc", ["en"], "CAR"),
	new Country("Ukraine", "ua", ["en", "ru"], "EET"),
	new Country("United Arab Emirates", "ae", ["en"], "ME"),
	new Country("United Kingdom", "gb", ["en"], "GB"),
	new Country("United States", "us", ["en", "es"], "US"),
	new Country("Uruguay", "uy", ["en", "es"], "SAM"),
	new Country("Venezuela", "ve", ["en", "es"], "SAM"),
	new Country("Viet Nam", "vn", ["en"], "AS")	
];

var LanguageOptions = [
	/* Language, code, default_country */
	new Language("English", "en", "us"),
	new Language("Chinese", "zh", "cn"),
	new Language("French", "fr", "fr"),
	new Language("German", "de", "de"),
	new Language("Italian", "it", "it"),
	new Language("Portuguese", "pt", "br"),
	new Language("Russian", "ru", "ru"),
	new Language("Spanish", "es", "us"),
	new Language("Japanese", "ja", "jp"),
	new Language("Korean", "ko", "kr"),
	new Language("Traditional Chinese", "zt", "hk")
];
CountryOptions.sort();

var calForm = "";
var calSDay = "";
var calSMonth = "";
childwin = null;

var cal_isNetscape = navigator.appName.indexOf("Netscape") != -1;

var cal_today = new Date();
var cal_currentDate = cal_today.getDate();
var cal_currentMonth = cal_today.getMonth();
var cal_currentYear = cal_today.getYear();

if (cal_isNetscape) cal_currentYear += 1900;

function openCalendar(tbForm, sDay, sMonth, e) {
   self.calForm = tbForm;
   self.calSDay = sDay;
   self.calSMonth = sMonth;

   w = screen.width-310
   h = screen.height-170
   x = e.screenX
   y = e.screenY
      if(x > w){
         x = x-310
         }
      if(y > h){
         y = y-170
         }

   var calendarUrl = "/components/calendar.jsp";

   var monthSel = document.getElementsByName(calSMonth);

   if (monthSel != null) {
      var selectedMonthIndex = monthSel[0].selectedIndex;
      var month = selectedMonthIndex;
      var year =  cal_currentYear;

      if (month < cal_currentMonth ) {
         year = year  + 1;
      }
      calendarUrl = calendarUrl + "?y=" + year + "&m=" + month;

   }
   childwin=window.open(calendarUrl,'Calendar','width=310,height=170,top='+y+',left='+x);
}

function setDate(day, month) {
   var daySel = document.getElementsByName(calSDay);
   daySel[0].options[day - 1].selected = true;
   var monthSel = document.getElementsByName(calSMonth);
   monthSel[0].options[month].selected = true;
}

function setRetMonth(tbForm, deptMonth, retMonth){
   var box1 = document.getElementsByName(deptMonth);
   var box2 = document.getElementsByName(retMonth);
   box2[0].selectedIndex = box1[0].selectedIndex;
}

// this will auto close the calendar window if no date is selected

function closeMe(){
   if (childwin != null){
   childwin.close()
   childwin = null
   }
}var airportListForm = "";
var airportListBox = "";

function openCityCodes(tbForm, tbBox, e) {
   self.airportListForm = tbForm;
   self.airportListBox = tbBox;

   w = screen.width-465
   h = screen.height-315
   x = e.screenX
   y = e.screenY
      if(x > w){
         x = x-45
         }
      if(y > h){
         y = y-315
         }

   childwin=window.open('/booking/cityCodes.do','CityCodes','width=465,height=315,top='+y+',left='+x);
}

function setAirportValue(airportCode) {
   var box = document.getElementsByName(airportListBox);
   for (var i=0; i<box.length; i++) {
      box[i].value = airportCode;
   }
}

// this will auto close the calendar if no date is selected and focus is lost

function closeMe(){
   if (childwin != null){
   childwin.close()
   childwin = null
   }
}/* begin /delta/shared_content/components/js/myitineraryHomepage.js */
function validateNumberform() {
	var f = document.forms['itinForm'];
	var validationError = false;
	var invalidfirstname = false;
	var invalidlastname = false;
	var invalidnumber = false;

	var errorMsg = "";
	setInnerHTML("itinerarySearchAlerts_Errors",errorMsg);
	var firstnamelength = f.firstName.value.length;
	var firstnamematch = f.firstName.value.match(/[a-zA-Z\s]+/);
	var lastnamelength = f.lastName.value.length;
	var lastnamematch = f.lastName.value.match(/[a-zA-Z\s-]+/);
	var numberlengthmatch = f.recLocId.value.match(/[^\s]+/);

	if (numberlengthmatch == null) {
		numberlength = 0;
		validationError = true;
	} else {
		numberlength = numberlengthmatch[0].length;
	}
	numbermatch1 = f.recLocId.value.match(/[\d]+/);
	numbermatch2 = f.recLocId.value.match(/[\w^_]+/); 

	if(firstnamematch == null || firstnamematch[0].length != firstnamelength) {
		validationError = true;
		invalidfirstname = true;
	}
	if(lastnamematch == null || lastnamematch[0].length != lastnamelength) {
		validationError = true;
		invalidlastname = true;
	}
	if(numberlength != 6) {
		validationError = true;
		invalidnumber = true;
	}
	if(numbermatch2 == null || numbermatch2[0].length != numberlength) {
		validationError = true;
		invalidnumber = true;
	}
	if(invalidfirstname) {
		setClassName('firstnamelabel','error');
		setClassName('firstName','error');
		errorMsg += '<div class="error">Please provide a first name.<\/div>';
	} else {
		setClassName('firstnamelabel','');
		setClassName('firstName','');
	}
	if(invalidlastname) {
		setClassName('lastnamelabel','error');
		setClassName('lastName','error');
		errorMsg += '<div class="error">Please provide a last name.<\/div>';
	} else {
		setClassName('lastnamelabel','');
		setClassName('lastName','');
	}
	if(invalidnumber) {
		setClassName('recLocIdlabel','error');
		setClassName('recLocId','error');
		errorMsg += '<div class="error">Please provide a confirmation number.<\/div>';
	} else {
		setClassName('recLocIdlabel','');
		setClassName('recLocId','');
	}
	setInnerHTML("itinerarySearchAlerts_Errors",errorMsg);
	if(validationError) { return false; }
	else { return true; }
}
/* end /delta/shared_content/components/js/myitineraryHomepage.js */
 function submitForm() {
	 var Index = document.getElementById('when').selectedIndex;
	switch(Index){
		case 0:
			document.flifoForm.flight_date.value = "Yesterday";
			document.schedForm.flight_date.value = "Yesterday";
			break;
		case 1:
			document.flifoForm.flight_date.value = "Today";
			document.schedForm.flight_date.value = "Today";
			 break;
		case 2:
			document.flifoForm.flight_date.value = "Tomorrow";
			document.schedForm.flight_date.value = "Tomorrow";
			break;
		default:
			break;
	}
	if (get('byFlightDate').checked) {
		document.schedForm.DptText.value = get('leavingfrom').value;
		document.schedForm.ArrText.value = get('goingto').value
		document.schedForm.submit();
	} else {
		document.flifoForm.flight_number.value = document.inputForm.flight_number.value;
		document.flifoForm.submit();
	}
}
function clearFlightNumber() {
	if(get('leavingfrom').value !== "" || get('goingto').value !== "") {
		get('flightnumber').value = "";
		document.flifoForm.flight_number.value = "";
		get('byFlightDate').checked = true;
	}
}
function clearOrigDest() {
	if(get('flightnumber').value !== "") {
		get('leavingfrom').value = "";
		get('goingto').value = "";
		document.schedForm.DptText.value = "";
		document.schedForm.ArrText.value = "";
		get('byFlightNumber').checked = true;
	}
}
/********************* begin misc.js ****************************/

var lostItems = {
	whereValue : !exists(get("required-where")) ? "" : this.getWhereValue(),
	airport_label_flight : '* To <a href="#" onClick="javascript:openCityCodes(\'LostItems\',\'required-airport\',event); return false;">airport</a>',
	airport_label : '* <a href="#" onClick="javascript:openCityCodes(\'LostItems\',\'required-airport\',event); return false;">Airport</a>',
	getWhereValue : function() {
		if(get("where-flight").checked) {
			this.whereValue = "flight";
			return;
		}
		if(get("where-gate").checked) {
			this.whereValue = "gate";
			return;
		}
		if(get("where-skyclub").checked) {
			this.whereValue = "club";
			return;
		}
	},
	setFlight : function() {
		get("airport_label").innerHTML = this.airport_label_flight;
		show("flight");
		show("fromAirport");
		hide("gate");
		get("required-flightNumber").value = "";
		get("required-fromAirport").value = "";
		get("required-gate").value = "none";
	},
	setGate : function() {
		get("airport_label").innerHTML = this.airport_label;
		hide("flight");
		hide("fromAirport");
		show("gate");
		get("required-flightNumber").value = "none";
		get("required-fromAirport").value = "none";
		get("required-gate").value = "";
	},
	setClub : function() {
		get("airport_label").innerHTML = this.airport_label;
		hide("flight");
		hide("fromAirport");
		hide("gate");
		get("required-flightNumber").value = "none";
		get("required-fromAirport").value = "none";
		get("required-gate").value = "none";
	},
	init : function() {
		lostItems.getWhereValue();
		switch(this.whereValue) {
			case "flight":
				lostItems.setFlight();
				break;
			case "gate":
				this.setGate();
				break;
			case "SkyClub" :
				this.setClub();
				break;
		}		
	}
}
//-----------------------------------------------------------------------------
// Some parameters for style and behaviour...
// Is better to use global parameters to avoid problems with updates,
// but if you want to override default values, here are the variables

DatePickerControl.defaultFormat   = "MM/DD/YYYY";
DatePickerControl.submitFormat    = "";
DatePickerControl.offsetY         = 1;
DatePickerControl.offsetX         = 0;
DatePickerControl.todayText       = "Today";
DatePickerControl.buttonTitle     = "Select a date";
DatePickerControl.buttonPosition  = "in";  // or "out"
DatePickerControl.buttonOffsetX   = 0;     // See below for some considerations about
DatePickerControl.buttonOffsetY   = 0;     // that values (for IE)
DatePickerControl.closeOnTodayBtn = true;  // close if today button is pressed?
DatePickerControl.defaultTodaySel = true;  // If true and content is blank, today date will be selected
DatePickerControl.autoShow        = false; // Auto show the calendar when the input grab the focus.
DatePickerControl.firstWeekDay    = 0;     // First day of week: 0=Sunday, 1=Monday, ..., 6=Saturday
DatePickerControl.weekend         = [0,6]; // Sunday and Saturday as weekend DatePickerControl.weekNumber      = false; // Display or not the week number


DatePickerControl.Months =
	["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];


DatePickerControl.Days =
	["S", "M", "T", "W", "T", "F", "S"];
//	["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];


//-----------------------------------------------------------------------------
// Specific patches

DatePickerControl.useTrickyBG = false;
if (navigator.userAgent.indexOf("MSIE") > 1){
	DatePickerControl.useTrickyBG   = true;
	DatePickerControl.offsetY       = 0;
	DatePickerControl.offsetX       = -1;
	DatePickerControl.buttonOffsetX = -4;
	DatePickerControl.buttonOffsetY = -2;
	// but if document have xhtml dtd, things are different... :S
	if (document.getElementsByTagName("html")[0].getAttribute("xmlns") != null){
		DatePickerControl.offsetY       = 16;
		DatePickerControl.offsetX       = 10;
		DatePickerControl.buttonOffsetX = 8;
		DatePickerControl.buttonOffsetY = 14;
	}
}

//-----------------------------------------------------------------------------
// Some constants and internal stuff

DatePickerControl.editIdPrefix    = "DPC_";          // The prefix for edit's id
DatePickerControl.displayed       = false;           // Is the calendar layer displayed?
DatePickerControl.HIDE_TIMEOUT    = 200;             // Time in ms for hide the calendar layer
DatePickerControl.hideTimeout     = null;            // The timeout identifier
DatePickerControl.buttonIdPrefix  = "CALBUTTON";     // The prefix for the calendar button's id
DatePickerControl.dayIdPrefix     = "CALDAY";        // The prefix for the calendar days frames' id
DatePickerControl.currentDay      = 1;               // The current day of current month of current year :-)
DatePickerControl.originalValue   = "";              // The original value of edit control
DatePickerControl.calFrameId      = "calendarframe"; // The id for the calendar layer
DatePickerControl.submitByKey     = false;           // Is submitting by keyboard?
DatePickerControl.dayOfWeek       = 0;               // The current day of current week ...
DatePickerControl.firstFocused    = false;           // Is the first time that the current edit control is focused?
DatePickerControl.hideCauseBlur   = false;           // Was the calendar close by onblur event?
DatePickerControl.onSubmitAsigned = false;           // Is form's onSubmit event asigned?
DatePickerControl.minDate         = null;            // The minimum date for the current datepicker
DatePickerControl.maxDate         = null;            // The maximum date for the current datepicker
DatePickerControl.DOMonth         = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; // Non-leap year month days
DatePickerControl.lDOMonth        = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; // Leap year month days

/**
 * Constructor
 */
function DatePickerControl()
{
}


/**
 * Creates the calendar's div element and the button into the input-texts with
 * attibute datepicker="true" or id="DPC_foo_[format]"
 */
DatePickerControl.init = function()
{
	// try to create the DatePickerControl.container:
	if (!document.getElementById("CalendarPickerControl")){
		// but first, take a look for global parameters:
		this.setGlobalParams();

		this.calBG = null;
		if (this.useTrickyBG){
			this.calBG                = document.createElement("iframe");
			this.calBG.id             = "CalendarPickerControlBG";
			this.calBG.style.zIndex   = "49999"; // below calcontainer
			this.calBG.style.position = "absolute";
			this.calBG.style.display  = "none";
			this.calBG.style.border   = "0px";
			this.calBG.style.top	  = "0px";
			this.calBG.style.left	  = "0px";
			this.calBG.src			  = "javascript:'<html></html>'";
			this.calBG.scrolling	  = "no";
			document.body.appendChild(this.calBG);
		}
		this.calContainer                = document.createElement("div");
		this.calContainer.id             = "CalendarPickerControl";
		this.calContainer.style.zIndex   = "50000";
		this.calContainer.style.position = "absolute";
		this.calContainer.style.display  = "none";
		document.body.appendChild(this.calContainer);

		if (this.calContainer.addEventListener){
			this.calContainer.addEventListener("click", DPC_onContainerClick, false);
			window.addEventListener("resize", DPC_onWindowResize, false);
		}
		else if (this.calContainer.attachEvent){
			this.calContainer.attachEvent("onclick", DPC_onContainerClick);
			window.attachEvent("onresize", DPC_onWindowResize);
		}
	}
	
	// looking for input controls that will be transformed into DatePickerControl's.
	var inputControls = document.getElementsByTagName("input");
	var inputsLength  = inputControls.length;
	for (i=0; i<inputsLength; i++){
		if (inputControls[i].type.toLowerCase() == "text"){
			var editctrl  = inputControls[i];
			var dpcattr   = editctrl.getAttribute("isdatepicker");
			var setEvents = false;
			// if datepicker pseudo-attribute:
			if (dpcattr != null && dpcattr == "true"){
				if (editctrl.id){
					if (!this.createButton(editctrl, false)) continue;
					setEvents = true;
				}
			}
			// if fomated id attr:
			else if (editctrl.id && editctrl.id.indexOf(this.editIdPrefix) == 0){
				if (!this.createButton(editctrl, true)) continue;
				setEvents = true;
			}
			//editctrl.setAttribute("isdatepicker", "true");
			// add the events:
			if (setEvents){
				if(editctrl.addEventListener){
					editctrl.addEventListener("keyup", DPC_onEditControlKeyUp, false);
					editctrl.addEventListener("keydown", DPC_onEditControlKeyDown, false);
					editctrl.addEventListener("keypress", DPC_onEditControlKeyPress, false);
					editctrl.addEventListener("blur", DPC_onEditControlBlur, false);
					editctrl.addEventListener("focus", DPC_onEditControlFocus, false);
					editctrl.addEventListener("change", DPC_onEditControlChange, false);
				}
				else if (editctrl.attachEvent){
					editctrl.attachEvent("onkeyup", DPC_onEditControlKeyUp);
					editctrl.attachEvent("onkeydown", DPC_onEditControlKeyDown);
					editctrl.attachEvent("onkeypress", DPC_onEditControlKeyPress);
					editctrl.attachEvent("onblur", DPC_onEditControlBlur);
					editctrl.attachEvent("onfocus", DPC_onEditControlFocus);
					editctrl.attachEvent("onchange", DPC_onEditControlChange);
				}
				var theForm = editctrl.form;
				if (!this.onSubmitAsigned && theForm){
					this.onSubmitAsigned = true;
					theForm.submitOrig = theForm.submit;
					theForm.submit = DPC_formSubmit;
					if (theForm.addEventListener){
						theForm.addEventListener('submit', DPC_onFormSubmit, false);
					}
					else if (theForm.attachEvent){
						theForm.attachEvent('onsubmit', DPC_onFormSubmit);
					}
				}
			}
		}
	}
}


/**
 * Set the global parameters.
 */
DatePickerControl.setGlobalParams = function()
{
	var obj = document.getElementById("DPC_DEFAULT_FORMAT");
	if (obj) this.defaultFormat = obj.value;

	obj = document.getElementById("DPC_SUBMIT_FORMAT");
	if (obj) this.submitFormat = obj.value;
	
	obj = document.getElementById("DPC_FIRST_WEEK_DAY");
	if (obj) this.firstWeekDay = (obj.value < 0 || obj.value > 6) ? 0 : parseInt(obj.value);
	
	obj = document.getElementById("DPC_WEEKEND_DAYS");
	if (obj) eval("this.weekend = " + obj.value);
	
	obj = document.getElementById("DPC_AUTO_SHOW");
	if (obj) this.autoShow = obj.value == "true";
	
	obj = document.getElementById("DPC_DEFAULT_TODAY");
	if (obj) this.defaultTodaySel = obj.value == "true";
	
	obj = document.getElementById("DPC_CALENDAR_OFFSET_X");
	if (obj) this.offsetX = parseInt(obj.value);
	
	obj = document.getElementById("DPC_CALENDAR_OFFSET_Y");
	if (obj) this.offsetY = parseInt(obj.value);
	
	obj = document.getElementById("DPC_TODAY_TEXT");
	if (obj) this.todayText = obj.value;
	
	obj = document.getElementById("DPC_BUTTON_TITLE");
	if (obj) this.buttonTitle = obj.value;
	
	obj = document.getElementById("DPC_BUTTON_POSITION");
	if (obj) this.buttonPosition = obj.value;
	
	obj = document.getElementById("DPC_BUTTON_OFFSET_X");
	if (obj) this.buttonOffsetX = parseInt(obj.value);
	
	obj = document.getElementById("DPC_BUTTON_OFFSET_Y");
	if (obj) this.buttonOffsetY = parseInt(obj.value);
	
	obj = document.getElementById("DPC_WEEK_NUMBER");
	if (obj) this.weekNumber = obj.value == "true";
	
	obj = document.getElementById("DPC_MONTH_NAMES");
	if (obj) eval("this.Months = " + obj.value);
	
	obj = document.getElementById("DPC_DAY_NAMES");
	if (obj) eval("this.Days = " + obj.value);
}


/**
 * Wrapper for init()
 */
function DPC_autoInit()
{
	DatePickerControl.init();
}

if (window.addEventListener){
	window.addEventListener("load", DPC_autoInit, false);
}
else if (window.attachEvent){
	window.attachEvent("onload", DPC_autoInit);
}


/**
 * Creates the calendar button for a text-input control and assign some attributes.
 * @param input The associated text-input to create the button.
 * @param useId Specify if you want to use the Id of input control to obtain the format
 * @return true is the control has been created, otherwise false
 */
DatePickerControl.createButton = function(input, useId)
{
	var newid = this.buttonIdPrefix + input.id;
	if (document.getElementById(newid)) return false; // if exists previously....
	// set the date format
	var fmt = "";
	if (useId){ // get the format from the control's id
		var arr = input.id.split("_");
		var last = arr[arr.length-1];
		// a not so beauty validation :S
		if ((last.indexOf("-")>0 || last.indexOf("/")>0 || last.indexOf(".")>0) && 
		     last.indexOf("YY") >= 0 && last.indexOf("D") >= 0 && last.indexOf("M") >= 0){ // is a format
			fmt = last;
		}
		else{
			fmt = this.defaultFormat;
		}
	}
	else{ // get the format from pseudo-attibute
		fmt = input.getAttribute("datepicker_format");
		if (!fmt){
			fmt = this.defaultFormat;
		}
	}
	input.setAttribute("datepicker_format", fmt);
	input.setAttribute("maxlength", fmt.length);
	
	// some new methods for datepickers
	input.setMinDate = function(d){this.setAttribute("datepicker_min", d);}
	input.setMaxDate = function(d){this.setAttribute("datepicker_max", d);}
	
	var calButton = document.createElement('img');
	calButton.id = newid;
	calButton.title = this.buttonTitle;
	// Set some attributes to remember the text-input associated
	// with this button and its format:
	calButton.setAttribute("datepicker_inputid", input.id);
	calButton.setAttribute("datepicker_format", fmt);
	// Add the event listeners:
	if (calButton.addEventListener){
		calButton.addEventListener("click", DPC_onButtonClick, false);
	}
	else if (calButton.attachEvent){
		calButton.attachEvent("onclick", DPC_onButtonClick);
	}
	// Set the style and position:
	calButton.className = "enhancedIconCalendar";
	calButton.src = "//images.delta.com/delta/enhancedCal/icon_calendar.gif";
	if (this.buttonPosition == "in"){
 		// calButton.style.left = "-" + calButton.offsetWidth;
	}

	var theParent = input.parentNode;
	var noBreak   = document.createElement('nobr');
	var spacer    = document.createElement('span');
	spacer.className = "calendarSelect";
	
	var sibling = null;
	if (input.nextSibling){
		sibling = input.nextSibling;
	}
	theParent.removeChild(input);
	noBreak.appendChild(input);
	spacer.appendChild(calButton);
	noBreak.appendChild(spacer);
	
	if (sibling){
		theParent.insertBefore(noBreak, sibling);
	}
	else{
		theParent.appendChild(noBreak);
	}
	
	// everything is ok
	return true;
}


/**
 * Show the calendar
 */
DatePickerControl.show = function()
{
	if (!this.displayed){
		var input = this.inputControl;
		if (input == null) return;
		if (input.disabled) return; // just in case ;)
		var top  = getObject.getSize("offsetTop", input);
		var left = getObject.getSize("offsetLeft", input);
		var calframe = document.getElementById(this.calFrameId);

		this.calContainer.style.top        = top + input.offsetHeight + this.offsetY + "px";
		this.calContainer.style.left       = left + this.offsetX + "px";
		this.calContainer.style.display    = "none";
		this.calContainer.style.visibility = "visible";
		this.calContainer.style.display    = "block";
		this.calContainer.style.height     = calframe.offsetHeight;
		if (this.calBG){ // the ugly patch for IE
			this.calBG.style.top        = this.calContainer.style.top;
			this.calBG.style.left       = this.calContainer.style.left;
			this.calBG.style.display    = "none";
			this.calBG.style.visibility = "visible";
			this.calBG.style.display    = "block";
			this.calBG.style.width      = this.calContainer.offsetWidth;
			if (calframe){
				this.calBG.style.height = calframe.offsetHeight;
			}
		}
		this.displayed = true;
		input.focus();
	}
}


/**
 * Hide the calendar
 */
DatePickerControl.hide = function()
{
	if (this.displayed){
		this.calContainer.style.visibility = "hidden";
		this.calContainer.style.left = -1000; // some problems with overlaped controls
		this.calContainer.style.top = -1000;
		if (this.calBG){ // the ugly patch for IE
			this.calBG.style.visibility = "hidden";
			this.calBG.style.left = -1000;
			this.calBG.style.top = -1000;
		}
		this.inputControl.value = this.originalValue;
		this.displayed = false;
	}
}


/**
 * Gets the name of a numbered month
 */
DatePickerControl.getMonthName = function(monthNumber)
{
	return this.Months[monthNumber];
}


/**
 * Obtains the days of a given month and year
 */
DatePickerControl.getDaysOfMonth = function(monthNo, p_year)
{
	if (this.isLeapYear(p_year)){
		return this.lDOMonth[monthNo];
	}
	else{
		return this.DOMonth[monthNo];
	}
}


/**
 * Will return an 1-D array with 1st element being the calculated month
 * and second being the calculated year after applying the month increment/decrement 
 * as specified by 'incr' parameter. 'incr' will normally have 1/-1 to navigate thru 
 * the months.
 */
DatePickerControl.calcMonthYear = function(p_Month, p_Year, incr)
{
	var ret_arr = new Array();

	if (incr == -1) {
		if (p_Month == 0) {
			ret_arr[0] = 11;
			ret_arr[1] = parseInt(p_Year) - 1;
		}
		else {
			ret_arr[0] = parseInt(p_Month) - 1;
			ret_arr[1] = parseInt(p_Year);
		}
	} 
	else if (incr == 1) {
		if (p_Month == 11) {
			ret_arr[0] = 0;
			ret_arr[1] = parseInt(p_Year) + 1;
		}
		else {
			ret_arr[0] = parseInt(p_Month) + 1;
			ret_arr[1] = parseInt(p_Year);
		}
	}

	return ret_arr;
}


/**
 * Gets the DatePickerControl HTML code
 */
DatePickerControl.getAllCode = function()
{
	var vCode = "";
	vCode += "<table class='calframe' id='" + this.calFrameId + "'>";
	vCode += this.getHeaderCode();
	vCode += this.getDaysHeaderCode();
	vCode += this.getDaysCode();
	vCode += "</table>";
	return vCode;
}


/**
 * The title and nav buttons
 */
DatePickerControl.getHeaderCode = function()
{
	var prevMMYYYY = this.calcMonthYear(this.month, this.year, -1);
	var prevMM = prevMMYYYY[0];
	var prevYYYY = prevMMYYYY[1];

	var nextMMYYYY = this.calcMonthYear(this.month, this.year, 1);
	var nextMM = nextMMYYYY[0];
	var nextYYYY = nextMMYYYY[1];

	var gNow = new Date();
	var vCode = "";
	
	var numberCols = this.weekNumber ? 8 : 7;

	vCode += "<tr><td colspan='" + numberCols + "' class='monthDisplay'>";
	vCode += this.monthName + "&nbsp;&nbsp;";

	vCode += "<span title='" + this.Months[this.month] + " " + (parseInt(this.year)-1) + "' class='yearbutton' ";
	vCode += "onclick='DatePickerControl.build(" + this.month + ", " + (parseInt(this.year)-1)+");return false;'>&laquo;</span>";
	vCode += "&nbsp;" + this.year + "&nbsp;";

	vCode += "<span title='" + this.Months[this.month] + " " + (parseInt(this.year)+1) + "' class='yearbutton' ";
	vCode += "onclick='DatePickerControl.build(" + this.month + ", " + (parseInt(this.year)+1) + ");return false;'>&raquo;</span>";
	vCode += "</td></tr>";

	vCode += "<tr><td style='border-width:0px' colspan='" + numberCols + "'>";
	vCode += "<table class='navigation' width='100%'><tr>";

	vCode += "<td class='navbutton' title='" + this.Months[prevMM] + " " + prevYYYY + "' ";
	vCode += "onclick='DatePickerControl.build(" + prevMM + ", " + prevYYYY + ");return false;'>&lt;&lt;</td>";

	vCode += "<td class='navbutton' title='" + gNow.getDate() + " " + this.Months[gNow.getMonth()] + " " + gNow.getFullYear() + "' ";
	vCode += "onclick='DatePickerControl.build(" + gNow.getMonth() + ", " + gNow.getFullYear() + ");DatePickerControl.selectToday();return false;'>";
	vCode += this.todayText + "</td>";

	vCode += "<td class='navbutton' title='" + this.Months[nextMM] + " " + nextYYYY + "' ";
	vCode += "onclick='DatePickerControl.build(" + nextMM + ", " + nextYYYY +	");return false;'>&gt;&gt;</td>";

	vCode += "</tr></table>";
	vCode += "</td></tr>";

	return vCode;
}


/**
 * The days' name headers
 */
DatePickerControl.getDaysHeaderCode = function()
{
	var vCode = "";

	vCode = vCode + "<tr>";
	if (this.weekNumber){
		vCode += "<td class='weeknumber'>&nbsp;</td>"
	}
	for (i=this.firstWeekDay; i<this.firstWeekDay+7; i++){
		vCode += "<td class='daysOfWeek' width='10%'>" + this.Days[i % 7] + "</td>";
	}
	vCode = vCode + "</tr>";

	return vCode;
}


/**
 * The days numbers code
 */
DatePickerControl.getDaysCode = function()
{
	var vDate = new Date();
	vDate.setDate(1);
	vDate.setMonth(this.month);
	vDate.setFullYear(this.year);

	var vFirstDay = vDate.getDay();
	var vDay = 1;
	var vLastDay = this.getDaysOfMonth(this.month, this.year);
	var vOnLastDay = 0;
	var vCode = "";
	this.dayOfWeek = vFirstDay;

	var prevm = this.month == 0 ? 11 : this.month-1;
	var prevy = this.prevm == 11 ? this.year - 1 : this.year;
	prevmontdays = this.getDaysOfMonth(prevm, prevy);
	vFirstDay = (vFirstDay == 0 && this.firstWeekDay) ? 7 : vFirstDay;
	
	if (this.weekNumber){
		var week = this.getWeekNumber(this.year, this.month, 1);
	}
	vCode += "<tr>";
	if (this.weekNumber){
		vCode += "<td class='weeknumber'>" + week + "</td>";
	}
	
	// Write the last days of previous month
	for (i=this.firstWeekDay; i<vFirstDay; i++) {
		vCode = vCode + "<td class='dayothermonth'>" + (prevmontdays-vFirstDay+i+1) + "</td>";
	}

	// Write rest of the 1st week
	for (j=vFirstDay-this.firstWeekDay; j<7; j++) {
		if (this.isInRange(vDay)){
			classname = this.getDayClass(vDay, j);
			vCode += "<td class='" + classname + "' class_orig='" + classname + "' " +
				"onClick='DatePickerControl.writeDate(" + vDay + ")' id='" + this.dayIdPrefix + vDay + "'>" + vDay + "</td>";
		}

		else{
			vCode += "<td class='dayothermonth'>" + vDay + "</td>";
		}
		vDay++;
	}
	vCode = vCode + "</tr>";

	// Write the rest of the weeks
	for (k=2; k<7; k++){
		vCode = vCode + "<tr>";
		if (this.weekNumber){
			week++;
			if (week >= 53) week = 1;
			vCode += "<td class='weeknumber'>" + week + "</td>";
		}
		for (j=0; j<7; j++){
			if (this.isInRange(vDay)){
				classname = this.getDayClass(vDay, j);
				vCode += "<td class='" + classname  + "' class_orig='" +  classname + "' " +
					"onClick='DatePickerControl.writeDate(" + vDay + ")' id='" + this.dayIdPrefix + vDay + "'>" + vDay + "</td>";
			}
			else{
				vCode += "<td class='dayothermonth'>" + vDay + "</td>";
			}
			vDay++;
			if (vDay > vLastDay){
				vOnLastDay = 1;
				break;
			}
		}

		if (j == 6)
			vCode += "</tr>";
		if (vOnLastDay == 1)
			break;
	}

	// Fill up the rest of last week
	for (m=1; m<(7-j); m++){
		vCode += "<td class='dayothermonth'>" + m + "</td>";
	}

	return vCode;
}


/**
 * Get the class according if is 'today', the 'current' date at the control,
 * a 'weekend' day, or a 'normal' day.
 * @param vday The number of the day in the current month and year
 * @param dayofweek The number of the day within the week (0..6)
 */
DatePickerControl.getDayClass = function(vday, dayofweek)
{
	var gNow      = new Date();
	var vNowDay   = gNow.getDate();
	var vNowMonth = gNow.getMonth();
	var vNowYear  = gNow.getFullYear();

	if (vday == vNowDay && this.month == vNowMonth && this.year == vNowYear){
		return "today";
	}
	else{
		// transform the day acording the specified firts day of week
		var realdayofweek = (7 + dayofweek + this.firstWeekDay) % 7;
		for (i=0; i<this.weekend.length; i++){
			if (realdayofweek == this.weekend[i]){
				return "bookableDay";
			}
		}
		return "bookableDay";
	}
}


/**
 * Gets the date string according to calendar's format
 * @param p_day The number of the day in the current month and year
 */
DatePickerControl.formatData = function(p_day)
{
	var vData;
	var vMonth = 1 + this.month;
	vMonth = (vMonth.toString().length < 2) ? "0" + vMonth : vMonth;
	var vMon = this.getMonthName(this.month).substr(0,3).toUpperCase();
	var vFMon = this.getMonthName(this.month).toUpperCase();
	var vY4 = new String(this.year);
	var vY2 = new String(this.year).substr(2,2);
	var vDD = (p_day.toString().length < 2) ? "0" + p_day : p_day;

	switch (this.format) {

		case "MM/DD/YYYY" :
			vData = vMonth + "/" + vDD + "/" + vY4;
			break;
		case "MM/DD/YY" :
			vData = vMonth + "/" + vDD + "/" + vY2;
			break;
		case "MM-DD-YYYY" :
			vData = vMonth + "-" + vDD + "-" + vY4;
			break;
		case "MM-DD-YY" :
			vData = vMonth + "-" + vDD + "-" + vY2;
			break;
		case "YYYY-MM-DD":
			vData = vY4 + "-" + vMonth + "-" + vDD;
			break;
		case "YYYY/MM/DD":
			vData = vY4 + "/" + vMonth + "/" + vDD;
			break;

		case "DD/MON/YYYY" :
			vData = vDD + "/" + vMon + "/" + vY4;
			break;
		case "DD/MON/YY" :
			vData = vDD + "/" + vMon + "/" + vY2;
			break;
		case "DD-MON-YYYY" :
			vData = vDD + "-" + vMon + "-" + vY4;
			break;
		case "DD-MON-YY" :
			vData = vDD + "-" + vMon + "-" + vY2;
			break;

		case "DD/MONTH/YYYY" :
			vData = vDD + "/" + vFMon + "/" + vY4;
			break;
		case "DD/MONTH/YY" :
			vData = vDD + "/" + vFMon + "/" + vY2;
			break;
		case "DD-MONTH-YYYY" :
			vData = vDD + "-" + vFMon + "-" + vY4;
			break;
		case "DD-MONTH-YY" :
			vData = vDD + "-" + vFMon + "-" + vY2;
			break;

		case "DD/MM/YYYY" :
			vData = vDD + "/" + vMonth + "/" + vY4;
			break;
		case "DD/MM/YY" :
			vData = vDD + "/" + vMonth + "/" + vY2;
			break;
		case "DD-MM-YYYY" :
			vData = vDD + "-" + vMonth + "-" + vY4;
			break;
		case "DD-MM-YY" :
			vData = vDD + "-" + vMonth + "-" + vY2;
			break;
		
		case "DD.MM.YYYY" :
			vData = vDD + "." + vMonth + "." + vY4;

			break;
		case "DD.MM.YY" :
			vData = vDD + "." + vMonth + "." + vY2;
			break;

		default :
			vData = vMonth + "/" + vDD + "/" + vY4;
	}

	return vData;
}


/**
 * Try to get the date from the control according to the format:
 * This function doesn't work with named months
 * @return An object of class Date with the current date in the control (if succesfull) or
 *  today if fails.
 */
DatePickerControl.getDateFromControl = function(ctrl)
{
	if (ctrl == null) ctrl = this.inputControl;
	var value = ctrl.value;
	var format = ctrl.getAttribute("datepicker_format");
	return this.getDateFromString(value, format.toString());
}


/**
 * Gets a Date objects from a string given a format.
 * @param strdate The string with the date.
 * @param format The date's format.
 * @return A Date object with the date of string according to the format, or
 * today if string is empty or non-valid.
 */
DatePickerControl.getDateFromString = function(strdate, format) 
{
	var aDate = new Date();
	var day, month, year;
	
	if (strdate == "" || format == "") return aDate;
	strdate = strdate.replace("/", "@").replace("/", "@");
	strdate = strdate.replace("-", "@").replace("-", "@");
	strdate = strdate.replace(".", "@").replace(".", "@");
	// check again
	if (strdate.indexOf("/")>=0 || strdate.indexOf("-")>=0 || strdate.indexOf(".")>=0) return aDate;
	// validate all other stuff
	var data = strdate.split("@");
	if (data.length != 3) return aDate;
	for (i=0; i<3; i++){
		data[i] = parseFloat(data[i]);
		if (isNaN(data[i])) return aDate;
	}
	aDate.setDate(1);
	if (format.substring(0,1).toUpperCase() == "D"){
		aDate.setFullYear(this.yearTwo2Four(data[2]));
		aDate.setMonth(data[1]-1);
		aDate.setDate(data[0]);
	}
	else if (format.substring(0,1).toUpperCase() == "Y"){
		aDate.setFullYear(this.yearTwo2Four(data[0]));
		aDate.setMonth(data[1]-1);
		aDate.setDate(data[2]);
	}
	else if (format.substring(0,1).toUpperCase() == "M"){
		aDate.setFullYear(this.yearTwo2Four(data[2]));
		aDate.setMonth(data[0]-1);
		aDate.setDate(data[1]);
	}
	return aDate;
}


/**
 * Transform a two digits year into a four digits year.
 * All year from 30 to 99 are trated as 19XX, year before
 * 30 are trated as 20XX
 */
DatePickerControl.yearTwo2Four = function(year)
{
	if (year < 99){
		if (year >= 30){
			year += 1900;
		}
		else{
			year += 2000;
		}
	}
	return year;
}
 

/**
 * Writes the specified date in the control and close the calendar.
 */
DatePickerControl.writeDate = function(day)
{
	var d = this.formatData(day);
	this.inputControl.value = d;
	this.originalValue = d;
	this.hide();
	if (DatePickerControl.onSelect) DatePickerControl.onSelect(this.inputControl.id);
	this.firstFocused = true;
	this.inputControl.focus();
}


/**
 * Writes the current date in the control
 */
DatePickerControl.writeCurrentDate = function()
{
	var d = this.formatData(this.currentDay);
	this.inputControl.value = d;
}


/**
 * Creates and write the calendar's code
 * @param m The month to build
 * @param y The year to build
 */
DatePickerControl.build = function(m, y)
{
	var bkm = this.month;
	var bky = this.year;
	var calframe = document.getElementById(this.calFrameId);
	if (m==null){
		var now = new Date();
		this.month = now.getMonth();
		this.year  = now.getFullYear();
	}
	else{
		this.month = m;
		this.year  = y;
	}
	// validate range
	if (!this.isInRange(null)){
		this.month = bkm;
		this.year  = bky;
	}
	if (!this.isInRange(this.currentDay)){
		if (this.minDate && this.currentDay < this.minDate.getDate()) this.currentDay = this.minDate.getDate();
		if (this.maxDate && this.currentDay > this.maxDate.getDate()) this.currentDay = this.maxDate.getDate();
	}
	this.monthName = this.Months[this.month];
	var code = this.getAllCode();
	writeLayer(this.calContainer.id, null, code);
	if (this.calContainer && calframe) this.calContainer.style.height = calframe.offsetHeight;
	this.firstFocused = true;
	this.inputControl.focus();
	this.selectDay(this.currentDay);
}


/**
 * Build the prev month calendar
 */
DatePickerControl.buildPrev = function()
{
	if (!this.displayed) return;
	var prevMMYYYY = this.calcMonthYear(this.month, this.year, -1);
	var prevMM = prevMMYYYY[0];
	var prevYYYY = prevMMYYYY[1];
	this.build(prevMM, prevYYYY);
}


/**
 * Build the next month calendar
 */
DatePickerControl.buildNext = function()
{
	if (!this.displayed) return;
	var nextMMYYYY = this.calcMonthYear(this.month, this.year, 1);
	var nextMM = nextMMYYYY[0];
	var nextYYYY = nextMMYYYY[1];
	this.build(nextMM, nextYYYY);
}


/**
 * Today button action
 */
DatePickerControl.selectToday = function()
{
	var now = new Date();
	var today = now.getDate();
	if (!this.isInRange(today)) return;
	if (this.closeOnTodayBtn){
		this.currentDay = today;
		this.writeDate(this.currentDay);
	}
	else{
		this.selectDay(today);
	}
}


/**
 * Select a specific day
 */
DatePickerControl.selectDay = function(day)
{
	if (!this.displayed) return;
	if (!this.isInRange(day)){
		return;
	}
	var n = this.currentDay;
	var max = this.getDaysOfMonth(this.month, this.year);
	if (day > max) return;
	var newDayObject = document.getElementById(this.dayIdPrefix+day);
	var currentDayObject = document.getElementById(this.dayIdPrefix+this.currentDay);
	if (currentDayObject){
		currentDayObject.className = currentDayObject.getAttribute("class_orig");
	}
	if (newDayObject){
		newDayObject.className = "current";
		this.currentDay = day;
		this.writeCurrentDate();
	}
}


/**
 * Select the prev week day
 * @param decr Use 1 for yesterday or 7 for prev week
 */
DatePickerControl.selectPrevDay = function(decr)
{
	if (!this.displayed) return;
	var n = this.currentDay;
	var max = this.getDaysOfMonth(this.month, this.year);
	var prev = n - decr;
	if ( prev <= 0 ){
		if (decr == 7){
			n = (n + this.dayOfWeek) + 28 - this.dayOfWeek;
			n--;
			prev = n > max ? n-7 : n;
		}
		else{
			prev = max;
		}
	}
	this.selectDay(prev);
}


/**
 * Select the next week day
 * @param decr Use 1 for tomorrow or 7 for next week
 */
DatePickerControl.selectNextDay = function(incr)
{
	if (!this.displayed) return;
	var n = this.currentDay;
	var max = this.getDaysOfMonth(this.month, this.year);
	var next = n + incr;
	if ( next > max ){
		if (incr == 7){
			n = ((n + this.dayOfWeek) % 7) - this.dayOfWeek;
			next = n < 0 ? n+7 : n;
			next++;
		}
		else{
			next = 1;
		}
	}
	this.selectDay(next);
}


/**
 * Show the calendar for an edit control
 */
DatePickerControl.showForEdit = function(edit)
{
	if (this.displayed) return;
	if (edit == null) return;
	if (edit.disabled) return;
	this.inputControl  = edit;
	this.originalValue = edit.value;
	this.setupRange();
	// the format
	var format = this.inputControl.getAttribute("datepicker_format");
	if (format == null) format = this.defaultFormat;
	this.format = format;
	// build with the current date in the control?
	if (this.validate(edit.value, format)){
		var date = this.getDateFromControl();
		this.currentDate = date;
		this.build(date.getMonth(), date.getFullYear());
		this.currentDay  = date.getDate();
	}
	else{
		edit.value = "";
		this.originalValue = "";
		this.currentDate = null;
		if (this.defaultTodaySel){
			this.currentDay = new Date().getDate();
		}
		else{
			this.currentDay = 1;
		}
		this.build(null, null);
	}
	var currentDayObject = document.getElementById(this.dayIdPrefix+this.currentDay);
	if (currentDayObject) currentDayObject.className = "current";
	this.writeCurrentDate();
	// and finally
	this.show();
}


/** 
 * Determine if a given day (with current month and year) is in range
 * according to the min and max limit.
 * @param day The number of the day; if null then the current month is validated.
 */
DatePickerControl.isInRange = function(day)
{
	if (!this.minDate && !this.maxDate) return true;
	if (day){
		var aDate = new Date();
		aDate.setFullYear(this.year);
		aDate.setMonth(this.month);
		aDate.setDate(day);
		if (this.minDate){
			if (this.compareDates(aDate, this.minDate) < 0) return false;
		}
		if (this.maxDate){
			if (this.compareDates(aDate, this.maxDate) > 0) return false;
		}
	}
	else{ // validate only the month.
		var currentym = parseInt(this.year.toString() + (this.month < 10 ? "0"+this.month.toString() : this.month.toString()));
		var m;
		if (this.minDate){
			m = this.minDate.getMonth();
			var minym = parseInt(this.minDate.getFullYear().toString() + (m < 10 ? "0"+m.toString() : m.toString()));
			if (currentym < minym) return false;
		}
		if (this.maxDate){
			m = this.maxDate.getMonth();
			var maxym = parseInt(this.maxDate.getFullYear().toString() + (m < 10 ? "0"+m.toString() : m.toString()));
			if (currentym > maxym) return false;
		}
	}
	return true;
}


/**
 *
 */
DatePickerControl.setupRange = function()
{
	// get the date range
	var edit = this.inputControl;
	var format = edit.getAttribute("datepicker_format");
	var min = edit.getAttribute("datepicker_min");
	this.minDate = min ? this.getDateFromString(min, format) : null;
	var max = edit.getAttribute("datepicker_max");
	this.maxDate = max ? this.getDateFromString(max, format) : null;
	if (this.maxDate && this.minDate){
		if (this.maxDate.getTime() < this.minDate.getTime()){
			var tmp = this.maxDate;
			this.maxDate = this.minDate;
			this.minDate = tmp;
		}
	}
}


/**
 * Compare two dates. We cannot use Date getTime() mehtod  in some specific cases,
 * so we use a trick with the string year+month+day transformed in a number.
 * @return '<0' if d1 < d2     '0' if d1 = d2     '>0' if d1 > d2
 */
DatePickerControl.compareDates = function(d1, d2)
{
	var m = d1.getMonth();
	var d = d1.getDate();
	var s1 = d1.getFullYear().toString() + (m<10 ? "0"+m.toString() : m.toString()) + (d<10 ? "0"+d.toString() : d.toString());
	m = d2.getMonth();
	d = d2.getDate();
	var s2 = d2.getFullYear().toString() + (m<10 ? "0"+m.toString() : m.toString()) + (d<10 ? "0"+d.toString() : d.toString());
	var n1 = parseInt(s1);
	var n2 = parseInt(s2);
	return n1-n2;
}


/**
 * Validate a string according to a date format.
 * Portions of code from: http://www.rgagnon.com/jsdetails/js-0063.html
 * @param strdate The string with the date.
 * @param format The format to validate.
 * @return true if succesfull or false otherwise
 */
DatePickerControl.validate = function(strdate, format)
{
	var dateRegExp;
	var separator;
	var d, m, y;
	var od = this.currentDay, om = this.month, oy = this.year;
	
	if (strdate == "") return false;
	
	// use the correct regular expresion...
	if (format.substring(0,1).toUpperCase() == "D"){
		dateRegExp = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{2,4}$/
	}
	else if (format.substring(0,1).toUpperCase() == "Y"){
		dateRegExp = /^\d{2,4}(\-|\/|\.)\d{1,2}\1\d{1,2}$/
	}
	else if (format.substring(0,1).toUpperCase() == "M"){
		dateRegExp = /^\d{1,2}(\-|\/|\.)\d{1,2}\1\d{2,4}$/
	}

	// is ok at least with the format?
	if (!dateRegExp.test(strdate)){
		return false;
	}
	
	// chek for a valid day month day combination
	separator = (strdate.indexOf("/") > 1) ? "/" : ((strdate.indexOf("-") > 1) ? "-" : ".");
	var datearray = strdate.split(separator);
	
	// get the number of date elements
	if (format.substring(0,1).toUpperCase() == "D"){
		d = parseFloat(datearray[0]);
		m = parseFloat(datearray[1]);
		y = parseFloat(datearray[2]);
	}
	else if (format.substring(0,1).toUpperCase() == "Y"){
		d = parseFloat(datearray[2]);
		m = parseFloat(datearray[1]);
		y = parseFloat(datearray[0]);
	}
	else if (format.substring(0,1).toUpperCase() == "M"){
		d = parseFloat(datearray[1]);
		m = parseFloat(datearray[0]);
		y = parseFloat(datearray[2]);
	}	
	// is a valid month?
	if (m<1 || m>12) return false;
	//check if month value and day value agree
	if (d > this.getDaysOfMonth(m-1, y)) return false;
	
	// ok, date is valid... but is it in range?
	this.month = m;
	this.year  = y;
	var res = this.isInRange(d);
	this.month = om;
	this.year  = oy;
	return res;
}


/**
 * Check if a year is leap:
 * 1.Years evenly divisible by four are normally leap years, except for...
 * 2.Years also evenly divisible by 100 are not leap years, except for...
 * 3.Years also evenly divisible by 400 are leap years.
 * @return true if the year is leap or false otherwise.
 */
DatePickerControl.isLeapYear = function(year)
{
	if ((year % 4) == 0){
		if ((year % 100) == 0 && (year % 400) != 0){
			return false;
		}
		return true;
	}
	return false;
}


/**
 * Click event for calendar button
 */
function DPC_onButtonClick(event){DatePickerControl.onButtonClick(event);}
DatePickerControl.onButtonClick = function(event)
{
	if (!this.displayed){
		// get the button
		if (event == null) event = window.event;
		var button = (event.srcElement) ? event.srcElement : event.originalTarget;
		// gets the associated input:
		var input = document.getElementById(button.getAttribute("datepicker_inputid"));
		this.showForEdit(input);
	}
	else{
		this.hide();
	}
}


/**
 * Click event for calendar layer.
 */
function DPC_onContainerClick(event){DatePickerControl.onContainerClick(event);}
DatePickerControl.onContainerClick = function(event)
{
	if (event == null) event = window.event;
	if (this.hideTimeout){
		clearTimeout(this.hideTimeout);
		this.hideTimeout = null;
	}
	this.inputControl.focus();
	return false;
}


/**
 * Key-up event for edit controls as date-pickers
 */
function DPC_onEditControlKeyUp(event){DatePickerControl.onEditControlKeyUp(event);}
DatePickerControl.onEditControlKeyUp = function(event)
{
	if (event == null) event = window.event;
	var edit = event.srcElement ? event.srcElement : event.originalTarget;
	var kc   = event.charCode ? event.charCode : event.which ? event.which : event.keyCode;
	switch (kc){
		case 37: // left arrow key
			this.selectPrevDay(1);
			break;

		case 38: // up arrow key
			this.selectPrevDay(7);
			break;

		case 39: // right arrow key
			this.selectNextDay(1);
			break;

		case 40: // down arrow key
			if (!this.displayed){
				this.showForEdit(edit);
			}
			else{
				this.selectNextDay(7);
				break;
			}
			break;

		case 27: // escape key
			this.hide();
			break;

		case 33: // repag key
			if ((event.modifiers & Event.SHIFT_MASK) || (event.shiftKey)){
				this.build(this.month, parseInt(this.year)-1);
			}
			else{
				this.buildPrev();
			}
			break;

		case 34: // avpag key
			if ((event.modifiers & Event.SHIFT_MASK) || (event.shiftKey)){
				this.build(this.month, parseInt(this.year)+1);
			}
			else{
				this.buildNext();
			}
			break;

		case 13: // enter-key (forms without submit buttons)
			if (this.displayed && this.currentDay > 0 && this.submitByKey){
				this.writeDate(this.currentDay);
			}
			break;
	}
	return false;
}


/**
 * Key-down event for edit controls as date-pickers
 */
function DPC_onEditControlKeyDown(event){DatePickerControl.onEditControlKeyDown(event);}
DatePickerControl.onEditControlKeyDown = function(event)
{
	if (event == null) event = window.event;
	var edit = event.srcElement ? event.srcElement : event.originalTarget;
	var kc   = event.charCode ? event.charCode : event.which ? event.which : event.keyCode;
	if ( kc >= 65 && kc <= 90 ){ // letters
		if (event.stopPropagation) event.stopPropagation();
		if (event.preventDefault)  event.preventDefault();
		event.returnValue  = false;
		event.cancelBubble = true;
		return false;
	}	
	switch (kc){
		case 13: // enter key
			this.submitByKey = true;
			break;
		case 9:  // tab key
		case 32: // space-bar key
			if (this.displayed && this.currentDay > 0){
				this.writeDate(this.currentDay);
			}
			break;
	}
}


/**
 * Key-press event for edit controls as date-pickers
 */
function DPC_onEditControlKeyPress(event){DatePickerControl.onEditControlKeyPress(event);}
DatePickerControl.onEditControlKeyPress = function(event)
{
	if (event == null) event = window.event;
	var edit = event.srcElement ? event.srcElement : event.originalTarget;
	var kc   = event.charCode ? event.charCode : event.which ? event.which : event.keyCode;
	if (!((kc < 32) || (kc > 44 && kc < 58))){
		if (event.stopPropagation) event.stopPropagation();
		if (event.preventDefault)  event.preventDefault();
		event.returnValue  = false;
		event.cancelBubble = true;
		return false;
	}	
}


/**
 * Blur event for edit controls as date-pickers
 */
function DPC_onEditControlBlur(event){DatePickerControl.onEditControlBlur(event);}
DatePickerControl.onEditControlBlur = function(event)
{
	if (event == null) event = window.event;
	if (!this.hideTimeout){
		this.hideTimeout = setTimeout("DatePickerControl.hide()", this.HIDE_TIMEOUT);
	}
	this.firstFocused  = false;
	this.hideCauseBlur = true;
}


/**
 * Change event for edit controls as date-pickers
 */
function DPC_onEditControlChange(event){DatePickerControl.onEditControlChange(event);}
DatePickerControl.onEditControlChange = function(event)
{
	if (event == null) event = window.event;
	var edit = (event.srcElement) ? event.srcElement : event.originalTarget;
	if (edit.value == "") return;
	var format = edit.getAttribute("datepicker_format");
	if (!this.validate(edit.value, format)){
		setTimeout("e = document.getElementById('"+edit.id+"'); e.value=''; e.focus()", 10);
	}
}


/**
 * Focus event for edit controls as date-pickers
 */
function DPC_onEditControlFocus(event){DatePickerControl.onEditControlFocus(event);}
DatePickerControl.onEditControlFocus = function(event)
{
	if (event == null) event = window.event;
	var edit = (event.srcElement) ? event.srcElement : event.originalTarget;
	
	this.inputControl  = edit;
	this.originalValue = edit.value;
	this.setupRange();
	
	if ((!this.displayed || this.hideCauseBlur) && this.autoShow && !this.firstFocused){
		clearTimeout(this.hideTimeout);
		this.hideTimeout   = null;
		this.firstFocused  = true;
		if (this.hideCauseBlur){
			this.hideCauseBlur = false;
			this.hide();
		}
		this.showForEdit(edit);
	}
	else if (this.inputControl && this.inputControl.id != edit.id){
		this.hide();
	}
	else if (this.hideTimeout){
		clearTimeout(this.hideTimeout);
		this.hideTimeout = null;
	}
}


/**
 * Form's submit event
 */
function DPC_onFormSubmit(event){DatePickerControl.onFormSubmit(event);}
DatePickerControl.onFormSubmit = function(event)
{
	if (this.submitByKey){
		this.submitByKey = false;
		if (this.displayed && this.currentDay > 0){
			this.writeDate(this.currentDay);
			if (event == null) event = window.event;
			var theForm = (event.srcElement) ? event.srcElement : event.originalTarget;
			if (event.stopPropagation) event.stopPropagation();
			if (event.preventDefault)  event.preventDefault();
			event.returnValue  = false;
			event.cancelBubble = true;
			return false;
		}
	}
	this.reformatOnSubmit();
}


/** 
 * Reformat all dates to the current onSubmit date format
 */
DatePickerControl.reformatOnSubmit = function()
{
	if (this.submitFormat == "") return true;
	var inputControls = document.getElementsByTagName("input"); 
	var inputsLength  = inputControls.length;
	var i;
	for (i=0; i<inputsLength; i++){
		if (inputControls[i].type.toLowerCase() == "text"){
			var editctrl  = inputControls[i];
			if (editctrl.value == "") continue;
			var isdpc = editctrl.getAttribute("isdatepicker");
			if (isdpc && isdpc == "true"){
				var thedate = this.getDateFromControl(editctrl);
				var res = this.submitFormat.replace("DD", thedate.getDate());
				var mo  = thedate.getMonth() + 1;
				res = res.replace("MM", mo.toString());
				if (this.submitFormat.indexOf("YYYY") >= 0){
					res = res.replace("YYYY", thedate.getFullYear());
				}
				else{
					res = res.replace("YY", thedate.getFullYear());
				}
				editctrl.value = res;
			}
		}
	}
	return true;
}


/**
 * Replacement for submit method of the form.
 */
function DPC_formSubmit()
{
	var res = DatePickerControl.reformatOnSubmit();
	if (this.submitOrig){
		res = this.submitOrig();
	}
	return res;
}


/**
 * Window resize event.
 */
function DPC_onWindowResize(event){DatePickerControl.onWindowResize(event);}
DatePickerControl.onWindowResize = function(event)
{
	this.relocate();
	//this.relocateButtons();
}


/**
 * Relocate buttons
 */
DatePickerControl.relocateButtons = function()
{
	return;
	var divElements = document.getElementsByTagName("div");
	for (key in divElements){
		if (divElements[key].id && divElements[key].id.indexOf(this.buttonIdPrefix) == 0){
			var calButton = divElements[key];
			if (calButton.style.display == 'none') continue;
			var input = document.getElementById(calButton.getAttribute("datepicker_inputid"));
			if (input.style.display == 'none' || input.offsetTop == 0) continue;
			var nTop = getObject.getSize("offsetTop", input);
			var nLeft = getObject.getSize("offsetLeft", input);
			calButton.style.top = (nTop + Math.floor((input.offsetHeight-calButton.offsetHeight)/2) + this.buttonOffsetY) + "px";
			var btnOffX         = Math.floor((input.offsetHeight - calButton.offsetHeight) / 2);
			if (this.buttonPosition == "in"){
				calButton.style.left = (nLeft + input.offsetWidth - calButton.offsetWidth - btnOffX + this.buttonOffsetX) + "px";
			}
			else{ // "out"
				calButton.style.left = (nLeft + input.offsetWidth + btnOffX + this.buttonOffsetX) + "px";
			}
		}
	}
}


/**
 * Relocate the calendar's frame
 */
DatePickerControl.relocate = function()
{
	if (this.displayed){
		var input = this.inputControl;
		if (input == null) return;
		var top  = getObject.getSize("offsetTop", input);
		var left = getObject.getSize("offsetLeft", input);
		this.calContainer.style.top  = top + input.offsetHeight + this.offsetY + "px";
		this.calContainer.style.left = left + this.offsetX + "px";
		if (this.calBG){ // the ugly patch for IE
			this.calBG.style.top  = this.calContainer.style.top;
			this.calBG.style.left = this.calContainer.style.left;
		}
	}
}


/**
 * Gets the number of the week on the year for the given year, month, day.
 */
DatePickerControl.getWeekNumber = function(year, month, day) 
{
	var when = new Date(year,month,day);
	var newYear = new Date(year,0,1);
	var offset = 7 + 1 - newYear.getDay();
	if (offset == 8) offset = 1;
	var daynum = ((Date.UTC(y2k(year),when.getMonth(),when.getDate(),0,0,0) - Date.UTC(y2k(year),0,1,0,0,0)) /1000/60/60/24) + 1;
	var weeknum = Math.floor((daynum-offset+7)/7);
	if (weeknum == 0) {
		year--;
		var prevNewYear = new Date(year,0,1);
		var prevOffset = 7 + 1 - prevNewYear.getDay();
		if (prevOffset == 2 || prevOffset == 8) weeknum = 53; else weeknum = 52;
	}
	return weeknum;
}

function y2k(number) { return (number < 1000) ? number + 1900 : number; }


function getObject(sId)
{
	if (bw.dom){
		this.hElement = document.getElementById(sId);
		this.hStyle = this.hElement.style;
	}
	else if (bw.ns4){
		this.hElement = document.layers[sId];
		this.hStyle = this.hElement;
	}
	else if (bw.ie){
		this.hElement = document.all[sId];
		this.hStyle = this.hElement.style;
	}
}

getObject.getSize = function(sParam, hLayer)
{
	nPos = 0;
	while ((hLayer.tagName) && !( /(body|html)/i.test(hLayer.tagName))){
		nPos += eval('hLayer.' + sParam);
		if (sParam == 'offsetTop'){
			if (hLayer.clientTop){
				nPos += hLayer.clientTop;
			}
		}
		if (sParam == 'offsetLeft'){
			if (hLayer.clientLeft){
				nPos += hLayer.clientLeft;
			}
		}
		hLayer = hLayer.offsetParent;
	}
	return nPos;
}


function writeLayer(ID, parentID, sText)
{
	if (document.layers){
		var oLayer;
		if(parentID){
			oLayer = eval('document.' + parentID + '.document.' + ID + '.document');
		}
		else{
			oLayer = document.layers[ID].document;
		}
		oLayer.open();
		oLayer.write(sText);
		oLayer.close();
	}
	else if(document.all){
		document.all[ID].innerHTML = sText;
	}
	else{
		document.getElementById(ID).innerHTML = sText;
	}
}

