// JavaScript Document

var ultraFlag = 1;
var ultraColor = "red";

var foodFlag = 1;
var foodColor = "blue";

//clear values when Start Over clicked
function restart(theForm) {

	theForm.route.length = 0;
	theForm.route_miles.value = 0;
	theForm.minHead.value = 0;
	theForm.hrsHead.value = 0;
	theForm.galTrip.value = 0;
	theForm.galResv1.value = 0;
	theForm.galResv2.value = 0;

	//rebuild list of airports
	makeAptList(theForm);

	//reset mileage selector to All
	theForm.AptsNear[3].checked = 1;
	setWayPoints(theForm);

}

//format numbers
function formatNum(expr,decplaces) {
	var str = (Math.round(parseFloat(expr) * Math.pow(10,decplaces))).toString();
	while (str.length <= decplaces) {
		str = "0" + str;
	} 
	var decpoint = str.length - decplaces;
	return str.substring(0,decpoint) + "." + str.substring(decpoint,str.length);
}

//format minutes
function formatMin(expr,decplaces) {
	var str = (Math.round(parseFloat(expr) * Math.pow(10,decplaces))).toString();
	while (str.length <= decplaces) {
		str = "0" + str;
	} 
	return str;
}


//create values for report
function report(theForm) {

	//stop if not enough waypoints selected
	//if (theForm.route.length < 2) return;
	
	if (theForm.route.length < 2) {
		
		theForm.minHead.value = 0;
		theForm.hrsHead.value = 0;
		theForm.galTrip.value = 0;
		theForm.galResv1.value = 0;
		theForm.galResv2.value = 0;
		return;
		
	}

	//minutes = (distance/airspeed)*60
	
	theForm.minHead.value = (theForm.route_miles.value / theForm.airspeed.value) * 60;
	theForm.minHead.value = formatNum(theForm.minHead.value, 1);
	
	//hours equals minutes / 60	
	theForm.hrsHead.value = theForm.minHead.value / 60;
	theForm.hrsHead.value = formatNum(theForm.hrsHead.value, 1);
	
	//fuel burn = (minutes / 60 ) * fuel rate
	theForm.galTrip.value = (theForm.minHead.value / 60) * theForm.fuel.value;
	theForm.galTrip.value = formatNum(theForm.galTrip.value, 1);
	
	//15 min reserve = fuel burn + (fuel rate * .25)
	
	//used to trap zero distance legs
	theForm.galResv1.value = parseFloat(theForm.galTrip.value) ? formatNum( parseFloat(theForm.galTrip.value) + (parseFloat(theForm.fuel.value) * .25), 1) : formatNum(0, 1);


	//30 min reserve = fuel burn + (fuel rate * .5)
	theForm.galResv2.value = parseFloat(theForm.galResv1.value) ? formatNum( parseFloat(theForm.galTrip.value) + (parseFloat(theForm.fuel.value) * .5), 1) : formatNum(0, 1);

	return;

}

//create an Airport entity, which allows one object to have the properties shown
function Airport(city, name, nbr, latDegrees, latMinutes, longDegrees, longMinutes, elevation, frequency, runway, phone, fuel, note, ultra, food) {

	this.city = city;
	this.name = name;
	this.id = nbr;
	this.degLat = latDegrees;
	this.minLat = latMinutes;
	this.degLong = longDegrees;
	this.minLong = longMinutes;
	this.elev = elevation;
	this.freq = frequency;
	this.rw = runway;
	this.ph = phone;
	this.fuel = fuel;
	this.note = note;
	this.ultra = ultra;
	this.food = food;

}

function makeAirports() {

	//for each airport in the database
	for (i=0; i<aptData.length; i++) {

	//temporarily split it and store in array "ken"	
	var ken = aptData[i].split(",");

	//convert temporary array into an Airport entity
	airports[airports.length] = new Airport(
	ken[0].toString(),
	ken[1].toString(),
	ken[2].toString(),
	ken[3].toString(),
	ken[4].toString(),
	ken[5].toString(),
	ken[6].toString(),
	ken[7].toString(),
	ken[8].toString(),
	ken[9].toString(),
	ken[10].toString(),
	ken[11].toString(),
	ken[12].toString(),
	ken[13].toString(),
	ken[14].toString()
	);

	//clear temporary array, then repeat until done
	ken = "";
	
	}

}

