//
// ict_common.js 
//
// Author: Michael Urban, WFO Wichita
// Date: March 30, 2005
// Script Description: Common JavaScript functions local to this web site
// Revision:
// Revision Date:
// Revision Description:
//

// Initialize any necessary variables
//
var baseURL = "/ict/";				// ** Base URL location...Change this when moving web page
var blankURL = "";				// Blank URL used in left frame of popup
var strWinProp;					// Global string containing window properties for popups.

//
// checkDates - Ensure end date is later than the beginning date
//
// objForm: Form object containing the form date elements (form object). 
//          Target elements should be named: beginMonth, beginDay, endMonth, endDay.
//
function checkDates(objForm) {

	// Extract the values from the form elements
	//
	// Beginning date values
	//
	var beginMonth = objForm.beginMonth.selectedIndex;
	var beginMonthText = objForm.beginMonth.options[beginMonth].text;
	var beginDay = objForm.beginDay.selectedIndex;
	var beginDayText = objForm.beginDay.options[beginDay].text;
	var beginDate = new Date(2000, beginMonth, beginDay + 1);

	var endMonth = objForm.endMonth.selectedIndex;
	var endMonthText = objForm.endMonth.options[endMonth].text;
	var endDay = objForm.endDay.selectedIndex;
	var endDayText = objForm.endDay.options[endDay].text;
	var endDate = new Date(2000, endMonth, endDay + 1);

	if (endDate >= beginDate) {
		return;
	} else {
		// Swap the beginning and ending date values if the are out of order
		//
		objForm.beginMonth.options[endMonth].selected = true;
		objForm.endMonth.options[beginMonth].selected = true;

		populateDays(objForm.beginDay, objForm.beginMonth.selectedIndex);
		populateDays(objForm.endDay, objForm.endMonth.selectedIndex);

		objForm.beginDay.options[endDay].selected = true;
		objForm.endDay.options[beginDay].selected = true;
	}
}

//
// getImageHeight - Get the height of a specified image
//
function getImageHeight(imageObject) { return imageObject.height; }

// 
// getImageWidth - Get the width of a specified image
//
function getImageWidth(imageObject) { return imageObject.width; }


//
// init - Initialize a popup window with default parameters.  Resultant window will not contain CIF elements
//
// winWidth:  Width of the window in pixels
// winHeight: Height of the window in pixels
//
function init(winWidth, winHeight) {

	// internal width and height.  Adjust intWidth for the end of screen.  Adjust 
	//   intHeight for the Icon Bar at the bottom of the window
	//
	var intWidth = screen.width - 10;
	var intHeight = screen.height - 80;
	var width = winWidth;
	var height = winHeight;

	// Set the properties of the popup window
	//  
	strWinProp = " toolbar=no"		// Back, Forward, etc...
		   + ",location=no"		// URL field
		   + ",directories=no"	// "What's New", etc...
		   + ",status=no"		// Status Bar at bottom of window.
		   + ",menubar=no"		// Menubar at top of window.
		   + ",resizable=yes"	// Resizable attribute
		   + ",scrollbars=yes"	// Displays scrollbars if document is larger than window.
		   + ",titlebar=yes"		// Enable/Disable titlebar resize capability.
		   + ",width="+width		// Width.  Set to intWidth for entire screen
		   + ",height="+height	// Height.  Set to intHeight for entire screen
		   + ",top=0"			// Offset of window's top edge from screen.
		   + ",left=0"		// Offset of window's left edge from screen.
		   + "";  
}

// 
// jumpAlert - Display a JavaScript dialog in lieu of a "jump" page
//
function jumpAlert() {
	var message = "You are now leaving the National Weather Service.\n\n"
		+ "The NWS provides a link to this site because it may contain\n"
		+ "information of interest to you.  This link does not constitute an\n"
		+ "endorsement by the NWS of any information, products or services\n"
		+ "on this site.\n\n"
		+ "Thank you for your cooperation with this NWS Web Policy.\n\n"
		+ "Continue?";

	var retval = window.confirm(message);
	return retval;
}

