/*

   file: fa.js

*/

// Add a trim function to trim whitespace
function trim(str) {
	return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
};

// -- Global Functions
function changeImages() {
	d = document;
	if (d.images) {
		var img;
		for (var i=0; i<changeImages.arguments.length; i+=2) {
			img = null;
			if (d.layers) {img = findElement(changeImages.arguments[i],0);}
			else {img = d.images[changeImages.arguments[i]];}
			if (img) {img.src = changeImages.arguments[i+1];}
		}
	}
}

function newImage(arg) {
        if (document.images) {
 rslt = new Image();
 rslt.src = arg;
 return rslt;
        }
}

function setAirportCode(code) {	
 document.airport.airport.value=code;
 document.getElementById("AirportQueryResult").style.display = "none"
 //document.getElementById("AirportQuery").style.display = "none"
 var res = document.getElementById("AirportQuery");
 //res.style.display = "block";
 res.innerHTML = "<p align=\"left\"><strong>One Moment Please</strong><div class=\"indent\">Loading airport status. . .</div></p>";
 document.airport.submit(); 
}

function DoLoginBox() {
	var res1 = document.getElementById("headerText");
	res1.style.display = "none";
	var res2 = document.getElementById("LoginBox");
	res2.style.display = "block";
	var res3 = document.getElementById("LiveFlightTracking");
	res3.style.display = "none";
	document.login.flightaware_username.focus();
}

function NoLoginBox() {
	var res2 = document.getElementById("LoginBox");
	res2.style.display = "none";
	var res1 = document.getElementById("headerText");
	res1.style.display = "block";
	var res3 = document.getElementById("LiveFlightTracking");
	res3.style.display = "inline";
}

/*
// +----------------------------------------------------------------------+
// | Livesearch Copyright (c) 2004 Bitflux GmbH            |
// +----------------------------------------------------------------------+
// | Licensed under the Apache License, Version 2.0 (the "License");      |
// | you may not use this file except in compliance with the License.     |
// | You may obtain a copy of the License at|
// | http://www.apache.org/licenses/LICENSE-2.0            |
// | Unless required by applicable law or agreed to in writing, software  |
// | distributed under the License is distributed on an "AS IS" BASIS,    |
// | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or      |
// | implied. See the License for the specific language governing         |
// | permissions and limitations under the License.        |
// +----------------------------------------------------------------------+
// | Author: Bitflux GmbH <l@bitflux.ch>|
// +----------------------------------------------------------------------+
*/

var liveSearchReq = false;
var t = null;
var liveSearchLast = "";
var isIE = false;
// on !IE we only have to initialize it once


function liveSearchInit() {
//	if (navigator.userAgent.indexOf("Safari") > 0) {
//		document.getElementById('livesearch').addEventListener("keydown",liveSearchSubmit,false);
//	} else if (navigator.product == "Gecko") {
//		document.getElementById('livesearch').addEventListener("keypress",liveSearchKeyPress,false);
//		document.getElementById('livesearch').addEventListener("blur",liveSearchHideDelayed,false);
//	} else {
//		document.getElementById('livesearch').attachEvent('onkeydown',liveSearchKeyPress);
//		isIE = true;
//	}

	defaultFormText = 'Enter Airline Name Here';
        if (defaultFormText == document.forms.searchform.q.value) {
		document.forms.searchform.q.value = '';
	}

	document.getElementById('livesearch').setAttribute("autocomplete","off");
}

function liveSearchKeyPress(event) {
	if (event.keyCode == 40 )
	//KEY DOWN
	{
		highlight = document.getElementById("LSHighlight");
		if (!highlight) {
			highlight = document.getElementById("LSResult").firstChild.firstChild.firstChild;
		} else {
			highlight.removeAttribute("id");
			highlight = highlight.nextSibling;
		}
		if (highlight) {
			highlight.setAttribute("id","LSHighlight");
		} 
		if (!isIE) { event.preventDefault(); }
	} 
	//KEY UP
	else if (event.keyCode == 38 ) {
		highlight = document.getElementById("LSHighlight");
		if (!highlight) {
			highlight = document.getElementById("LSResult").firstChild.firstChild.lastChild;
		} 
		else {
			highlight.removeAttribute("id");
			highlight = highlight.previousSibling;
		}
		if (highlight) {
				highlight.setAttribute("id","LSHighlight");
		}
		if (!isIE) { event.preventDefault(); }
	} 
	//ESC
	else if (event.keyCode == 27) {
		highlight = document.getElementById("LSHighlight");
		if (highlight) {
			highlight.removeAttribute("id");
		}
		document.getElementById("LSResult").style.display = "none";
		document.forms.searchform.q.value = '';
	} 
}
function liveSearchStart() {

	if (t) {
		window.clearTimeout(t);
	}
	t = window.setTimeout("liveSearchDoSearch()",200);
}

function liveSearchDoSearch() {
        var agt=navigator.userAgent.toLowerCase();
        var is_major = parseInt(navigator.appVersion);
        var is_minor = parseFloat(navigator.appVersion);
        var is_ie = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
        var is_ie7 = (is_ie && (agt.indexOf("msie 7.")!=-1) );
	if ((!is_ie) || (is_ie7)) {
		liveSearchReq = new XMLHttpRequest();
 	}

	document.forms.searchform.ident_prefix.value = '';

	if (liveSearchLast != document.forms.searchform.q.value) {
	if (liveSearchReq && liveSearchReq.readyState < 4) {
		liveSearchReq.abort();
	}
	if ( document.forms.searchform.q.value == "") {
		document.getElementById("LSResult").style.display = "none";
		highlight = document.getElementById("LSHighlight");
		if (highlight) {
			highlight.removeAttribute("id");
		}
		return false;
	}
	if (window.XMLHttpRequest) {
	// branch for IE/Windows ActiveX version
	} else if (window.ActiveXObject) {
		liveSearchReq = new ActiveXObject("Microsoft.XMLHTTP");
	}
	liveSearchReq.onreadystatechange= liveSearchProcessReqChange;
	liveSearchReq.open("GET", "http://flightaware.com/include/search.rvt?type=airline;query=" + document.forms.searchform.q.value);
	liveSearchLast = document.forms.searchform.q.value;
	liveSearchReq.send(null);
	}
}

