// 080605 - 5:00pm - FIX: code formatting
function firePaymentEvent(event) {
	frmMain = document.forms[1]
	frmMain.elements["action"].value=event
	frmMain.submit()
}

// this method is used to display Airplane Look up
function airplaneLookUp(keyName) {
	var url = "/ube/aircraftInfo.do"+"?keyName="+keyName; 
	var winparams = "width=539,height=500,scrollbars=yes,resizable=yes,toolbar=no,dependent=yes,location=no";
	popWin = window.open( url, 'Aircraft', winparams);  
	if(document.all){
		 if(popWin.document) {
			popWin.document.location.reload();
		 }
	}
}

function openPopUpWind(link) { 
    windowOptions = "width=539,height=270,scrollbars=yes,resizable=yes";
    openNewWindow(link, '', windowOptions ,"AirportLookup");
}

function openMPLookup(parms) {
	openMPLookup(parms,"","");
}

function openMPLookup(parms, widthParm, heightParm) {  
    urlPrefix = "/ube/articleLookup.do?";
    windowOptions = "scrollbars=yes,status=yes,resizable=yes,toolbar=yes";
    if (widthParm != "") {
       windowOptions = windowOptions + ",width="+widthParm;
    }
    if(heightParm != "") {
       windowOptions = windowOptions + ",height="+heightParm;
    }
    openNewWindow(urlPrefix, parms, windowOptions ,"ArticleLookup");
}

/** 
 * Airport lookup tool window 
 */
function openAiportLookupWin(url) {
   	var winl = retrieveTop(539, 500);
	var wint = retrieveLeft(539, 500);
	if(winl && wint){
	   popWin = window.open(url,'popDoc','width=539,height=500,top='+winl+',left='+wint+',scrollbars=yes,status=yes,resizable=yes,toolbar=no,dependent=yes','AirportLookup');
	} else {
	   popWin = window.open(url,'popDoc','width=539,height=500,scrollbars=yes,status=yes,resizable=yes,toolbar=no,dependent=yes','AirportLookup');
	}
}

function openPopupWin(url,xwid,yhit){
	var winl = retrieveTop(xwid, yhit);
	var wint = retrieveLeft(xwid, yhit);
	if(winl && wint){
	   popWin = window.open(url,'popDoc','width='+xwid+',height='+yhit+',top='+winl+',left='+wint+',scrollbars=yes,status=yes,resizable=yes,toolbar=no,dependent=yes','PopupWindow');
	} else {
	   popWin = window.open(url,'popDoc','width='+xwid+',height='+yhit+',scrollbars=yes,status=yes,resizable=yes,toolbar=no,dependent=yes','PopupWindow');
	}
}

/**
 * Utility method to retive top and  left position to display popup window.
 * This should take care of positioning window based the size of parent window.
 * If the size of parent window is less than popup window, then display popup
 * in default position. Otherwise make sure popup is displayed on the top of 
 * parent window ( center ).
 * Find the width and height of parent window.
 * 1. if parent window is smaller than popup than do nothing.
 * 2. Find difference of parent window and popup. Divide the differce by 2
 *    that will will be top or left depending on whether we are dealing with width or height.
 *  screenX, screenY
 * @parm pWidth popup width
 * @parm pHeight popup height
 */
function retrieveTop(pWidth, pHeight){
	var rv; // = 0;
	try {
		var parentWinHt;// = window.outerheight;
		if (self.innerWidth){
			parentWinHt = self.innerHeight;
		}
		else if (document.documentElement && document.documentElement.clientWidth){
			parentWinHt = document.documentElement.clientHeight;
		}
		else if (document.body){
			parentWinHt = document.body.clientHeight;
		}
		if(parentWinHt > pHeight){
			rv = (parentWinHt - pHeight)/2;
		}
	} catch(e) {
		//ignore    
	}
	return rv;
}

