//========================================================================
// clientfunctions.js - common client javascript functions
//========================================================================

//========================================================================
// $( element ) - Shorthand method shamelessly stolen from the prototype.js
// library.  Equivalent to document.getElementById(element).
// Wrapped in a if block to allow prototype's version (or others, if 
// applicable) to override it if available.
//
// Note (MCC): I'm not replacing any of the code inside this script to use
// this function over document.getElementById so that none of the functionality
// changes if a different library *does* override it.
//========================================================================
if (typeof($) == 'undefined')
{
	$ = function (element) 
	{
		var elem = document.getElementById(element);
		return elem;
	}
}

//========================================================================
// htmlDecode( content ) - Decodes escaped html characters.  This function
// is a work in progress.  Add new encoded characters to decode as needed.
//========================================================================
function htmlDecode( content ) {
	if( content ) {
		content = replaceAll( content, "&lt;", "<" );
		content = replaceAll( content, "&gt;", ">" );
	}
	return content;
}

//========================================================================
// replaceAll( content, from, to ) - Currently a helper function for 
// htmlDecode.  If you use function elsewhere, please update this comment.
//========================================================================
function replaceAll( content, from, to ) {
	// *** TODO: Need to change this to handle RegExp ***
	var index = content.indexOf( from );
	while( index > -1 ) {
		content = content.replace( from, to );
		index = content.indexOf( from );
	}
	return content;
}


//========================================================================
// isEmpty(theString) - returns false if anything other than whitespace is 
//	found in the string, true otherwise.
//========================================================================
function isEmpty(theString)
{
	var character;
	for (var i = 0; i < theString.length; i++) {	
		character = theString.charAt(i);
		if ( (character != ' ') && (character != '\n') && (character != '\t') )
			return false;
	}	
	return true; //made it through loop, string is empty		
}

//========================================================================
//	OpenNewWindow(...) opens a 'popup' window with the following properties
//
//		mypage = value of "href=..."
//		myname = window name, leave as default value unless opening multiple 
//							windows
//		w = new window width - numeric
//		h = new window height - numeric
//		scrollbars...resizable = yes or no - disables window properties
//========================================================================
function OpenNewWindow(mypage, myname, w, h, scrollbars, toolbar, location, status, menubar, resizable)
{
	var ieWinLeft = (screen.width - w) / 2;
	var ieWinTop = (screen.height - h) / 2;
	
	var navWinLeft = window.screenX + (window.innerWidth/2) - (w/2);
	var navWinTop = window.screenY + (window.innerHeight/2) - (h/2);
	
	var strBrowser = new String(window.navigator.appName);
	
	if (strBrowser == "Microsoft Internet Explorer") {
		winprops =	'height='+h+
					',width='+w+
					',top='+ieWinTop+
					',left='+ieWinLeft+
					',scrollbars='+scrollbars+
					',toolbar='+toolbar+
					',location='+location+
					',status='+status+
					',menubar='+menubar+
					',resizable='+resizable;
	} else {
		winprops =	'height='+h+
					',width='+w+
					',screenY='+navWinTop+
					',screenX='+navWinLeft+
					',scrollbars='+scrollbars+
					',toolbar='+toolbar+
					',location='+location+
					',status='+status+
					',menubar='+menubar+
					',resizable='+resizable;
	}		

	win = window.open(mypage, myname, winprops)

	if (window.focus)
		win.focus();
	
	// Return handle to the new window.
	return win;
}

//========================================================================
// Open window but do not return the window handle (seems to cause problems
// in firefox.
// Parameters:
// page - Path to the page to open
// name - name of the window
// width - width of the window
// height - height of the window
// scrollbars - 'yes' - scrollbars visible; 'no' - scrollbars not visible.
// toolbar - 'yes' - toolbar visible; 'no' - toolbar not visible.
// locationbar - 'yes' - locationbar visible; 'no' - locationbar not visible.
// statusbar - 'yes' - statusbar visible; 'no' - statusbar not visible.
// menubar - 'yes' - menubar visible; 'no' - menubar not visible.
// resizable - 'yes' - resizable visible; 'no' - resizable not visible.
//========================================================================
function openWindow( page, name, width, height, scrollbars, toolbar, locationbar, statusbar, menubar, resizable ) {
	return OpenNewWindow( page, name, width, height, scrollbars, toolbar, locationbar, statusbar, menubar, resizable );
}

function openPopup( page, name, width, height, form) {
	var win = openWindow( page, name, width, height, 'yes', 'no', 'no', 'no', 'no', 'yes' );
	//form refers to a form in the opener window.
	if(form)
	{
		if(!form.method)
		{
			form = document.getElementById(form);
		}
		form.target = name;
		
		var origAction = form.action;
		setTimeout(function(){form.target = ''; form.action = origAction;}, 2000);
	}
	return win;
}

// openNotesWindow() - Open the type notes popup window at a standard size.
function openNotesWindow(form)
{
	openPopup('about:blank', 'type_notes', 660, 590, form);
}

//========================================================================
// hideHelpPopup()
// id = id of the element we wish to hide.
// Hides a help pop up div by setting display to none.
//========================================================================
function hideHelpPopup(id) {
	if( document && document.getElementById ) {
		var element = document.getElementById( id ) ;
		// Set class of element to popupHelpHidden - defined in commonstyles.css
		if( element ) {
			element.className = "popupHelpHidden" ;
			element.style.left = ""; //removing explicit left/top styles (class def remains intact)
			element.style.top = "";	 //in case showHelpPopup has set these.
		}
	}
}