function liveSearchProcessReqChange() {
	if (liveSearchReq.readyState == 4) {
		var  res = document.getElementById("LSResult");
		res.style.display = "block";
		res.innerHTML = liveSearchReq.responseText;
	}
}

function liveSearchSubmit() {
	var highlight = document.getElementById("LSHighlight");
	if (highlight && highlight.firstChild) {
		window.location = highlight.firstChild.getAttribute("href");
		return false;
	} 
	else {
		return true;
	}
}

function liveSearchHighlightEntryArea() {
  var livesearchBox = document.getElementById("livesearch");
}

function setCode(code,name) {	
 document.searchform.ident_prefix.value=code;
 document.searchform.livesearch.value=name;
 document.getElementById("LSResult").style.display = "none"
 if (document.searchform.ident_suffix.value.length > 1) {
  var  res = document.getElementById("LSResult");
  res.style.display = "block";
  res.innerHTML = "<p align=\"left\"><strong>One Moment Please</strong><div class=\"indent\">Loading flight status. . .&nbsp;&nbsp;</div></p>";
  document.searchform.submit();
 }
}

function checkPrefix() {
 if (document.searchform.ident_prefix.value.length < 3) {
 	if (document.searchform.q.value.length < 4) {
		alert('You must type in part of an airline name and then select the correct one from the box below the search form.');
	} else {
		alert('You must select the correct airline name from the box below the search form.');
	}
        document.searchform.q.focus();
        return false;
 }

 if (document.searchform.ident_suffix.value.length < 1) {
	alert('You must type in a flight number in the field next to your selected airline name.');
	return false;
 }

 return true;
}

/*
function DoAirportBox() {
	var res = document.getElementById("AirportQuery");
	res.style.display = "block";
	res.innerHTML = "<table width='100%'><tr><td colspan='2' align='right' style='border:0; font-size: 12px;'><a href='javascript:XAirportBox()'>Close</a></td></tr><tr><td align='center' style='border: 0;'>Type part of an airport or city name:</td></tr><tr><td align='left' style='border: 0;'><input id='livesearch2' type='text' name='q' onkeypress='liveSearchStart2()' size='25' autocomplete='off' /></td></tr><tr><td style='border: 0;'><div id=\"AirportQueryWait\"></div></td></tr></table>"; 
	document.AirportQueryForm.q.focus();
}
function XAirportBox() {
	document.getElementById("AirportQuery").style.display = "none"
}

*/
function DoUploadBox() {
	var res = document.getElementById("UploadBox");
	res.style.display = "block";
	res.innerHTML = "<table width='100%'><tr><td align='right' colspan='2' font-size: 12px;'>(<a style='color: black' href='javascript:XUploadBox()'>Close</a>)</td></tr><tr><td colspan='2' style='border: 0;'><h3>Upload Photo</h3><p>Upload a picture of this aircraft by selecting the file below.</p></td></tr><tr><td><form  action='/photos/upload_action.rvt' enctype='multipart/form-data' method='post'><td><input type='file' name='media' size='40'></td></tr><tr><td></td><td><input type='submit' value='Send' /></td></tr><tr><td>Do not upload images you do not own.  All content is subject to the <a href=\"javascript:license();\">FlightAware Photo License Agreement.</a></td></rd></form></table>";
}

function license() {
	window.open('/photos/license.rvt','cellphone_window','toolbar=no,location=no, directories=no, status=yes, menubar=no, resizable=yes, copyhistory=no, scrollbars=no, width=350, height=450');
}

function XUploadBox() {
	document.getElementById("UploadBox").style.display = "none"
}


var liveSearchReq = false;
var t = null;
var liveSearchLast = "";
var isIE = false;
// on !IE we only have to initialize it once
if (window.XMLHttpRequest) {
	liveSearchReq = new XMLHttpRequest();
}

function liveSearchInit2() {
	if (navigator.userAgent.indexOf("Safari") > 0) {
		document.getElementById('livesearch2').addEventListener("keydown",liveSearchKeyPress2,false);
	} else if (navigator.product == "Gecko") {
		document.getElementById('livesearch2').addEventListener("keypress",liveSearchKeyPress2,false);
	} else {
		document.getElementById('livesearch2').attachEvent('onkeydown',liveSearchKeyPress2);
		isIE = true;
	}

}

function liveSearchKeyPress2(event) {


	if (event.keyCode == 40 )
	//KEY DOWN
	{
		highlight = document.getElementById("LSHighlight");
		if (!highlight) {
			highlight = document.getElementById("AirportQueryResult").firstChild.firstChild.firstChild;
		} else {
			highlight.removeAttribute("id");
			highlight = highlight.nextSibling;
		}
		if (highlight) {
			highlight.setAttribute("id","LSHighlight");
		} 
		if (!isIE) { event.preventDefault(); }
	} 
	//KEY UP
	else if (event.keyCode == 38 ) {
		highlight = document.getElementById("LSHighlight");
		if (!highlight) {
			highlight = document.getElementById("AirportQueryResult").firstChild.firstChild.lastChild;
		} 
		else {
			highlight.removeAttribute("id");
			highlight = highlight.previousSibling;
		}
		if (highlight) {
				highlight.setAttribute("id","LSHighlight");
		}
		if (!isIE) { event.preventDefault(); }
	} 
	//ESC
	else if (event.keyCode == 27) {
		highlight = document.getElementById("LSHighlight");
		if (highlight) {
			highlight.removeAttribute("id");
		}
		document.getElementById("AirportQueryResult").style.display = "none";
		document.forms.AirportQueryForm.q.value = '';
	} 
}
function liveSearchStart2() {
        var wait = document.getElementById("AirportQueryWait");
       	wait.style.display = "block";
       	wait.innerHTML = "<p align=\"center\">I'll guess when I know what you mean.</p>";

	if (t) {
		window.clearTimeout(t);
	}
	t = window.setTimeout("liveSearchDoSearch2()",200);
}