//rounding function
function round(n) {
   if(n < 0.01) return 0;
   if(n <= 10) mult = 100;
   if((n > 10) && (n < 100))  mult = 10;
   if(n >= 100) mult = 1;
   return parseInt((n * mult) + 0.5) / mult;
}

var distance = 0;

//calculate total distance of route
function calcRoute(theForm) {

	//stop if not enough waypoints selected
	//if (document.apt.route.length < 2) return;
	if (theForm.route.length < 2) {
		
		theForm.route_miles.value = 0;
		return;
		
	}
	

	//reset total distance counter variable
	if (distance) distance = 0;

	//set up waypoints for point-to-point calculation
	for (j = 0; j < theForm.route.options.length-1; j++) {

		//get first pair of waypoints in var's start and end
		var tmpOption = theForm.route.options[j].text.split(",");
		var start = tmpOption[1].slice(1);
		
		var tmpOption = theForm.route.options[j+1].text.split(",");
		var end = tmpOption[1].slice(1);

	//Search for matching Airport entities based on name property of "start" and "end"
	for (i = 0; i < airports.length; i++) {
		if (start == airports[i].name) {
			
			//Reset first waypoint to matching Airport entity
			start = airports[i];
			
		}
		
		if (end == airports[i].name) {
			
			//Reset second waypoint to matching Airport entity
			end = airports[i];
			
		}
	}
	
	//increment total distance counter; calc function returns distance between points
	distance += parseFloat(calc(start, end));
	
	}	//end outside FOR

	//set form value
	theForm.route_miles.value = formatNum(distance, 1);
	
}

//calculates miles between two points
function calc(start, end) {

   //massage longitude of first waypoint
   rad = 0.01745566;
   LoAdeg = start.degLong;
   LoAmin = start.minLong;
   if((LoAdeg == "") || (LoAmin == "")) return;
   LoAdeg = parseFloat(LoAdeg); LoAmin = parseFloat(LoAmin);
   LoA = LoAdeg + (LoAmin / 60);
   if(LoA > 180) return;

   //massage longitude of second waypoint
   LoBdeg = end.degLong;
   LoBmin = end.minLong;
   if((LoBdeg == "") || (LoBmin == "")) return;
   LoBdeg = parseFloat(LoBdeg); LoBmin = parseFloat(LoBmin);
   LoB = LoBdeg + (LoBmin / 60);
   if(LoB > 180) return;
   Lo = Math.abs(LoA - LoB);

   //massage latitude of first waypoint
   LatAdeg = start.degLat;
   LatAmin = start.minLat;
   if((LatAdeg == "") || (LatAmin == "")) return;
   LatAdeg = parseFloat(LatAdeg); LatAmin = parseFloat(LatAmin);
   LatA = LatAdeg + (LatAmin /60);
   if(LatA > 90) return;

   //massage latitude of second waypoint
   LatBdeg = end.degLat;
   LatBmin = end.minLat;
   if((LatBdeg == "") || (LatBmin == "")) return;
   LatBdeg = parseFloat(LatBdeg); LatBmin = parseFloat(LatBmin);
   LatB = LatBdeg + (LatBmin /60);
   if(LatB > 90) return;

   //determine distance in radians
   with(Math) {
      Drad = acos((sin(LatA*rad)*sin(LatB*rad))+
            (abs(cos(LatA*rad))*abs(cos(LatB*rad))*cos(Lo*rad)));
   }

   //convert to miles and return value
   var result_miles = " "+ round(Drad * 3956.316186);
   return result_miles;
   
}