//========================================================================
// showHelpPopup() 
//	Show a help popup div by setting display to block.
//
// id -		id of the element we wish to hide.
// left - Optional. Sets the left coordinate for the block.  Pass in whatever you'd put in css.  (ex. 10px)
// top -	Optional. Sets the top coordinate.  (be sure to set left to "auto" if you only want to set the top)
//========================================================================
function showHelpPopup(id, left, top) {
	if( document && document.getElementById ) {
		var element = document.getElementById( id );
		// Set class of element to popupHelpHidden - defined in commonstyles.css
		if( element ) {
			element.className = "popupHelpVisible";
			if (left)
				element.style.left = left;
			if (top)
				element.style.top = top;
		}
	}
}

// Comment(CJF): These are functions I am planning to use to build an "in-window popup".
function hidePopup(id) {
	if( document && document.getElementById ) {
		var element = document.getElementById( id );
		if( element ) {
			element.style.display = "none";
		} else {
			alert( "javascript version is too old" );
		}
	}
}

function showPopup() {
	if( document && document.getElementById ) {
		var element = document.getElementById( id ) ;
		if( element ) {
			element.style.display = "visible";
		}
	} else {
		alert( "javascript version is too old" );
	}
}


//========================================================================
// setFocus( id ) - Sets the focus on the selected input
// id - id of the selected input.
//========================================================================
function setFocus( id ) {
	if( document && document.getElementById ) {
		var element = document.getElementById( id );
		if( element ) {
			element.focus();
		}
	}
}

//========================================================================
// Capture the enter keypress and submit form
// submitButton must be an anchor or a button.
// Note: when using this function, make sure to return the result to browser
//========================================================================
function captureEnter( buttonId, event ) {
	if( window.event && window.event.keyCode == '13' || event && event.which == '13' ) {
		simulateClick( buttonId );
		return false;
	}
	// Return true (IE gets whiny if you don't).
	return true;
}

//========================================================================
// gotoUrl( url ) - set location of current page to the url passed in.
// url - url of the desired page (resource).
// Note: Be careful with this function.  winIE6 does not send the referer 
// when you attempt to progress this way.
//========================================================================
function gotoUrl( url ) {
	if( url ) {
		alert( url );
		window.location.href = url;
	}
}

//==================================================================================
//	simulateClick( buttonID )
//	Action: cause link or button to be activated by script instead of 
//					direct user action
//
//	Author: clint
//
//	buttonid:		unique id applied to anchor tag or button you'd like to click
//	win:		the window to be looking at.
//==================================================================================
function simulateClick( buttonId, win ) {
	if( buttonId ) {
		if( !win ) win = window;
		var button;
		if( typeof( buttonId ) == 'object' ) {
			button = buttonId;
		} 
		else {
			button = win.document.getElementById( buttonId );
		}
		if( button ) {
			if( button.click ) {
				/* only IE has this function defined for DOM objects that are not buttons. */
				button.click();
			} else if( button.onclick && button.onclick != "" ) {
				/* this works in firefox and opera. */
				if( button.onclick() == true )
				{
				  /* 
				  the above didn't seem to redirect on it's own (manual selection), so i copied the
				  redirection code from below
				  */
				  if( button.href.toLowerCase().indexOf( "javascript" ) > -1 ) {
					  eval(button.href); //TODO: need to update this references between calling eval.
				  } else {
					  win.location = button.href;
				  }
				}
			} else if( button.href ) {
				if( button.href.toLowerCase().indexOf( "javascript" ) > -1 ) {
					eval( button.href );
				} else {
					win.location = button.href;
				}
			}
		}
	}
}

//========================================================================
// prefetchImage( url ) - make browser load the image before
// it needs to display it to prevent flashes.
//========================================================================
function prefetchImage( url ) {
	//alert( "prefetching image: " + url );
	var img = new Image( 1, 1 );
	img.src = url;
}

//========================================================================
// attachFunctionToEvent( function, event, object ) - attaches a function to an event.
// func (function, required) - a reference to the function to be attached.
// ev (string, required) - the name of the event to attach to. (e.g. load)
// Note: use the w3c event names, not the microsoft "on" + eventname events to name
// events.  
// obj (object, required) - the target object to attach the event listener to.
//========================================================================
function attachFunctionToEvent( func, ev, obj ) {
	if( obj ) {
		if( obj.addEventListener ) {
			// this is the w3c spec interface for adding event listeners.
			obj.addEventListener(ev, func, false); 
			return true;
		} else if( obj.attachEvent ) {
			// this is the microsoft interface for adding event listeners.
			obj.attachEvent( "on" + ev, func );
			return true;
		} else {
			alert( "failed to attach event" );
		}
	}
	return false;
}

//========================================================================
// checkEnterPress( evt )
//	evt - the event being processed.
// checks to see if the user pressed the enter key (key #13).
// primarily for use in an input tag's onkeypress event.
// returns true if the key number of the event was 13 (indicating enter was
//	pressed), false otherwise.
//========================================================================
function checkEnterPress(evt)
{
	var keynum
	
	if(window.event) // IE
	{
		keynum = evt.keyCode
	}
	else if(evt.which) // Netscape/Firefox/Opera
	{
		keynum = evt.which
	}
	return (keynum == 13);
}

//========================================================================
// translateEnterToClick( evt, btnId )
//	evt - the event to process.
//	btnId - the ID of the button to click when enter is pressed.
// simulates clicking a specific button if the enter key was pressed.
// used primarily in an input tag's onkeypress event.
//========================================================================
function translateEnterToClick(evt, btnId)
{
	if (checkEnterPress(evt))
	{
		var button = document.getElementById(btnId);
		if (!button)
		{
			return false;
		}
		button.click();
		return false;
	}
	
	return true;
}