function liveSearchDoSearch2() {
        var agt=navigator.userAgent.toLowerCase();
        var is_major = parseInt(navigator.appVersion);
        var is_minor = parseFloat(navigator.appVersion);
        var is_ie = ((agt.indexOf("msie") != -1) && (agt.indexOf("opera") == -1));
        var is_ie7 = (is_ie && (agt.indexOf("msie 7.")!=-1) );
	if ((!is_ie) || (is_ie7)) {
		liveSearchReq = new XMLHttpRequest();
 	}

	document.forms.airport.airport.value = '';

	if (liveSearchLast != document.forms.AirportQueryForm.q.value) {
	if (liveSearchReq && liveSearchReq.readyState < 4) {
		liveSearchReq.abort();
	}
	if ( document.forms.AirportQueryForm.q.value == "") {
		document.getElementById("AirportQueryResult").style.display = "none";
		highlight = document.getElementById("LSHighlight");
		if (highlight) {
			highlight.removeAttribute("id");
		}
		return false;
	}
	if (window.XMLHttpRequest) {
	// branch for IE/Windows ActiveX version
	} else if (window.ActiveXObject) {
		 liveSearchReq = new ActiveXObject("Microsoft.XMLHTTP"); 
	}
	liveSearchReq.onreadystatechange= liveSearchProcessReqChange2;
	liveSearchReq.open("GET", "http://flightaware.com/include/search.rvt?type=airport;query=" + document.forms.AirportQueryForm.q.value);
	liveSearchLast = document.forms.AirportQueryForm.q.value;
	liveSearchReq.send(null);
	}
}

function liveSearchProcessReqChange2() {
	if (liveSearchReq.readyState == 4) {
		var  res = document.getElementById("AirportQueryResult");
		res.style.display = "block";
		res.innerHTML = liveSearchReq.responseText;
	}
}

function liveSearchSubmit2() {
	var highlight = document.getElementById("LSHighlight");
	if (highlight && highlight.firstChild) {
		window.location = highlight.firstChild.getAttribute("href");
		return false;
	} 
	else {
		return true;
	}
}

function liveSearchHighlightEntryArea2() {
  var livesearchBox = document.getElementById("livesearch2");
}

function ajax_lookup_to_div(target_div,ajax_url,message,request_vars) {
	if (typeof target_div == "undefined") {
		return;
	}
	if (typeof message == "undefined") {
		message = '<p>Please wait...</p>';
	}
	var target = document.getElementById(target_div);

	if (message != 'NONE') {
		target.innerHTML = message;
	}

	var xhr;
	try {  xhr = new ActiveXObject('Msxml2.XMLHTTP');   }
	catch (e) {
		try {   xhr = new ActiveXObject('Microsoft.XMLHTTP');    }
		catch (e2) {
			try {  xhr = new XMLHttpRequest();     }
			catch (e3) {  xhr = false;   }
		}
	}
  
	xhr.onreadystatechange  = function() { 
		if(xhr.readyState  == 4) {
			if(xhr.status  == 200) {
				target.innerHTML = xhr.responseText;
			} else {
				target.innerHTML = "Error code " + xhr.status;
			}
		}
	}; 
	if (typeof request_vars == "undefined") {
		xhr.open("GET", ajax_url, true); 
	} else {
		xhr.open("POST", ajax_url, true); 
		xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		xhr.send(request_vars);
	}
	// xhr.send(null); 

       //if(target_div == 'pleasewait_box') {
       //   alert('using ajax function for flight plannning');
          //initializeJqueryOnload();
       //} 
}

function ajax_lookup_to_field(field_name,ajax_url,onupdate) {
	var target = document.getElementById(field_name);


	var xhr;
	try {  xhr = new ActiveXObject('Msxml2.XMLHTTP');   }
	catch (e) {
		try {   xhr = new ActiveXObject('Microsoft.XMLHTTP');    }
		catch (e2) {
			try {  xhr = new XMLHttpRequest();     }
			catch (e3) {  xhr = false;   }
		}
	}
  
	xhr.onreadystatechange  = function() { 
		if(xhr.readyState  == 4) {
			if(xhr.status  == 200) {
				target.value = xhr.responseText.replace(/^\s+|\s+$/g,"");
				if(typeof onupdate != "undefined") {
					if ( onupdate.indexOf('(') == -1 ) {
						onupdate = onupdate + '()';
					}
					eval(onupdate);
				}
			}
		}
	}; 
	if (typeof request_vars == "undefined") {
		xhr.open("GET", ajax_url, true); 
	} else {
		xhr.open("POST", ajax_url, true); 
		xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		xhr.send(request_vars);
	}
	xhr.send(null); 
}

function ajax_validate_field(field_name,ajax_url,onupdate) {
	var target = document.getElementById(field_name);
	ajax_url = '/ajax/' + ajax_url + '.rvt?data=' + target.value;

	var xhr;
	try {  xhr = new ActiveXObject('Msxml2.XMLHTTP');   }
	catch (e) {
		try {   xhr = new ActiveXObject('Microsoft.XMLHTTP');    }
		catch (e2) {
			try {  xhr = new XMLHttpRequest();     }
			catch (e3) {  xhr = false;   }
		}
	}
  
	xhr.onreadystatechange  = function() { 
		if(xhr.readyState  == 4) {
			if(xhr.status  == 200) {
				target.value = xhr.responseText.replace(/^\s+|\s+$/g,"");
				if(typeof onupdate != "undefined") {
					if ( onupdate.indexOf('(') == -1 ) {
						onupdate = onupdate + '()';
					}
				}
			}
		}
	}; 
	if (typeof request_vars == "undefined") {
		xhr.open("GET", ajax_url, true); 
	} else {
		xhr.open("POST", ajax_url, true); 
		xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
		xhr.send(request_vars);
	}
	xhr.send(null); 
}

function validate_airport_code(formfield) {
	var ident = formfield.value.toUpperCase();
	formfield.value = trim(ident);
}

function validate_aircrafttype(formfield) {
	var buf = formfield.value.toUpperCase();
	formfield.value = trim(buf);
}