function makeAptList(theForm) {

	theForm.airports.options.length = 0;
	theForm.airports.options.length = aptData.length;


	//load each airport name into the select box
	for (i = 0; i < aptData.length; i++) {
		theForm.airports.options[i].text = airports[i].city + ", " + airports[i].name + ", " + airports[i].id;

		if ( ultraFlag && airports[i].ultra ) { //item is UL friendly) 
		
			theForm.airports.options[i].style.color = ultraColor;
		
		}

		if ( foodFlag && airports[i].food ) {//item has food onsite or very near

			theForm.airports.options[i].style.color = foodColor;

		}

	}


	switch (siteID) {
		
		case 0 : //do nothing
		break;
		
		case 2 : setDefault("STA-Lite Aviation",theForm);
		break;
		
		default : setDefault("Ray Community",theForm);
		
	}

/*
	if (siteID == 1 || siteID == 3) {
	
		setDefault("Ray Community",theForm);	//set Ray as home for me
	}
	
	if (siteID==2) {
	
		setDefault("STA-Lite Aviation",theForm);	//set STA-Lite as home for Steve
	}
*/

}

function setDefault(defApt,theForm) {

	// sets the default selection
	for (i = 0; i < theForm.airports.options.length; i++) {

		var tmpOption = theForm.airports.options[i].text.split(",");
		tmpOption[1] = tmpOption[1].slice(1);

		//if (apt.airports.options[i].text == defApt) {
		if (tmpOption[1] == defApt) {
			theForm.airports.options[i].selected = true;
		}

	}

}


//highlight airports within selected radius
function showNear(nearMe,theForm) {

	//abort if no starting point selected
	if (theForm.route.options.length==0) {
		
		return;
	}
	
	else {
	
		//clear list of airports
		theForm.airports.options.length = 0;

	}

	//set var start to first item in route list
	var tmpOption = theForm.route.options[0].text.split(",");
	var start = tmpOption[1].slice(1);

	//find corresponding airport entity and assign to var start
	for (i=0; i<airports.length; i++) {

		if (start == airports[i].name) {
			start = airports[i];
		}
	}

	//create an index array
	var mw = new Array();

	//determine which airports are less than selected distance
	for (i=0; i<airports.length; i++) {
	
		//set each item in airport entity array to var end
		end = airports[i];

		//calculate distance between start and end
		var locDistance = calc(start, end);
		//if distance greater than selected distance (var nearMe), flag for deletion
		(locDistance > nearMe) ? mw[i] = 0 : mw[i] = 1;

	}

	//rebuild list of airports
	for (i=0; i<mw.length; i++) {
		if (mw[i] == 1) {
			theForm.airports.options.length++;
			theForm.airports.options[theForm.airports.options.length-1].text = airports[i].city + ", " + airports[i].name + ", " + airports[i].id;

				if ( ultraFlag && airports[i].ultra ) {
					theForm.airports.options[theForm.airports.options.length-1].style.color = ultraColor;
				}

				if ( foodFlag && airports[i].food ) {

					theForm.airports.options[theForm.airports.options.length-1].style.color = foodColor;

				}

		}

	}

	// resets the default selection to the originating waypoint

	var tmpOption = theForm.route.options[0].text.split(",");
	setDefault(tmpOption[1].slice(1),theForm);

	// resets waypoint counter
	setWayPoints(theForm);

}


//list manipulation functions

//Copy selected airport to flight plane
function copySelectedApt(theForm) {
	
	//find selected item in list of airports
	for (i = 0; i < theForm.airports.options.length; i++) {
		if (theForm.airports.options[i].selected) {
			
			//increase length of route array by 1
			theForm.route.options.length++;
			
			//Slice selection into components
			var tmpOption = theForm.airports.options[i].text.split(",");
			
			//set new route array element to selected airport name and ID
			theForm.route.options[theForm.route.options.length-1].text =
				tmpOption[0] + ", " + tmpOption[1].slice(1) + ", " + tmpOption[2].slice(1);
		}
	}
}


//delete selected airport from route
function delSelectedApt(theForm) {
	
	//find selected airport
	for (i=0; i<theForm.route.options.length; i++) {
		if (theForm.route.options[i].selected) {
			//delete it; list array collapses automatically
			theForm.route.options[i] = null;
		}
	}
}

//delete last airport in route list
function delApt(theForm) {
	theForm.route.options.length--;
}


//load apt data was here