function retrieveLeft(pWidth, pHeight){
	var rv; // = 0;
	try{
		var parentWinWdth;// = window.outerheight;
		if (self.innerWidth){
			parentWinWdth = self.innerWidth;
		}
		else if (document.documentElement && document.documentElement.clientWidth){
			parentWinWdth = document.documentElement.clientWidth;
		}
		else if (document.body){
			parentWinWdth = document.body.clientWidth;
		}
		if(parentWinWdth > pWidth){
			rv = (parentWinWdth - pWidth)/2;
		}
	}catch(e){
		//ignore
	}
	return rv;
}

/** The window size and other attributes will be set here.
 * The reason we are passing in URL is, if we change the module or web app name it
 * will be automatically taken care of as we are using JSTL tags to compose URL
 */
function openDecodeWin(url){
   var winl; // = retrieveTop(539, 400);
   var wint; // = retrieveLeft(539, 400);
   if(winl && wint){
	   openNewWindow(url,'', 'width=539,height=400,top='+winl+',left='+wint+',scrollbars=yes,status=yes,resizable=yes,dependent=yes', 'AiportDecode');
   } else {
	   openNewWindow(url,'', 'width=539,height=400,scrollbars=yes,status=yes,resizable=yes,dependent=yes', 'AiportDecode');
   }   
}

function showMap(url, country, address, city, state, zipcode) {
  var lUrl = "";
  alert('not used any more');
}

function openNewWindow(url, parms, windowOptions, descr) {  
    urlPrefix = url;
    if (parms != ""){
      urlPrefix = urlPrefix + parms;
    }
    popWin = window.open(urlPrefix,descr,windowOptions);
    popWin.focus();
}

/*From Airport search lookup the aiport selected by user will be set in parent
 * window.
 */
function returnSelection(orginFormName, originFieldName, selectedValue) {
   // if selectedValue is not passed ( default case) and there is a search result set
   // available then iterate and find selected airportmetrocode
   if (selectedValue == "" && document.airportSearchResultsForm.airportCode){
       // obtain it from the form
		if(document.airportSearchResultsForm.airportCode.length > 1){
			for(var i=0;i<document.airportSearchResultsForm.airportCode.length;i++) {
				if(document.airportSearchResultsForm.airportCode[i].checked) {
			  		selectedValue = document.airportSearchResultsForm.airportCode[i].value;
			  		break;
				}
			}
		}
		if(selectedValue == ""){
			if (document.getElementById('airportCodeStyleId0')) {
			 selectedValue = document.getElementById('airportCodeStyleId0').value;
			} 
		}
   }
   /* For some reason if the action name is dynamic in JSP, the form name is being returned as [object] */
   var foundFormField = "false";
   if(orginFormName != "" && originFieldName != ""){
   	   for(i=0; i < window.opener.document.forms.length; i++){
	      if (window.opener.document.forms[i].name == orginFormName){
	         // we found what we are looking for.
	         // now get elements.
	         for(j=0; j < window.opener.document.forms[i].elements.length; j++){
	            if(window.opener.document.forms[i].elements[j].name == originFieldName){
	               // we are lucky today or what?
	               if(selectedValue != ""){// set only if selectedValue is not empty
		               window.opener.document.forms[i].elements[j].value = selectedValue;
	               }
	               foundFormField = "true";
	               break;
	            }
	         }// end elements for loop
	         break;
	      }
	   }// end forms for loop
	   // close popup window
   }else{
      alert('Error: Origin formname and field is empty or null');
   }
   if (foundFormField == "false" && window.opener.document.forms.length > 0 &&  selectedValue != "") {
       // This is fallback case. now there are forms but we did not find the form we are looking for
       // what's up with that!
       var fieldFlag = "false";
   	   for(i=0; i < window.opener.document.forms.length; i++){
	         for(j=0; j < window.opener.document.forms[i].elements.length; j++){
	            if(window.opener.document.forms[i].elements[j].name == originFieldName){
	               window.opener.document.forms[i].elements[j].value = selectedValue;
	               fieldFlag = "true";
	               break;
	            }
	         }// end elements for loop
	         if(fieldFlag == "true"){
	             break;
	         }
	   }// end forms for loop
       
   }
   self.close();
}