function fuel_price_lookup(formfield,target_div) {
	var ident = formfield.value.toUpperCase();
	formfield.value = ident;

	var aircraft_id = document.getElementById('aircraft').options[document.getElementById('aircraft').selectedIndex].value;
	var id_string = '';
	if (aircraft_id > 0) {
		id_string = ';aircraft_id=' + aircraft_id;
	}
	// formfield.value = validate_airport_code(formfield);

	if (ident != '') {
		ajax_lookup_to_div(target_div,'/ajax/fuel_prices.rvt?airport=' + ident + id_string);
	}
}
/*
function fp_airport_meta_lookup(formfield,fuel_target,alternates_target) {
	var ident = formfield.value.toUpperCase();
        //previously done in JQuery code
	//formfield.value = ident;

	if (ident != '') {
		ajax_lookup_to_div(alternates_target,'/ajax/alternates.rvt?airport=' + ident);
		//fuel_price_lookup(formfield,fuel_target);
                document.getElementById('alternateContainer').style.display = 'block';
	}
}
*/

function fp_fuel_price_indication(element) {
      // a click needs to remove all the styles for the other cell,
      // as well as change the style for the one that was clicked.
      var parentRow = element.parentNode;
      var parentTable = parentRow.parentNode;

      //remove the specific style from all it's children
      for (i=0;i<parentTable.childNodes.length;i++)
      {
           var row = parentTable.childNodes[i];
           if (row.childNodes[2]) {
               //undo style for this cell:
               row.childNodes[2].style.backgroundImage = ''; 
               //set the row back to the previous style:
               //row.className = 'smallActiverow' + row + 'Hover'; 
            
           } 
           //save last style name to alternate row.
      }

      element.style.backgroundImage = "url('/images/FAE051.gif')";
      //element.parentNode.className = 'SelectedRoute';
}
function fp_update_perf_selects(formfield,target) {
	var id = formfield.options[formfield.selectedIndex].value;

	if (id > 0) {
		ajax_lookup_to_div(target,'/ajax/perf_profiles.rvt?id=' + id);
		ajax_lookup_to_field('minAltitude','/ajax/aircraft_info.rvt?id=' + id + ';field=cruise_min');
		ajax_lookup_to_field('maxAltitude','/ajax/aircraft_info.rvt?id=' + id + ';field=cruise_max');
	}
	fuel_price_lookup(document.getElementById('origin'),'priceblock1');
	fuel_price_lookup(document.getElementById('destination'),'priceblock2');
}


//the following function is used only when the user clicks the back button after going to step two of plan a flight
//it is called on webroot/flightplan/flightplan.rvt body onload.
//we want to retain user settings for cruise alt. min and max, which they may have overridden from the populated defaults.
//but at the same time, get the dynamic aircraft sub-select lists repopulated. So it's the same function, with cruise_min and 
//cruise_max not reset in this case.

function fp_update_perf_selects_alt(formfield,target) {
        var id = formfield.options[formfield.selectedIndex].value;

        if (id > 0) {
                ajax_lookup_to_div(target,'/ajax/perf_profiles.rvt?id=' + id);
                //ajax_lookup_to_field('minAltitude','/ajax/aircraft_info.rvt?id=' + id + ';field=cruise_min');
                //ajax_lookup_to_field('maxAltitude','/ajax/aircraft_info.rvt?id=' + id + ';field=cruise_max');
        }

        fuel_price_lookup(document.getElementById('origin'),'priceblock1');
        fuel_price_lookup(document.getElementById('destination'),'priceblock2');
}               

function fp_category_update(formfield,target_div) {
	var target = document.getElementById(target_div);
	var category = formfield.options[formfield.selectedIndex].value;

	if (category == "Cruise") {
		target.style.visibility = "hidden";
	} else {
		target.style.visibility = "visible";
	}
}

last = 0;
laststyle = '';
cellstyle = '';

function fp_route_click(cell) {
	if (last) last.className = laststyle;
	last = cell;
	laststyle = cellstyle;
	cell.className = 'SelectedRoute';
	cellstyle = 'SelectedRoute';

	document.getElementById("selected").value = cell.id;

        //arobson: we also need to enable the other "WITH FAA" button in the case of fuel and souls are provided
        var fuelOnBoard    = document.getElementById('fuelOnBoard').value;
        //var personsOnBoard = document.getElementById('personsOnBoard').value;
        if(fuelOnBoard != "") { 
            document.getElementById('file').disabled = false;
        }

        //we don't use the following function for validating any more,
        //and it's not harmless to include it.
	//fp_flightplan_validate();

        // if there is warning in the second form about selecting route, we have to remove just that part.
        //we now remove the error html with JQuery, so the following line has been commented out.
        //document.getElementById('problems').innerHTML = document.getElementById('problems').innerHTML.replace("<li>Please select a route and altitude combination above</li>","");
}

function fp_route_mouseover(cell) {
	cellstyle = cell.className;
	cell.className = 'SelectedRoute';
}

function fp_route_mouseout(cell) {
	cell.className = cellstyle;
}

function fp_flightplan_validate() {
	var valid = 1;

	var htmlout = "<ul>"

	var fuelOnBoard    = document.getElementById('fuelOnBoard').value;
	var personsOnBoard = document.getElementById('personsOnBoard').value;
	var private_profile = document.getElementById('private_profile').value;

	if(fuelOnBoard.length == 0) {
		htmlout = htmlout + '<li>Please enter fuel on board</li>';
		valid = 0;
	}

	if(personsOnBoard.length == 0) {
		htmlout = htmlout + '<li>Please enter persons on board</li>';
		valid = 0;
	}

	if (private_profile == 0) {
		htmlout = htmlout + '<li>You cannot file a flight plan for a shared profile aircraft</li>';
		valid = 0;
	}

        //arobson: to determine if we can enable the button, we also must make sure a route has been selected
        // one quick cheat is to test if the other button is enabled.

        //arobson: we now do this test with jquery in the page. there is not longer a 'nofile' element
        //if(document.getElementById('nofile').disabled == true) {
        //    htmlout = htmlout + '<li>Please select a route and altitude combination above</li>';
        //    valid = 0;
        //}

	htmlout = htmlout + '</ul>';

	document.getElementById('problems').innerHTML = htmlout;

	if(valid == 0) {
		document.getElementById('file').disabled = true;
	} else {
		document.getElementById('file').disabled = false;
	}
}