function aptInfo() {

if (!document.all) {

	// go to internet routine for non-IE browsers
	aptInfo2();

	}

else {

	//Get option text
	var apt = findSelectedApt(document.forms[0]).split(",");
	
	for (i=0; i<airports.length; i++) {
	
		//if airport names match
		if (apt[1].slice(1) == airports[i].name) {

			//display info in popup
			var ken = window.createPopup();

			ken.document.body.style.fontFamily = "arial, helvetica, sans-serif";
			ken.document.body.style.fontSize = "12px";
			ken.document.body.innerHTML = "<b>" + airports[i].city + ", " + airports[i].name + ", " + airports[i].id + "<br>GPS:</b> N" + airports[i].degLat + "&deg; " + airports[i].minLat + "&#8242;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;W" + airports[i].degLong + "&deg; " + airports[i].minLong + "&#8242;<br><b>Elev:</b> " + airports[i].elev + "<br><b>Freq:</b> " + airports[i].freq + "<br><b>Runways:</b> " + airports[i].rw + "<br><b>Phone:</b> " + airports[i].ph + "<br><b>Fuel:</b> " + airports[i].fuel + "<br><b>Notes:</b> " + airports[i].note + "<p style='text-align:center; font-weight: bold'>Click anywhere outside this box to close it.</p>";
			ken.document.body.style.border="3px solid #08A3BC";
			ken.document.body.style.padding = "3px";

			//popup.show(X, Y, Width, Height)
			ken.show(175,75,300,220,document.body);
			break;
			}
	
	}

}

}

function findSelectedApt(theForm) {

	//find selected airport
	for (i=0; i<theForm.airports.options.length; i++) {
		if (theForm.airports.options[i].selected) {

			//assign selection text to variable for passback
			var aptID = theForm.airports.options[i].text;
			break;
		}
	}
	
	return aptID;

}

/*///////////////////////////////

function findSelectedApt() {

	//find selected airport
	for (i=0; i<document.apt.airports.options.length; i++) {
		if (document.apt.airports.options[i].selected) {

			//assign selection text to variable for passback
			var aptID = document.apt.airports.options[i].text;
			break;
		}
	}
	
	return aptID;

}

////////////////////////////*/


function aptInfo2() {

	//Get option text
	var apt = findSelectedApt(document.forms[0]).split(",");
	var aptID = apt[2].slice(1);
	
	//var theURL = "http://www.ipilot.com/airport/apinfo.asp?li=" + aptID
	
	var theURL = "http://www.airnav.com/airport/" + aptID;

	window.open(theURL, "", "resizable,scrollbars,width=750,height=540");

}



function printPlan(theForm) {

	var enroute = 0;

	if (theForm.route.options.length == 0) return;

	//720,540,576,432,432,324
	var theURL = window.open("", "", "menubar,scrollbars,toolbar,status,resizable,width=576,height=432");

	theURL.document.write("<html><title>Flight Planner by Ken Fackler</title><style>body {font-family: 'Times New Roman', Times, serif;font-size: 1em;}</style><body>");

	theURL.document.write("<p><input type='button' value='Print Now' onClick='window.print();close()'></p>");

	for (j=0; j<theForm.route.options.length; j++) {
	
		//for each, split text into tmp array
		//compare tmp array [0] to airports
		//when match, write desired results
		
		var tmpArray = theForm.route.options[j].text.split(",");
		var tmpEntity = findEntity(tmpArray);

		if (j>0) {
			var tmpArray2 = theForm.route.options[j-1].text.split(",");
			var tmpEntity2 = findEntity(tmpArray2);
		}
		else {
			var tmpEntity2 = tmpEntity;
		}


		if (j == 0) {

			theURL.document.write("<br /><p><strong>Starting point:</p>");

		}

		else {
	
			theURL.document.write("<br /><p><strong>Fly true course " +  compute(tmpEntity2, tmpEntity) +  "&deg; for " + formatNum( calc(tmpEntity, tmpEntity2), 1) + " miles to:</p>");

			enroute += parseFloat( calc(tmpEntity, tmpEntity2) );

		}
		
		theURL.document.write("<p>" + tmpEntity.city + ", " + tmpEntity.name +  ", " + tmpEntity.id + "<br>GPS:</strong> N" + tmpEntity.degLat + "&deg; " + tmpEntity.minLat + "&#8242;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;W" + tmpEntity.degLong + "&deg; " + tmpEntity.minLong + "&#8242;<br><b>Elev:</b> " + tmpEntity.elev + "<br><b>Freq:</b> " + tmpEntity.freq + "<br><b>Runways:</b> " + tmpEntity.rw + "<br><b>Phone:</b> " + tmpEntity.ph + "<br><b>Fuel:</b> " + tmpEntity.fuel + "<br><b>Notes:</b> " + tmpEntity.note);

		if (enroute > 0) {

			theURL.document.write("<br><b>Total distance:</b> " + formatNum(enroute, 1) + " miles</p><hr>");

		}

		else {

			theURL.document.write("</p><hr>");

		}

	} //end For
	

	//Report flight distance and time; apt.route_miles.value
	theURL.document.write("<p><strong>Duration:</strong> " + theForm.minHead.value + " minutes</p><p><strong>Flight time:</strong> " + theForm.hrsHead.value + " hours</p>");
	
	//report flight fuel requirements
	theURL.document.write("<p><strong>Minimum fuel:</strong> " + theForm.galTrip.value + " gallons</p><p><strong>Fuel with 15 min. reserve:</strong> " + theForm.galResv1.value + " gallons</p><p><strong>Fuel with 30 min. reserve:</strong> " + theForm.galResv2.value + " gallons</p>");

	theURL.document.write("</body></html>");

	//required to see the output properly
	theURL.document.close();

}