/** given form name post the form*/
function submitForm(formName){	
   for(var i=0; i < document.forms.length; i++){
	  if (document.forms[i].name == formName){
		document.forms[i].submit();
		break;
	  }
   }
}

/* funtion to set days depending on selection of month*/
function dyna_days_object(sFormName, sMonth, sDay, sYear, vDayInitSelection){
	this.iFormName = document.getElementById(sFormName);
	this.iMonth = document.getElementById(sMonth);
	if(this.iMonth == null){
		this.iMonth = findGivenFormElem(sFormName, sMonth);
	}
	this.iDay = document.getElementById(sDay);
	if(this.iDay == null){
		this.iDay = findGivenFormElem(sFormName, sDay);
	}
	this.iYear = document.getElementById(sYear);
	if(this.iYear == null){
		this.iYear = findGivenFormElem(sFormName, sYear);
	}
	this.iDayInitSelection = vDayInitSelection;
}

function findGivenFormElem(sFormName, sMonth){
	rv = null;
	// scan through all elements and get the name
	for(var i=0; i < document.forms.length; i++) {
		if (document.forms[i].name == sFormName) {
			// we found what we are looking for.
			// now get elements.
			for(var j=0; j < document.forms[i].elements.length; j++) {
				if(document.forms[i].elements[j].name == sMonth) {
					rv = document.forms[i].elements[j];
					break;
				}
			}// end elements for loop
			break;
		}
	}// end forms for loop
	return rv;   
}

function DaysInMonth(WhichMonth, WhichYear) {
	var DaysInMonth = 31;
	if (WhichMonth == "4" || WhichMonth == "6" || WhichMonth == "9" || WhichMonth == "11") DaysInMonth = 30;
	if (WhichMonth == "2" && (WhichYear/4) != Math.floor(WhichYear/4))	DaysInMonth = 28;
	if (WhichMonth == "2" && (WhichYear/4) == Math.floor(WhichYear/4))	DaysInMonth = 29;
	return DaysInMonth;
}

function dyna_MPSelectedMonth() {
   var l_selected_month = 1;
   for (var i = 0; this.iMonth.options.length; i++){
      if(this.iMonth.options[i].selected){
          l_selected_month = this.iMonth.options[i].value;
          break;
      }
   }// end for loop
   return l_selected_month;
}

function dyna_MPSelectedYear() {
   var l_selected_year = 1900;
   for (var j = 0; this.iYear.options.length; j++){
      if(this.iYear.options[j].selected){
          l_selected_year = this.iYear.options[j].value;
          break;
      }
   }// end for loop
   return l_selected_year;
}

function dyna_MPSelectedDay() {
	var l_selected_day = 0;
	for (var jDy = 0; this.iDay.options.length; jDy++){
		if(this.iDay.options[jDy].selected){
			l_selected_day = this.iDay.options[jDy].value;
			break;
		}
	}// end for loop
	if (this.iDay.options.length == 1) {
		l_selected_day=this.iDayInitSelection;
	}
   return l_selected_day;
}

function dyna_days_Init() {
   // get current selected month and year.
   this.UpdateDays();
}

function dyna_days_UpdateDays() {
   // get current selected month and year.
   var l_selected_month = this.SelectedMonth();
   var l_selected_year = this.SelectedYear();
   var l_days_in_month = DaysInMonth(l_selected_month, l_selected_year);
	
   var userSelDay = this.SelectedDay();
   if (userSelDay > l_days_in_month){
       userSelDay = l_days_in_month;
   }
   var dayOptions = this.iDay.options;
   dayOptions.length = 0;

   for (var iDy = 0; iDy < l_days_in_month; iDy++){
       var temp = iDy + 1;
		 var temp2 = temp;
		 if (temp <10) {
		 	temp2 = '0'+temp;
		 }
		//alert(userSelDay+': '+temp);
       var defaultSelected = temp == userSelDay;
       dayOptions[iDy] = new Option(temp2, temp);
	   dayOptions[iDy].defaultSelected = defaultSelected;
	   dayOptions[iDy].selected = defaultSelected;
   } 
}