function fp_simpleplan_validate() {
	var valid = 1;

	var htmlout = "<ul>"

	var altitude = document.getElementById('altitude').value;
	var speed    = document.getElementById('speed').value;
	var ete      = document.getElementById('ete').value;
	var fob      = document.getElementById('fob').value;
	var sob      = document.getElementById('sob').value;
	var route    = document.getElementById('route').value;

	if(altitude.length == 0) { valid = 0; }
	if(speed.length == 0) { valid = 0; }
	if(ete.length == 0) { valid = 0; }
	if(fob.length == 0) { valid = 0; }
	if(sob.length == 0) { valid = 0; }

	if(valid == 0) {
		htmlout = htmlout + '<li>Please complete all the fields</li>';
	}
	htmlout = htmlout + '</ul>';

	document.getElementById('problems').innerHTML = htmlout;

	if(valid == 0) {
		document.getElementById('plan').disabled = true;
	} else {
		document.getElementById('plan').disabled = false;
	}
}

function fp_perf_list_sanitize(buf,type) {

}

function fp_phone_validate(formfield) {
	var phone_number = trim(formfield.value);
	phone_number = phone_number.replace(/^\+?1[ \-]/,'');
	phone_number = phone_number.replace(/[^0-9]+/g,'');
	if(phone_number.length != 10) {
		return false;
	} else {
		phone_number = phone_number.substring(0,3) + '-' + phone_number.substring(3,6) + '-' + phone_number.substring(6,10);
		formfield.value = phone_number;
		return true;
	}
}

function fp_pilot_validate() {
	var valid = 1;

	var htmlout = "<ul>";

	if(!fp_phone_validate(document.getElementById('phone'))) {
		htmlout = htmlout + '<li>Please enter a 10-digit phone number</li>';
		valid = 0;
	}

	fp_phone_validate(document.getElementById('emergency_contact_phone'));

	document.getElementById('problems').innerHTML = htmlout + '</ul>';

	if(valid == 0) {
		document.getElementById('save_pilot').disabled = true;
	} else {
		document.getElementById('save_pilot').disabled = false;
	}
}

function fp_comnav_validate(me) {
	if(me == document.getElementById('comnav_G')) {
		if(document.getElementById('comnav_G').checked) {
			document.getElementById('comnav_R').checked = true;
		}
	}

	if(me == document.getElementById('comnav_L')) {
		if(document.getElementById('comnav_L').checked) {
			document.getElementById('comnav_O').checked = true;
		}
	}

	if(document.getElementById('comnav_J').checked) {
		document.getElementById('datalink').style.display = 'table-row';
	} else {
		document.getElementById('datalink').style.display = 'none';
	}

	if(document.getElementById('comnav_R').checked) {
		document.getElementById('rnp').style.display = 'table-row';
	} else {
		document.getElementById('rnp').style.display = 'none';
		document.getElementById('rnav_0').checked = false;
		document.getElementById('rnav_4').checked = false;
	}

}

function fp_aircraft_validate() {
	var valid = 1;

	var htmlout = "<ul>"

	var ident          = document.getElementById('fp_ident').value;
	var description    = document.getElementById('fp_description').value;
	var type           = document.getElementById('type').value;
	var empty_weight   = document.getElementById('empty_weight').value;
	var max_to_weight  = document.getElementById('max_to_weight').value;

	if(ident.length == 0) {
		htmlout = htmlout + '<li>Ident missing</li>';
		valid = 0;
	}
	if(ident == 'INVALID') {
		htmlout = htmlout + '<li>Ident does not look like a tail number or callsign</li>';
		valid = 0;
	}
	if(type.length == 0) {
		htmlout = htmlout + '<li>Aircraft type missing</li>';
		valid = 0;
	}
	if(type == 'INVALID') {
		htmlout = htmlout + '<li>iAircraft type does not look right</li>';
		valid = 0;
	}
	if(empty_weight.length == 0) {
		htmlout = htmlout + '<li>You must supply an empty weight</li>';
		valid = 0;
	}
	if(max_to_weight.length == 0) {
		htmlout = htmlout + '<li>You must supply a maximum takeoff weight</li>';
		valid = 0;
	}
	htmlout = htmlout + '</ul>';

	document.getElementById('problems').innerHTML = htmlout;

	if(valid == 0) {
		document.getElementById('save_aircraft').disabled = true;
	} else {
		document.getElementById('save_aircraft').disabled = false;
	}
}

function fp_perf_validate() {
	var description = document.getElementById('fp_description').value;
	var weights 	= document.getElementById('weights').value;
	var temps 	= document.getElementById('temps').value;
	var altitudes 	= document.getElementById('altitudes').value;
	var htmlout	= "<ul>";

	var valid = 1;

	weights = weights.replace(/[^0-9 ]/g,'');
	weights = weights.replace(/  +/g,' ');
	weights = weights.replace(/ $/g,'');
	altitudes = altitudes.replace(/[^0-9 ]/g,'');
	altitudes = altitudes.replace(/  +/g,' ');
	altitudes = altitudes.replace(/ $/g,'');
	temps = temps.replace(/[^0-9 \-+]/g,'');
	temps = temps.replace(/  +/g,' ');
	temps = temps.replace(/ $/g,'');

	document.getElementById('weights').value = weights;
	document.getElementById('temps').value = temps;
	document.getElementById('altitudes').value = altitudes;

	if(description.length == 0) {
		htmlout = htmlout + '<li>Please enter a description</li>';
		valid = 0;
	}
	if(weights.length == 0) {
		htmlout = htmlout + '<li>You must enter at least one weight</li>';
		valid = 0;
	}
	if(altitudes.length == 0) {
		htmlout = htmlout + '<li>You must enter at least one altitude</li>';
		valid = 0;
	}
	htmlout = htmlout + '</ul>';

	document.getElementById('problems').innerHTML = htmlout;
	if(valid == 0) {
		document.getElementById('step_two').disabled = true;
	} else {
		document.getElementById('step_two').disabled = false;
	}
}

function SelectAll(id) {
    document.getElementById(id).focus();
    document.getElementById(id).select();
}