function findEntity(waypoint) {

	for (i=0; i<airports.length; i++) {
		
			if (waypoint[1].slice(1) == airports[i].name) {
			
				waypoint = airports[i];
				break;
			
			}
			
	}

	return waypoint;

}


//complete route in reverse
function goHome(theForm) {

	//initialize new, empty array
	var rtnHome = new Array();

	//transfer elements of current route to array rtnHome
	for (i=0; i<theForm.route.options.length; i++) {

		rtnHome[i] = theForm.route.options[i].text;

	}

	//delete last element and then reverse the course
	rtnHome.pop();
	rtnHome.reverse();

	//add each element in array rtnHome to end of route
	for (i=0; i<rtnHome.length; i++) {

		theForm.route.options.length++
		theForm.route.options[theForm.route.options.length-1].text = rtnHome[i];
	}

	//refresh calculations
	calcRoute(theForm);
	report(theForm);

}

function setWayPoints(theForm) {
	
	theForm.waypoints.value = theForm.airports.length;
	
}

////////////////////////  PERSONAL CUSTOMIZATION ROUTINES //////////////////////////

function getPrompt(theRoute) {

	if (theRoute.length < 1) {
		return 0;
	}

	var thePrompt = theRoute[theRoute.length-1].text;
	thePrompt = thePrompt.split(", ")[0];

	return thePrompt;

}

function bakeCookie(theForm) {

	if (getCookie("cookieList") == null) {

		setCookie('cookieList','BLANK',90);

	}

	var apt_prompt = getPrompt(theForm.route);

	if (apt_prompt == 0) return s("You can't save an empty flight plan.");
	var cookieName = prompt("Plan name:\n",apt_prompt);

	if (cookieName == "" || cookieName == null) {

		return;

	}

	storeIt(theForm,cookieName,10);

	updateCookieList(cookieName);

	return;

}

function updateCookieList(name) {

	var tmpList = getCookie("cookieList");

	if (tmpList == "BLANK") {
		var cookieList = new Array();
	}
	else {
		var cookieList = tmpList.split(",");
	}


	//check for too many cookies, max 6
	if (cookieList.length > 5) {

		return s("Too many flight plans.\nDelete one or more before saving.");

	}






	//check for existing
	if ( tmpList.indexOf(name) == -1 ) {

		//new, so add it
		cookieList.push(name);

	}

	cookieList.sort();

	//update master list
	setCookie("cookieList",cookieList,90);

	return;

}