dyna_days_object.prototype.Init          = dyna_days_Init;
dyna_days_object.prototype.UpdateDays    = dyna_days_UpdateDays;
dyna_days_object.prototype.SelectedMonth = dyna_MPSelectedMonth;
dyna_days_object.prototype.SelectedYear  = dyna_MPSelectedYear;
dyna_days_object.prototype.SelectedDay   = dyna_MPSelectedDay;

function syncDate() {
	var fYear  = document.getElementById('fromyear').value;
	var fMonth = document.getElementById('frommonth').value;
	var fDay   = document.getElementById('fromday').value;
	var tYear  = document.getElementById('toyear').value;
	var tMonth = document.getElementById('tomonth').value;
	var tDay   = document.getElementById('todate').value;
	
	var fromDate = new Date(fYear, fMonth-1, fDay);
	var thruDate = new Date(tYear, tMonth-1, tDay);
	
	if (this.chkBrowser("msie") && this.chkBrowser("mac")) {
		var fromDate = new Date(fYear, fMonth, fDay);
		var thruDate = new Date(tYear, tMonth, tDay);
		tMonth = tMonth-1;
		tDay   = tDay-1;
	}
	
	var currDate = new Date();
	
	if (thruDate > currDate) {		
		var cYear = currDate.getYear();
		if (cYear<1000) cYear += 1900;
					
		document.getElementById('toyear').value = cYear;
		document.getElementById('tomonth').value = (currDate.getMonth()+1);
		document.getElementById('todate').value = currDate.getDate();
		if (this.chkBrowser("msie") && this.chkBrowser("mac")) {
			document.getElementById('tomonth').value = (currDate.getMonth());
			document.getElementById('todate').value = currDate.getDate()-1;
		}		
		dyna_days_objectFrom.UpdateDays();
	} 
	if (fromDate > thruDate) {		
		document.getElementById('fromyear').value = tYear;
		document.getElementById('frommonth').value = tMonth;
		document.getElementById('fromday').value = tDay;
		dyna_days_objectTo.UpdateDays();
	}
			
}

//highlight user credit card for purchase page in thelist if any.
function highlightUserCardType(list,cardType){
 	if ( (list != null ) && (cardType != null) ){
 	       for(var i=0;i<list.length; i++){
	 	        if ( cardType.toUpperCase().indexOf(list.options[i].text.toUpperCase()) >= 0 ) {
	 	        	list.selectedIndex = i;
	 	        	break;
	 	        }
 	       }
 	}
 
}

/**
 * Asynchronous request processing for Airport Lookup tool
 */
var _airportRequest;
var _isIE = false;
var _listObjectId;
var _urlOfPage;
function asyncRetrieveACLookupRes(url, parms, listType){
	_urlOfPage = url;
	if(listType == 'city'){
		_listObjectId = 'groupByCorA';
	}else{
	 	_listObjectId = 'groupByAirport';
	}
	if(window.XMLHttpRequest){
	  	_airportRequest = new XMLHttpRequest();
	}else if(window.ActiveXObject){
	  	_airportRequest = new ActiveXObject("Microsoft.XMLHTTP");
	  	_isIE = true;
	}
	if(_airportRequest){
		_airportRequest.onreadystatechange = processStateChange;
		_airportRequest.open("POST",url+parms,true);
		if(_isIE){
			_airportRequest.send();// nothing to be sent.
		}else{
			_airportRequest.send(null);// nothing to be sent.
		}
		window.status = 'Composing response...';
	} else {
		//If none of the objects are supported, may be user is using really old browser.refresh the entire page.
		var currUrl = url;
		var prefix = currUrl.substring(0, currUrl.indexOf("/aiportcityGroupBy"));
		var suffix = currUrl.substring(currUrl.indexOf("/aiportcityGroupBy") + "/aiportcityGroupBy".length, currUrl.length);
		var updatedUrl = prefix + "/aiportcitylookup" +suffix;
	  
		if (typeof tempurl =="string") {
			if (tempurl.indexOf('travel.united.com')!=-1 && tempurl.indexOf('homepage')!=-1) {
				updatedUrl = updatedUrl+'&homepage=1';
			}
		}
	  
		var formObject;
		for(i=0; i < document.forms.length; i++){
			if (document.forms[i].name == "airportSearchResultsForm"){
				formObject = document.forms[i];
				break;
			}
		}
	  formObject.action = updatedUrl;
	  formObject.submit();
	  window.status = 'Done';
	}// end else
}