function admaker_upload_form(type) {
        if (document.newbanner.type.value == "upload") {
		document.getElementById('new_image').style.display = "";
		document.getElementById('new_text_1').style.display = "none";
		document.getElementById('new_text_2').style.display = "none";
		document.getElementById('new_createad1').style.display = "none";
		document.getElementById('new_createad2').style.display = "none";
		document.getElementById('new_createad3').style.display = "none";
		document.getElementById('new_createad4').style.display = "none";
		document.getElementById('new_createad5').style.display = "none";
		document.getElementById('new_preview').style.display = "none";
		return;
        } else if (document.newbanner.type.value == "createad") {
		document.getElementById('new_text_1').style.display = "none";
		document.getElementById('new_text_2').style.display = "none";
		document.getElementById('new_image').style.display = "none";
		document.getElementById('new_createad1').style.display = "";
		document.getElementById('new_createad2').style.display = "";
		document.getElementById('new_createad3').style.display = "";
		document.getElementById('new_createad4').style.display = "";
		document.getElementById('new_createad5').style.display = "";
		document.getElementById('new_preview').style.display = "";
		return;
        } else {
		document.getElementById('new_createad1').style.display = "none";
		document.getElementById('new_createad2').style.display = "none";
		document.getElementById('new_createad3').style.display = "none";
		document.getElementById('new_createad4').style.display = "none";
		document.getElementById('new_createad5').style.display = "none";
		document.getElementById('new_image').style.display = "none";
		document.getElementById('new_preview').style.display = "none";
		document.getElementById('new_text_1').style.display = "";
		document.getElementById('new_text_2').style.display = "";
		return;
        }
}

var previousPreviewURL = '';
function admaker_update_preview() {
 	var url = '/commercial/advertising/ad_maker/make_ad.rvt?' +
	'title=' + escape(document.getElementById('title').value) + ';' +
	'bodytext=' + escape(document.getElementById('bodytext').value) + ';' +
	'bodysize=' + escape(document.getElementById('bodysize').value) + ';' +
	'template=' + document.getElementById('template').value + ';' +
	'font=' + document.getElementById('font').value;

	if (previousPreviewURL != url) {
	    document.getElementById('banner_url').value = url;
        document.getElementById('banner_preview').src = url;
		previousPreviewUrl = url;
	}
}

function debug_toggle (element) {

	if (document.getElementById){ 
		var i; 
		var x = document.getElementById('debug_block').getElementsByTagName('div');
		for (i=0;i<x.length;i++){ 
			if (x[i].className == 'debug_detail') {
				x[i].style.display='none'; 
			} 
		} 
	}

	var id = document.getElementById('debug_detail_' + element);
	if (id.style.display == 'block') {
		id.style.display = 'none';
	} else {
		id.style.display = 'block';
	}
}

function fa_form_update (fieldname) {
	userlist = document.getElementById(fieldname).value;
	limit    = document.getElementById(fieldname+'_limit').value;

	ajax_lookup_to_div(fieldname+'_form_uid','/ajax/fa_form_update_userlist.rvt?fieldname='+fieldname+';value='+userlist+';limit='+limit,'NONE');
}

function fa_form_delete_item (fieldname, item) {
	userlist = document.getElementById(fieldname).value.split(' ');
	newlist = '';

	for ( var i in userlist ) {
		var uid = userlist[i];
		if (uid != item) {
			newlist = newlist + uid + ' ';
		}
	}

	document.getElementById(fieldname).value = newlist.replace(/\s+$/,"");

	fa_form_update(fieldname);
}

function fa_form_add_item (fieldname) {
	var buf = document.getElementById(fieldname+'_add').value;
	var old = document.getElementById(fieldname).value;
	limit   = document.getElementById(fieldname+'_limit').value;

	if (limit == 1) {
		document.getElementById(fieldname+'_display').style.display = 'block';
		document.getElementById(fieldname+'_entry').style.display = 'none';
	}
	ajax_lookup_to_field(fieldname,'/ajax/fa_form_add_username.rvt?old='+old+';new='+buf+';limit='+limit,'fa_form_update(\''+fieldname+'\');');
	if (limit != 1) {
		document.getElementById(fieldname+'_add').value = '';
	}
}

function fa_form_toggle_edit (fieldname,style) {
	de = document.getElementById(fieldname+'_display');
	ee = document.getElementById(fieldname+'_entry');
	value = document.getElementById(fieldname).value;

	if(value == '') {
		style = 'edit';
	}

	if (style == 'edit') {
		de.style.display = 'none';
		ee.style.display = 'block';
	} else {
		ee.style.display = 'none';
		de.style.display = 'block';
	}

}


/*

   END ORIGINAL fa.js

*/

/*
FREESTYLE MENUS v1.0 RC (c) 2001-2006 Angus Turnbull, http://www.twinhelix.com
Altering this notice or redistributing this file is prohibited.
*/