function loadCookieList(theForm,theCookie) {

	//erase existing list of options
	theForm.options.length=0;

	if (getCookie(theCookie) == null) {

		theForm.options.length++;
		theForm.options[0].text = "BLANK";
		return;

	}

	var cookieList = getCookie(theCookie).split(",");

	theForm.options.length++;
	theForm.options[0].text = "-SELECT-";

	for (i=0; i<cookieList.length; i++) {

		theForm.options.length++;
		theForm.options[i+1].text = cookieList[i];

	}

	return;

}

function showPlans(theForm,theCookie) {

	if (getCookie(theCookie) == "BLANK" || getCookie(theCookie) == null) {

		return s("No flight plans found.");

	}

	//if only one saved route, load it immediately
	var cookieList = getCookie("cookieList").split(",");
	if (cookieList.length == 1) {

		recallPlan(theForm,1);

	}

	else {

		//otherwise load the drop-down list
		theForm.plan.style.display = "block";
		loadCookieList(theForm.plan,theCookie);

	}

	return;

}

function recallPlan(theForm,thePlan) {

	var cookieList = getCookie("cookieList").split(",");
	var theCookie = cookieList[thePlan-1];

	// check here to see if it exists
	if (getCookie(theCookie) == null) {

		killPlan(theForm,thePlan);

		return s("No flight plan by that name is available.\nThis item was removed from the list.");

	}

	restoreIt(theForm,theCookie);

	return;

}

function previewKill(theForm,theCookie) {

	if (getCookie(theCookie) == "BLANK" || getCookie(theCookie) == null) {

		return s("No flight plans found.");

	}

	var cookieList = getCookie("cookieList").split(",");

	theForm.killer.style.display = "block";
	loadCookieList(theForm.killer,theCookie);

	return;

}

function killPlan(theForm,planToKill) {

	if (planToKill == 0) {

		return;

	}

	var cookieList = getCookie("cookieList").split(",");

	var removed = cookieList.splice(planToKill-1,1);

	setCookie('cookieList',cookieList,90);

	delCookie(removed);

	return;

}

function findCity(theForm,theLetter) {

	for (i = 0; i < theForm.airports.options.length; i++) {

		var tmpOption = theForm.airports.options[i].text.split(",");

		tmpOption[0] = tmpOption[0].substring(0,1);

		//if (apt.airports.options[i].text == defApt) {
		if (tmpOption[0] == theLetter) {
			theForm.airports.options[i].selected = true;
			break;
		}

	}

}

function showKey(theForm,msg) {

	findCity(theForm,msg);

	theForm.jump.value = "";
	theForm.jump.style.display = "none";

	return;
	

}

function showSearch(theForm) {

	theForm.jump.style.display = "block";
	theForm.jump.focus();

	return;

}

function addWaypoints(arrApts) {

	for (i=0; i<waypoints.length; i++) {

		arrApts.push(waypoints[i]);

	}


	return arrApts;

}

function routeAdjDn(theForm) {

	//convenience statements
	var x = theForm.route.options;

	//if not at least two waypoints, or none selected, there's nothing to do, so ignore
	if (x.length < 2 || theForm.route.selectedIndex < 0) return;
	
	//if there's no room to move it down, quit
	if( (theForm.route.selectedIndex+1) == theForm.route.options.length) return;
	
	//get text of current selected and next
	var y = theForm.route.selectedIndex;
	var z = y + 1;

	var tmp = x[y].text;
	
	x[y].text = x[z].text;
	x[z].text = tmp;
	
	theForm.route.selectedIndex++;
	
	//refresh the data
	calcRoute(theForm);
	report(theForm);

}

function routeAdjUp(theForm) {

	//convenience statements
	var x = theForm.route.options;

	//if not at least two waypoints, or none selected, there's nothing to do, so ignore
	if (x.length < 2 || theForm.route.selectedIndex < 0) return;
	
	//if there's no room to move it up, quit
	if(theForm.route.selectedIndex == 0) return;
	
	//get text of current selected and next
	var y = theForm.route.selectedIndex;
	var z = y - 1;

	var tmp = x[y].text;
	
	x[y].text = x[z].text;
	x[z].text = tmp;
	
	theForm.route.selectedIndex--;

	//refresh the data
	calcRoute(theForm);
	report(theForm);

}