/** 
 * This function will be invoked when either response is returned
 * or there is some kind of error.
 */
function processStateChange() {
    try {
		// only if req shows "loaded"
		if (_airportRequest.readyState == 4) {
			// only if "OK"
			if (_airportRequest.status == 200) {
				 updateDynaContent();
			} else {
				//alert("There was a problem retrieving response:\n" +
				//    _airportRequest.statusText);
				reloadAirportGroupByPage();
			}
	    }
    }
    catch(e) {
        // reload entire page.
        reloadAirportGroupByPage();
    }
}

/**
 * Reload entire page instead.
 */
function reloadAirportGroupByPage(){
	var currUrl    = _urlOfPage;
	var prefix     = currUrl.substring(0, currUrl.indexOf("/aiportcityGroupBy"));
	var suffix     = currUrl.substring(currUrl.indexOf("/aiportcityGroupBy") + "/aiportcityGroupBy".length, currUrl.length);
	var updatedUrl = prefix + "/aiportcitylookup" + suffix;
	if (typeof tempurl =="string") {
		if (tempurl.indexOf('travel.united.com')!=-1 && tempurl.indexOf('homepage')!=-1) {
			updatedUrl = updatedUrl+'&homepage=1';
		}
	}	  
	var formObject;
	for(i=0; i < document.forms.length; i++){
		if (document.forms[i].name == "airportSearchResultsForm"){
			formObject = document.forms[i];
			break;
		}
	}
	formObject.action = updatedUrl;
	formObject.submit();
	window.status = 'Done';
}

/**
 * This function will be invoked after successfully retrieving
 * response from server.
 */
function updateDynaContent(){
	formObj = document.all[_listObjectId];
	if(_isIE){
		document.getElementById(_listObjectId).innerHTML = _airportRequest.responseText;
	} else {
		formObj.innerHTML=_airportRequest.responseText;
	}
	window.status = 'Done'; //TBD use internationalized val
}

/*  END Dyna content processing*/
/**
 * New requirement. UC-2.1.1. Pre-Populate search field with use entered value.
 * If user entered some values. Otherwise leave it blank. In the page we already
 * have access to formname and fieldname. Retrieve value and poulate in "searchString" field
 * in the "this" document. You can access the parent using opener property of current
 * document.
 */
function prepopulateSrchFld(){
	parentDoc = window.opener.document;
	parentFormNameElem      = document.getElementById("originFormName");
	parentFormNameElemName  = parentFormNameElem.value;//actual form name in parent doc
	parentFieldNameElem     = document.getElementById("originFieldName");
	parentFieldNameElemName = parentFieldNameElem.value;//actual form name in parent doc
	// parentFieldNameElemVal = parentDoc.getElementById(parentFieldNameElemName).value;
	// it is not guaranteed to have the parent element id attribute defined.
	// so we have to retrieve it by looping throught all form elements within the give form.
	var actualElementInParentDoc;
	var parentFieldNameElemVal;
	// scan through all elements and get the name
	for(var i=0; i < parentDoc.forms.length; i++) {
		if (parentDoc.forms[i].name == parentFormNameElemName) {
			// we found what we are looking for.
			// now get elements.
			for(var j=0; j < parentDoc.forms[i].elements.length; j++) {
				if(parentDoc.forms[i].elements[j].name == parentFieldNameElemName){
				   actualElementInParentDoc = parentDoc.forms[i].elements[j];
				   break;
				}
			}// end elements for loop
			break;
		}// end if
	}// end forms for loop
	if(actualElementInParentDoc) {
		parentFieldNameElemVal = actualElementInParentDoc.value;
	} else if (parentDoc.forms.length > 0) {
		// there are forms but would did not find what we are looking for
		for(var k=0; k < parentDoc.forms.length; k++){
			for(var m=0; m < parentDoc.forms[k].elements.length; m++){
				if(parentDoc.forms[k].elements[m].name == parentFieldNameElemName){
					actualElementInParentDoc = parentDoc.forms[k].elements[m];
					break;
				}
			}// end elements for loop
		}// end forms for loop
		// now check again. Who ever said about giving up?
		if(actualElementInParentDoc){
			parentFieldNameElemVal = actualElementInParentDoc.value;
		}
	}
	if(parentFieldNameElemVal && parentFieldNameElemVal != "") {
		searcFld = document.getElementById("searchString0");
		if(searcFld && searcFld.value == "") { // set only if it is empty
			searcFld.value = parentFieldNameElemVal;
		}
	}
}