var isDOM=document.getElementById?1:0,isIE=document.all?1:0,isNS4=navigator.appName=='Netscape'&&!isDOM?1:0,isOp=self.opera?1:0,isDyn=isDOM||isIE||isNS4;function getRef(i,p){p=!p?document:p.navigator?p.document:p;return isIE?p.all[i]:isDOM?(p.getElementById?p:p.ownerDocument).getElementById(i):isNS4?p.layers[i]:null};function getSty(i,p){var r=getRef(i,p);return r?isNS4?r:r.style:null};if(!self.LayerObj)var LayerObj=new Function('i','p','this.ref=getRef(i,p);this.sty=getSty(i,p);return this');function getLyr(i,p){return new LayerObj(i,p)};function LyrFn(n,f){LayerObj.prototype[n]=new Function('var a=arguments,p=a[0],px=isNS4||isOp?0:"px";with(this){'+f+'}')};LyrFn('x','if(!isNaN(p))sty.left=p+px;else return parseInt(sty.left)');LyrFn('y','if(!isNaN(p))sty.top=p+px;else return parseInt(sty.top)');if(typeof addEvent!='function'){var addEvent=function(o,t,f,l){var d='addEventListener',n='on'+t,rO=o,rT=t,rF=f,rL=l;if(o[d]&&!l)return o[d](t,f,false);if(!o._evts)o._evts={};if(!o._evts[t]){o._evts[t]=o[n]?{b:o[n]}:{};o[n]=new Function('e','var r=true,o=this,a=o._evts["'+t+'"],i;for(i in a){o._f=a[i];r=o._f(e||window.event)!=false&&r;o._f=null}return r');if(t!='unload')addEvent(window,'unload',function(){removeEvent(rO,rT,rF,rL)})}if(!f._i)f._i=addEvent._i++;o._evts[t][f._i]=f};addEvent._i=1;var removeEvent=function(o,t,f,l){var d='removeEventListener';if(o[d]&&!l)return o[d](t,f,false);if(o._evts&&o._evts[t]&&f._i)delete o._evts[t][f._i]}}function FSMenu(myName,nested,cssProp,cssVis,cssHid){this.myName=myName;this.nested=nested;this.cssProp=cssProp;this.cssVis=cssVis;this.cssHid=cssHid;this.cssLitClass='highlighted';this.menus={root:new FSMenuNode('root',true,this)};this.menuToShow=[];this.mtsTimer=null;this.showDelay=0;this.switchDelay=125;this.hideDelay=500;this.showOnClick=0;this.hideOnClick=true;this.animInSpeed=0.2;this.animOutSpeed=0.2;this.animations=[]};FSMenu.prototype.show=function(mN){with(this){menuToShow.length=arguments.length;for(var i=0;i<arguments.length;i++)menuToShow[i]=arguments[i];clearTimeout(mtsTimer);if(!nested)mtsTimer=setTimeout(myName+'.menus.root.over()',10)}};FSMenu.prototype.hide=function(mN){with(this){clearTimeout(mtsTimer);if(menus[mN])menus[mN].out()}};FSMenu.prototype.hideAll=function(){with(this){for(var m in menus)if(menus[m].visible&&!menus[m].isRoot)menus[m].hide(true)}};function FSMenuNode(id,isRoot,obj){this.id=id;this.isRoot=isRoot;this.obj=obj;this.lyr=this.child=this.par=this.timer=this.visible=null;this.args=[];var node=this;this.over=function(evt){with(node)with(obj){if(isNS4&&evt&&lyr.ref)lyr.ref.routeEvent(evt);clearTimeout(timer);clearTimeout(mtsTimer);if(!isRoot&&!visible)node.show();if(menuToShow.length){var a=menuToShow,m=a[0];if(!menus[m]||!menus[m].lyr.ref)menus[m]=new FSMenuNode(m,false,obj);var c=menus[m];if(c==node){menuToShow.length=0;return}clearTimeout(c.timer);if(c!=child&&c.lyr.ref){c.args.length=a.length;for(var i=0;i<a.length;i++)c.args[i]=a[i];var delay=child?switchDelay:showDelay;c.timer=setTimeout('with('+myName+'){menus["'+c.id+'"].par=menus["'+node.id+'"];menus["'+c.id+'"].show()}',delay?delay:1)}menuToShow.length=0}if(!nested&&par)par.over()}};this.out=function(evt){with(node)with(obj){if(isNS4&&evt&&lyr&&lyr.ref)lyr.ref.routeEvent(evt);clearTimeout(timer);if(!isRoot&&hideDelay>=0){timer=setTimeout(myName+'.menus["'+id+'"].hide()',hideDelay);if(!nested&&par)par.out()}}};if(this.id!='root')with(this)with(lyr=getLyr(id))if(ref){if(isNS4)ref.captureEvents(Event.MOUSEOVER|Event.MOUSEOUT);addEvent(ref,'mouseover',this.over);addEvent(ref,'mouseout',this.out);if(obj.nested){addEvent(ref,'focus',this.over);addEvent(ref,'click',this.over);addEvent(ref,'blur',this.out)}}};FSMenuNode.prototype.show=function(forced){with(this)with(obj){if(!lyr||!lyr.ref)return;if(par){if(par.child&&par.child!=this)par.child.hide();par.child=this}var offR=args[1],offX=args[2],offY=args[3],lX=0,lY=0,doX=''+offX!='undefined',doY=''+offY!='undefined';if(self.page&&offR&&(doX||doY)){with(page.elmPos(offR,par.lyr?par.lyr.ref:0))lX=x,lY=y;if(doX)lyr.x(lX+eval(offX));if(doY)lyr.y(lY+eval(offY))}if(offR)lightParent(offR,1);visible=1;if(obj.onshow)obj.onshow(id);lyr.ref.parentNode.style.zIndex=2000;setVis(1,forced)}};FSMenuNode.prototype.hide=function(forced){with(this)with(obj){if(!lyr||!lyr.ref||!visible)return;if(isNS4&&self.isMouseIn&&isMouseIn(lyr.ref))return show();if(args[1])lightParent(args[1],0);if(child)child.hide();if(par&&par.child==this)par.child=null;if(lyr){visible=0;if(obj.onhide)obj.onhide(id);lyr.ref.parentNode.style.zIndex=1999;setVis(0,forced)}}};FSMenuNode.prototype.lightParent=function(elm,lit){with(this)with(obj){if(!cssLitClass||isNS4)return;if(lit)elm.className+=(elm.className?' ':'')+cssLitClass;else elm.className=elm.className.replace(new RegExp('(\\s*'+cssLitClass+')+$'),'')}};FSMenuNode.prototype.setVis=function(sh,forced){with(this)with(obj){if(lyr.forced&&!forced)return;lyr.forced=forced;lyr.timer=lyr.timer||0;lyr.counter=lyr.counter||0;with(lyr){clearTimeout(timer);if(sh&&!counter)sty[cssProp]=cssVis;var speed=sh?animInSpeed:animOutSpeed;if(isDOM&&speed<1)for(var a=0;a<animations.length;a++)animations[a](ref,counter,sh);counter+=speed*(sh?1:-1);if(counter>1){counter=1;lyr.forced=false}else if(counter<0){counter=0;sty[cssProp]=cssHid;lyr.forced=false}else if(isDOM){timer=setTimeout(myName+'.menus["'+id+'"].setVis('+sh+','+forced+')',50)}}}};FSMenu.animSwipeDown=function(ref,counter,show){if(show&&(counter==0)){ref._fsm_styT=ref.style.top;ref._fsm_styMT=ref.style.marginTop;ref._fsm_offT=ref.offsetTop||0}var cP=Math.pow(Math.sin(Math.PI*counter/2),0.75);var clipY=ref.offsetHeight*(1-cP);ref.style.clip=(counter==1?((window.opera||navigator.userAgent.indexOf('KHTML')>-1)?'':'rect(auto,auto,auto,auto)'):'rect('+clipY+'px,'+ref.offsetWidth+'px,'+ref.offsetHeight+'px,0)');if(counter==1||(counter<0.01&&!show)){ref.style.top=ref._fsm_styT;ref.style.marginTop=ref._fsm_styMT}else{ref.style.top=((0-clipY)+(ref._fsm_offT))+'px';ref.style.marginTop='0'}};FSMenu.animFade=function(ref,counter,show){var done=(counter==1);if(ref.filters){var alpha=!done?' alpha(opacity='+parseInt(counter*100)+')':'';if(ref.style.filter.indexOf("alpha")==-1)ref.style.filter+=alpha;else ref.style.filter=ref.style.filter.replace(/\s*alpha\([^\)]*\)/i,alpha)}else ref.style.opacity=ref.style.MozOpacity=counter/1.001};FSMenu.animClipDown=function(ref,counter,show){var cP=Math.pow(Math.sin(Math.PI*counter/2),0.75);ref.style.clip=(counter==1?((window.opera||navigator.userAgent.indexOf('KHTML')>-1)?'':'rect(auto,auto,auto,auto)'):'rect(0,'+ref.offsetWidth+'px,'+(ref.offsetHeight*cP)+'px,0)')};FSMenu.prototype.activateMenu=function(id,subInd){with(this){if(!isDOM||!document.documentElement)return;var fsmFB=getRef('fsmenu-fallback');if(fsmFB){fsmFB.rel='alternate stylesheet';fsmFB.disabled=true}var a,ul,li,parUL,mRoot=getRef(id),nodes,count=1;var lists=mRoot.getElementsByTagName('ul');for(var i=0;i<lists.length;i++){li=ul=lists[i];while(li){if(li.nodeName.toLowerCase()=='li')break;li=li.parentNode}if(!li)continue;parUL=li;while(parUL){if(parUL.nodeName.toLowerCase()=='ul')break;parUL=parUL.parentNode}a=null;for(var j=0;j<li.childNodes.length;j++)if(li.childNodes[j].nodeName.toLowerCase()=='a')a=li.childNodes[j];if(!a)continue;var menuID=myName+'-id-'+count++;if(ul.id)menuID=ul.id;else ul.setAttribute('id',menuID);var sOC=(showOnClick==1&&li.parentNode==mRoot)||(showOnClick==2);var evtProp=navigator.userAgent.indexOf('Safari')>-1||isOp?'safRtnVal':'returnValue';var eShow=new Function('with('+myName+'){var m=menus["'+menuID+'"],pM=menus["'+parUL.id+'"];'+(sOC?'if((pM&&pM.child)||(m&&m.visible))':'')+' show("'+menuID+'",this)}');var eHide=new Function('e','if(e.'+evtProp+'!=false)'+myName+'.hide("'+menuID+'")');addEvent(a,'mouseover',eShow);addEvent(a,'focus',eShow);addEvent(a,'mouseout',eHide);addEvent(a,'blur',eHide);if(sOC)addEvent(a,'click',new Function('e',myName+'.show("'+menuID+'",this);if(e.cancelable&&e.preventDefault)e.preventDefault();e.'+evtProp+'=false;return false'));if(subInd)a.insertBefore(subInd.cloneNode(true),a.firstChild)}if(isIE&&!isOp){var aNodes=mRoot.getElementsByTagName('a');for(var i=0;i<aNodes.length;i++){addEvent(aNodes[i],'focus',new Function('e','var node=this.parentNode;while(node){if(node.onfocus)node.onfocus(e);node=node.parentNode}'));addEvent(aNodes[i],'blur',new Function('e','var node=this.parentNode;while(node){if(node.onblur)node.onblur(e);node=node.parentNode}'))}}if(hideOnClick)addEvent(mRoot,'click',new Function(myName+'.hideAll()'));menus[id]=new FSMenuNode(id,true,this)}};var page={win:self,minW:0,minH:0,MS:isIE&&!isOp,db:document.compatMode&&document.compatMode.indexOf('CSS')>-1?'documentElement':'body'};page.elmPos=function(e,p){var x=0,y=0,w=p?p:this.win;e=e?(e.substr?(isNS4?w.document.anchors[e]:getRef(e,w)):e):p;if(isNS4){if(e&&(e!=p)){x=e.x;y=e.y};if(p){x+=p.pageX;y+=p.pageY}}if(e&&this.MS&&navigator.platform.indexOf('Mac')>-1&&e.tagName=='A'){e.onfocus=new Function('with(event){self.tmpX=clientX-offsetX;self.tmpY=clientY-offsetY}');e.focus();x=tmpX;y=tmpY;e.blur()}else while(e){x+=e.offsetLeft;y+=e.offsetTop;e=e.offsetParent}return{x:x,y:y}};if(isNS4){var fsmMouseX,fsmMouseY,fsmOR=self.onresize,nsWinW=innerWidth,nsWinH=innerHeight;document.fsmMM=document.onmousemove;self.onresize=function(){if(fsmOR)fsmOR();if(nsWinW!=innerWidth||nsWinH!=innerHeight)location.reload()};document.captureEvents(Event.MOUSEMOVE);document.onmousemove=function(e){fsmMouseX=e.pageX;fsmMouseY=e.pageY;return document.fsmMM?document.fsmMM(e):document.routeEvent(e)};function isMouseIn(sty){with(sty)return((fsmMouseX>left)&&(fsmMouseX<left+clip.width)&&(fsmMouseY>top)&&(fsmMouseY<top+clip.height))}}

var listMenu = new FSMenu("listMenu", false, "display", "block", "none");
listMenu.animations[listMenu.animations.length] = FSMenu.animFade;
listMenu.animations[listMenu.animations.length] = FSMenu.animSwipeDown;
addEvent(window, 'load', new Function('listMenu.activateMenu("listMenuRoot")'));