//
// populateDays - Populate the a form select object with days based on the value of the passed month
//
// targetElement: Target form element (days) to receive the output
// selectIndex:   Value of the selected index of the form element (integer)
//
function populateDays (targetElement, selectIndex) {

	// Create array containing days within the month
	//
	monthDays = new Array(31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
	var daysInMonth = monthDays[selectIndex];

	// Clear the targetElement and load with number of days in the month
	//
	for (var i = 0; i <= targetElement.length; i++) {
		targetElement.options[0] = null;
	}

	for (var i = 0; i < daysInMonth; i++) {
		targetElement.options[i] = new Option(i + 1);
	}

	// Select the first element
	//
	targetElement.options[0].selected = true;
}

// 
// showImage - Display popup window containing only an image with given URL of the image
//
// titleString: Title displayed in the window (string)
// imageURL:    URL displayed in the window
//
function showImage(titleString, imageURL, width, height) {
	var targetImage;
	var documentString;
	var resizeWidth = false;
	var resizeHeight = false;

	// Create a new Image instance
	//
	targetImage = new Image();
	targetImage.src = imageURL;

	// Validate the passed variables
	//
	if (titleString.length == 0) titleString = "";
	if (imageURL.length == 0) return false;

	// Get/Set the dimensions of the desired image
	//
	if (!width) width = getImageWidth(targetImage);
	if (isNaN(width) || width <= 0 || width > screen.width) {
//		width = 640;
		resizeWidth = true;
	}

	if (!height) height = getImageHeight(targetImage);
	if (isNaN(height) || height < 0 || height > screen.height) {
//		height = 480;
		resizeHeight = true;
	}

	if (resizeWidth) width *= 0.75;
	if (resizeHeight) height *= 0.75;

	// Add some space to the right and bottom of the image
	//
	width = width + 10;
	height = height + 20;

	// Initialize the popup window
	//
	init(width, height);

	// Create the document output
	//
	documentString = "<html>\n<head>\n"
		+ "<title>" + titleString + "</title>\n"
		+ "<body>\n"

		+ "<img src='" + imageURL + "'"

	if (resizeHeight) documentString += " height='" + height + "'";
	if (resizeWidth) documentString += " width='" + width + "'";

	documentString += ">\n"
		+ "</body></html>";

	newwin = window.open('', 'imageWindow', strWinProp);
	newwin.document.open();
	newwin.document.write(documentString);
	newwin.document.close();
	newwin.blur();
	newwin.focus();
}

// showGlossary - Display popup window showing AFD Weather Glossary terms
//
// linkName:   Link to the filename to be displayed
// windowName: Name provided to the newly displayed window
//
function showGlossary(linkName, windowName) {
	if (!window.focus) return true;

	var href;
	var newwin;

	if (typeof(linkName) == 'string')
		href=linkName;
	else
		href=linkName.href;

	newwin = window.open(href, windowName, 'width=400,height=180,scrollbars=yes');
	newwin.focus();

	return false;
}

// 
// showWindchillTable - Output the html to create the Wind Chill calculator
//
function showWindchillTable() {
	document.write('<table align="center" border="0" cellpadding="2" width="458" cellspacing="1">' +
		'<tr>' +
		'<td width="448" align="center">' +
		'	<form action="" method="post" name="windform">' +
		'		<table border="1" cellpadding="3" cellspacing="0" width="350" class="default">' +
		'			<tr>' + 
		'				<td align="center">Air Temperature (&ordm;F) =</td>' +
		' 				<td align="center"><input type="text" name="temp" size="6"></td>' +
		'			</tr>' +
		'			<tr>' +
		'				<td align="center">Wind Speed (MPH) =</td>' +
		'				<td align="center"><input type="text" name="wind" size="6"></td>' +
		'			</tr>' +
		'			<tr>' +
		'				<td colspan="2" align="center">' +
		'					<input type="button" value="Calculate Wind Chill" onclick="windChill(this.form)">'+
		'				</td>' +
		'			</tr>' +
		'			<tr>' +
		'			<td align="center">' +
		'				<span class="highlight_blue">Old Wind Chill Index</span>' +
		'				<input name="oldwindchill" type="text" size="6">' +
		'			</td>' +
		'			<td align="center">' +
		'				<span class="highlight_blue">New Wind Chill Index</span>' +
		'				<input name="newwindchill" type="text" size="6">' +
		'			</td>' +
		'			</tr>' +
		'		</table>' +
		'	</form>' +
		'</td>' +
		'</tr>' +
		'</table>');
}

//
// showWindow - Display popup windows with given title and URL
//
// titleString: Title displayed in the window (string)
// targetURL:   URL displayed in right frame (string)
// width:       Desired width of the window, in pixels (integer)
// height:      Desired height of the window, in pixels (integer)
//
function showWindow(titleString, targetURL, width, height) {
	var leftFrame;
	var rightFrame;
	var frameCode;

	// Validate the passed variables
	//
	if (titleString.length == 0) titleString = "National Weather Service Forecast Office - Wichita, KS";
	if (targetURL.length == 0) return false;

	// Ensure width and height are within valid values.  Set to default values, if not.
	//
	if (!width || isNaN(width) || width < 0 || width > screen.width) width = 690;
	if (!height || isNaN(height) || height < 0 || height > screen.height) height = 500;

	// Initialize the popup window
	//
	init(width, height);

	frameCode = "<html><head>\n"
		+ "<title>" + titleString + "</title>\n"
		+ "<link rel='stylesheet' type='text/css' href='" + baseURL + "common/ict_common.css'>\n"
		+ "</head>\n"
		+ "<frameset cols='*,100%' framespacing='0' border='0'>\n"
		+ "<frame src='" + blankURL + "' name='leftframe' noresize scrolling='no'>\n"
		+ "<frame src='" + targetURL + "' name='rightframe' noresize>\n"
		+ "</frameset>\n"
		+ "</html>\n";

	// Open window and write code into it
	//
	newwin = window.open("", "", strWinProp);
	newwin.document.open();
	newwin.document.write(frameCode);
	newwin.document.close();
	newwin.blur();
	newwin.focus();
}

//
// validateStormReport - Validate the storm report form
//
function validateStormReport(submitButton) {
	var formName = document.stormReport;

	// Ensure required fields are present
	//
	// Name
	//
	if (formName.realname.value == "") {
		window.alert("Please enter your name...");
		formName.realname.focus();
		return false;
	}
	//
	// Email
	//
	if (formName.email.value == "") {
		window.alert("Please enter your e-mail address...");
		formName.email.focus();
		return false;
	}

	if (formName.affiliation[0].checked == false && 
	    formName.affiliation[1].checked == false &&
	    formName.affiliation[2].checked == false) {
		window.alert("Please select your affiliation...");
		formName.affiliation[0].focus();
		return false;
	}

	// Place any further validation routines here...
	//

	return true;
}

//
// windChill - Calculate and return the wind chill value (old and new formulas)
//
// -- Modified 9/10/2001: Bryan Ruby, National Weather Service, Sioux Falls -->
// -- Previous Contributers: Darren Collins (WFO FSD), James P. Dildine (jpd@wlsmail.com), Bryan Ruby (bryan.ruby@noaa.gov) -->
function windChill(form) {
	wind=eval(form.wind.value);
	temp=eval(form.temp.value);

	// -- New and Old Wind Chill Equation 
	oldchill=(0.0817*(3.71*(Math.sqrt(wind))+5.81-0.25*wind)*(temp-91.4)+91.4);
	newchill=(35.74+0.6215*temp-35.75*Math.pow(wind,0.16)+0.4275*temp*Math.pow(wind,0.16));

	oldchill=Math.round(oldchill);
	newchill=Math.round(newchill);

	// -- Wind Thresholds --
	oldchill=(wind <= 4) ? temp : oldchill;
	newchill=(wind <= 3) ? temp : newchill;

	// -- Max Ambient Temperature Thresholds --
	oldchill=(temp > 50) ? temp : oldchill;
	newchill=(temp > 50) ? temp : newchill;

	// -- Insert Values Back Into Form Fields --
	form.oldwindchill.value = oldchill;
	form.newwindchill.value = newchill;
}