function chkBrowser(sInp) {
	var sUA = navigator.userAgent.toLowerCase();
	var bFound = sUA.indexOf(sInp) + 1;
	return bFound;
}	

function showSpecialCodeDescription(desc,title) {
	url = "promodesc.do?shop_promotioncode="+desc+"&"+"titleKey="+title;
 	openPopupWin(url, 510,300);
} 


// begin global popup scripts
function goPopup1() {
	if (!popWin.closed) {
		window.popWin.focus();
	}
}
										
function clsAllPops() {
	if (popWin) {
		if (!popWin.closed) {
			if (popWin != null && popWin.open) {			 		
				popWin.close();
			}
		}
	} 
} 
					
function ldFocFunc() {
	bodtag = document.getElementsByTagName('body');
	if (bodtag.focus) {
		chkPopFoc();
		return false;
	} 
}
				
function chkFoc2() {
	if (typeof visSeat =='function') { visSeat() }
	var bodtag = document.getElementById('bodymain');
	// safari close all fix
	if (this.chkBrowser("safari")) {
		bodtag.addEventListener('unload',clsAllPops,false);
	}
	// ie mac
	if (this.chkBrowser("msie") && this.chkBrowser("mac")) {		
		if(typeof window.onfocus == 'function') {
			var existing = onfocus;
			window.onfocus = function() {
				existing();
				chkPopFoc();
			}
		} else {
			window.onfocus = function() {
				chkPopFoc();
			}
		}
	} else {
		if (bodtag.addEventListener) {
			// W3C
			bodtag.addEventListener('focus',chkPopFoc,false);
		} else {
			// IE
			bodtag.attachEvent('focus',chkPopFoc);
		}
	}
	if (typeof loadReg =='function') {loadReg()}
	if (typeof loadTed =='function') {loadTed()}
	
	/* ie pulldown fix */
	if (window.attachEvent && document.getElementsByTagName) {
		var  selRe = document.getElementsByTagName("select");
		for (var iRe = 0; iRe < selRe.length; ++iRe) {
			selRe[iRe].attachEvent('onmousewheel', function() {return false;});  
		}
	}
	
	if (typeof adPosX =='function' && document.getElementById('ad')) { adPosX() }
	if (typeof adbPos =='function' && document.getElementById('ad')) { adbPos() }
	else {if (document.getElementById('ad')){document.getElementById('ad').style.display='block'}}
	if (typeof MPAdPos =='function' && document.getElementById('ad')) { MPAdPos() }
	if (typeof initSort =='function') { initSort() }
}
				
var showwindow;

function shownewwindow(windowName, link, height, width) {
	shownewwindow(windowName, link, height, width, 50, 50);
}
	
function shownewwindow(windowName, link, height, width, left, top) {
	var xpos = ((window.screen.width-height)/2);
	var ypos = ((window.screen.height-width)/2);
	closeWindow(showwindow);
	showwindow = window.open(link,windowName,"height=" + height + ",width=" + width + ",resizable=no,left=" + left + ",top=" + top + ",screenX=" + xpos + ",screenY=" + ypos + ",status=no,scrollbars=yes,menubar=no,toolbar=no,location=no");
	showwindow.focus();
}
	
function closeWindow(theWindow) {
	if (theWindow) {
		if (!theWindow.closed) {
			theWindow.close();
		}
	}
}
// end global popups


