/////////////////////////////////////////////////////////////////////////////////////////
// js_utils.js
// Contains all utility functions which are common to the external applications
/////////////////////////////////////////////////////////////////////////////////////////

/////////////////////////////////////////////////////////////////////////////////////////
// Table of Contents
/////////////////////////////////////////////////////////////////////////////////////////

// DREAMWEAVER FUNCTIONS

// MM_swapImgRestore ()					Restores image to off state onMouseOut.
// MM_preloadImages ()					Preloads all swap images.
// MM_findObj (n, d)					Help function for image swap.
// MM_swapImage()						Swaps image onMouseOver.
// MM_displayStatusMsg(msgStr) 			Displays status message.
// MM_jumpMenu							Jump menu function onChange. onChange="MM_jumpMenu('parent',this,0)"

// BASIC DATA VALIDATION FUNCTIONS:

// isAllSpaces						   	Check whether s is empty or only whitespace; uses isEmpty.
// isAlphaNumeric						Checks whether s is a string.
// isAlphaOnly							Checks whether s is only alpha characters.
// isNumeric							Checks whether s is only numbers.
// isPhoneNumber						Checks for valid phone number (US or international).
// isSpecialChars						Checks for special characters in a string.
// isValidEmail							Checks for valid email address.
// isWhitespace (s)                   	Checks for whitespace in string.
// isDateString							Method to validate a date string for the mm/dd/yyyy format

// FUNCTIONS TO REFORMAT DATA

// stripIntialWhitespace				Removes whitespace at front of string					
// trimElement							Removes whitespace only at front and end of string	
// trim								    trimElement and sets the value to the trimmed string.		
// checkValue							disallows > and < chars and converts to &gt and &lt for HTML rendering

// MISC HELPER FUNCTIONS
// checkNames							Validate username and password at logon.
// clearForm							Clear form so that values are erased.
// closeReloadWin						Closes popup window; returns to and reloads parent window.
// goBackAfterSubmit					Returns updated popup; reloads the parent window to show updated results.
// openWindow							Opens link in new window.
// putFocus								Puts cursor focus in form element.
// putSelect							Forces select on form element; use for form validation.
// sniffer								Checks browser; displays datepicker for IE.


/////////////////////////////////////////////////////////////////////////////////////////
// Global Variables
/////////////////////////////////////////////////////////////////////////////////////////

// time vars
var timeFlag = false;
var startTime;
var endTime;
var whitespace = " \t\n\r";

/////////////////////////////////////////////////////////////////////////////////////////
// DREAMWEAVER FUNCTIONS
/////////////////////////////////////////////////////////////////////////////////////////

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}

function MM_findObj(n, d) { //v3.0
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document); return x;
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function MM_displayStatusMsg(msgStr) { //v1.0
  status=msgStr;
  document.MM_returnValue = true;
}

function MM_jumpMenu(targ,selObj,restore){ //v3.0
  eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
  if (restore) selObj.selectedIndex=0;
}

/////////////////////////////////////////////////////////////////////////////////////////
// BASIC DATA VALIDATION FUNCTIONS
/////////////////////////////////////////////////////////////////////////////////////////


//-------------isAllSpaces---------------------------------------------------------------
// Returns true if string s is empty or whitespace characters only.
// For use when only white spaces are entered in required field.
// Comparable to isAllSpaces

function isAllSpaces (s)

{   var i;

    // Is s empty?
    if (isEmpty(s)) return true;

    // Search through string's characters one by one
    // until we find a non-whitespace character.
    // When we do, return false; if we don't, return true.

    for (i = 0; i < s.length; i++)
    {   
        // Check that current character isn't whitespace.
        var c = s.charAt(i);

        if (whitespace.indexOf(c) == -1) return false;
    }

    // All characters are whitespace.
    return true;
}
//end isAllSpaces


//-------------isAlphaNumberic------------------------------------------------------------
// Check that a string contains only letters and numbers

function isAlphaNumeric(string, ignoreWhiteSpace) {
	if (string.search) {
		if ((ignoreWhiteSpace && string.search(/[^\w\s]/) != -1) || (!ignoreWhiteSpace && string.search(/\W/) != -1)) return false;
	}
	return true;
}
//end isAlphaNumeric


//-------------isAlphaOnly----------------------------------------------------------------
// Check that a string contains only letters

function isAlphaOnly(string, ignoreWhiteSpace) {
	if (string.search) {
		if ((ignoreWhiteSpace && string.search(/[^a-zA-Z\s]/) != -1) || (!ignoreWhiteSpace && string.search(/[^a-zA-Z]/) != -1)) 			  return false;
	}
	return true;
}
//end isAlphaOnly


//-------------isEmpty-------------------------------------------------------------------
// Check whether string s is empty.

function isEmpty(s){   

	return ((s == " ") || (s.length == 0))
}
//end isEmpty


//-------------isNumeric-----------------------------------------------------------------

// Check that a string contains only numbers
function isNumeric(string, ignoreWhiteSpace) {
	if (string.search) {
		if ((ignoreWhiteSpace && string.search(/[^\d\s]/) != -1) || (!ignoreWhiteSpace && string.search(/\D/) != -1)) return false;
	}
	return true;
}
//end is Numeric


//-------------isPhoneNumber-------------------------------------------------------------
//return true if phoneValue is a valid Phone Number, false otherwise.

function isPhoneNumber( phoneValue_ )
{
  var pNum = trim( phoneValue_ );

	// Empty string is valid
	if(pNum.length == 0) 
		return true;

  for( var i = 0; i < pNum.length; i++ ) 
  {
    var c = pNum.charAt(i);
    
    // Check if it's a  number
    if ( !isNaN( c ) )
			continue;
    
		// Check if it's a lowercase letter
	  else if ( c >= 'a' && c <= 'z')
		    continue;
    
		// Check if it's an uppercase letter
	  else if ( c >= 'A' && c <= 'Z')
		    continue;
    
		// Check if it's one of the other accepted characters: - ( ) . / \ + # * (space)
	  else if (c == '-' 
					|| c == '(' 
					|| c == ')' 
					|| c == '/' 
					|| c == '\\' 
					|| c == '.' 
					|| c == '+' 
					|| c == '#' 
					|| c == '*' 
					|| c == ' ' 
					)
		    continue;
		    
		else
		{
		  alert("Please enter a valid phone number.");
			return false;
		}
  }

	return true;
}




// end isPhoneNumber


//-------------isSpecialChars---------------------------------------------------------------
//Checks for special characters in string.

function isSpecialChars(filestr)
{
  var regexp = /[\/\\:|&<>\"?^()@#$%-+=*{}~!`_;\[\],]/;

  return( containsChar( filestr, regexp ) );
}

//end hasSpecialChars


//-------------isValidEmail---------------------------------------------------------------
// 
//isValidEmail: test if a string is formatted as an email
// returns: true or false
function isValidEmail(email) {

	if (!hasPreText(email)) {
		//alert("no pretext...");
		return false;
	}
	else if(!hasAt(email)) {
		//alert("no at symbol...");
		return false;
	}
	else if (!hasDot(email)) {
		//alert("no dot...");
		return false;
	}
	else if (!hasFoo(email)) {
		//alert("no foo...");
		return false;
	}
	else {
		return true;
	}
	
	
}

// *********************************
//Begin supporting isEmail functions

// hasPreText: tests if the first character is not the @ symbol
// returns: true or false
function hasPreText(email) {

	if (email.charAt(0) != "@") {
		
		return true;
	
	}
	else return false;

}

// hasAt: tests if there is an at symbol in the string
// returns: true or false
function hasAt(email) {

	var isAt = 0;
	
	//looping through the characters in the string...
	for (var i=0; i<email.length;i++) {
	
		//first check to see if the string has the @ symbol...
		if (email.charAt(i) == "@") {
			isAt = 1;			
			break;
		}
	
	}
	
	if (isAt) {
		return true;
	}
	else return false;

}

// hasDot: tests if there is a "." in the email, after the @ symbol
// returns: true or false
function hasDot(email) {

	var emailFromAt = email.substring(email.indexOf("@")+1);
	var isDot = 0;
	//alert("emailFromAt = " + emailFromAt);

	//check if the first character of the fromAt string is a dot...
	if (emailFromAt.charAt(0) != ".") {
		//alert("the first char is not a dot...");

		//now loop through the trimmed string to see if there is a dot
		for (var i=0; i<emailFromAt.length; i++) {
		
			if (emailFromAt.charAt(i) == ".") {
				isDot = 1;
				break;
			}
		
		}
		
		if (!isDot) {
			return false;
		}
		else return true;
		
	}
	else return false;

}

// hasFoo: tests if email includes text after the "."
// returns: true or false
function hasFoo(email) {

	var emailFromLastDot = email.substring(email.lastIndexOf(".")+1);
	//alert("emailFromLastDot = " + emailFromLastDot);
	
	if ( (emailFromLastDot == -1) || (emailFromLastDot.length<1) ) {
		return false;
	}
	else return true;

}
// End supporting email functions...
// *********************************

// end isValidEmail



// function:isDateString( FormTextField )
//
// Method is to validate Date entered
function isDateString( value ) {
// Method is to allow the Date object to parse the string.  
// However, we first extract the year from the string.  This is simple
// Since almost all date formats end with the year in digits.  We need
// to extract the year to handle two digits properly.  The date object
// treats any number between 0 and 99 as automatically being in the 1900's.
// We change it to follow this formula: 
//		if ( year > 25 and  < 100 ) we add 1900 to it
//		if ( year < 25 we add 2000 to it
//
	var s = trim(value);
	// Empty string is valid
	if(s.length == 0) 
		return s;

	var i = s.length - 1;
	for (; i >= 0; i--) {
		var n = s.charCodeAt(i);
		if(n < 48 || n > 57) { // is a digit
		break;	
		}
	}

	// Get year
	var yr = parseInt(s.substring(i + 1));
	if( isNaN(yr) )
		return null;

    if (yr < 25) yr += 2000;
    if (yr < 100) yr += 1900;
    if (yr < 1000) return null;

	// Get string for day and month
	var daymon = s.substring(0,i+1);
	daymon = trim(daymon);
	var len = daymon.length;
	if (daymon.charAt(len-1) == "/" || daymon.charAt(len-1) == "-") {
		daymon = daymon.substring(0, len-1);
		daymon = trim(daymon);
		len = daymon.length;
	}

	// Find month (first or second position)
	//  month can be entered as text in either position
	//  if entered as numeric, it should always be first
	var charlast = s.charCodeAt(len-1);
	var monFirst = true;
	var monText = false;
	if(charlast < 48 || charlast > 57) 
	{
		monFirst = false;
		monText = true;
	}

	// Now get day and mon as entered
	var dayEntered = ""
	var monEntered = ""
	if (monFirst) {
		var n = daymon.charCodeAt(0);
		if(n < 48 || n > 57) { // is a digit
			monText = true;
		} else {
			for (i=0; i < daymon.length; i++) {
				var n = daymon.charCodeAt(i);
				if(n < 48 || n > 57) { // is a digit
				break;	
				}
			}
			monEntered = daymon.substr(0,i);
		}

		i = daymon.length - 1;
		for (; i >= 0; i--) {
			var n = daymon.charCodeAt(i);
			if(n < 48 || n > 57) { // is a digit
				break;	
			}
		}
		dayEntered = daymon.substr(i + 1);
	} else {
		for (var i=0; i < daymon.length; i++) {
			var n = daymon.charCodeAt(i);
			if(n < 48 || n > 57) { // is a digit
			break;	
			}
		}
		dayEntered = daymon.substr(0,i);

		i = daymon.length - 1;
		if(!monText) {
			for (; i >= 0; i--) {
				var n = daymon.charCodeAt(i);
				if(n < 48 || n > 57) { // is a digit
					break;	
				}
			}
			monEntered = daymon.substr(i + 1);
		}
	}

	var dateObj = new Date( s );
	if( isNaN(dateObj) ) {
		return null; 
	}
	else {
		// Make Month and Date double-digit
		var m = dateObj.getMonth() + 1;

		// If parsed mon is not same as entered mon, return error
		if (!monText && m != monEntered)
			return null;

		if(m < 10)
		m = 0 + "" + m;

		var d = dateObj.getDate();

		// If parsed day is not same as entered day, return error
		if (d != dayEntered)
			return null;

		if(d < 10)
		  d = 0 + "" + d;

	}
	return ( m + "/" + d + "/" + yr ); 
}




/////////////////////////////////////////////////////////////////////////////////////////
// FUNCTIONS TO REFORMAT DATA
/////////////////////////////////////////////////////////////////////////////////////////

//-------------stripInitialWhitespace------------------------------------------------------------
// Removes initial (leading) whitespace characters from s.
// Global variable whitespace (see above)
// defines which characters are considered whitespace.

function stripInitialWhitespace (s)

{   var i = 0;

    while ((i < s.length) && charInString (s.charAt(i), whitespace))
       i++;
    
    return s.substring (i, s.length);
}
// end stripInitialWhitespace


//-------------trim--------------------------------------------------------------------------------
// removes whitespace only at front and end of string
function trim( s ) { 
  if(s.length == 0)
    return s;

  var i = 0, j = s.length - 1;

  for(; i <= j; i++) {
    var c = s.charAt(i);
    if(c != ' ' & c != '\n' & c != '\t')
      break;
  }

  // If i passed j, we have an empty string
  if(i > j)
    return "";
  
  for(; j > i; j--) {
    var c = s.charAt(j);
    if(c != ' ' & c != '\n' & c != '\t')
      break; 
  } 

  if (i > 0 || j < s.length - 1)
    return s.substring(i, j + 1);
  else
    return s;
}
//end trim

//-------------trimElement------------------------------------------------------------------------
// removes whitespace only at front and end of element value
// and sets the value to the trimmed string.
function trimElem( elem )
{
	elem.value = trim( elem.value );
} 
//end trimElement


//-------------checkValue------------------------------------------------------------------------
// This method attempts to avoid browser rendering problems
// by disallowing < and > characters as inputs.  It converts
// such characters to lt; and gt; for HTML rendering.
function checkValue(value) {

   var theChar = "";
   var formattedString = value;

   for(var x=0; x < formattedString.length; x++) {
       theChar = formattedString.charAt(x);
       
       if(theChar == "<") {
          theChar = "&lt;";
	  formattedString = formattedString.substring(0, x) + theChar + 
                            formattedString.substring(x+1, formattedString.length);
       } else if(theChar == ">") {
          theChar = "&gt;";
          formattedString = formattedString.substring(0, x) + theChar +
                            formattedString.substring(x+1, formattedString.length);
       } //if

   } //for

   return formattedString;

}
//checkValue


/////////////////////////////////////////////////////////////////////////////////////////
// Utility Misc Helper Functions
/////////////////////////////////////////////////////////////////////////////////////////

//-------------checkNames ------------------------------------------------------------------

// use this to validate the username and password fields at login screens
function checkNames(username,password) {

	if ( (username.value !="" && password.value !="") ) {
		return true;
	}
	else {
		alert("Input Error. Login and Password must be provided to logon to the application.");
		return false;
	}
	
}	
//end checkNames

//-------------clearForm------------------------------------------------------------------
// Clear a form so that default initial values are erased
function clearForm(form) {
	var element;
	for (var i = 0; i < form.elements.length; i++) {
		element = form.elements[i];
		if (element.type == "text" || element.type == "password" || element.type == "textarea") element.value = '';
		else if (element.type.indexOf("select") != -1) element.selectedIndex = -1;
		else if (element.type == "checkbox" && element.checked) element.checked = false;
		else if (element.type == "radio" && element.checked == true) element.checked = false;
	}
}


//end clearForm

//-------------closeReloadPage---------------------------------------------------------
// closeReloadPage - UpdateIssueConfirm_Include.jsp & UpdateExceptionConfirm_Include.jsp
// closes the pop-up window that displays the updated details, then reloads
// the parent window to show the updated results.
function closeReloadPage(url) {

	//alert("window.opener = " + window.opener.location);
	//window.opener.location.reload();
	window.opener.location.replace(url);
	window.close();

}
// end closeReloadPage

//-------------goBackAfterSubmit---------------------------------------------------------
// goBackAfterSubmit - UpdateIssueConfirm_Include.jsp & UpdateExceptionConfirm_Include.jsp
// returns user to the updated item details, then reloads
// the parent window to show the updated results.

function goBackAfterSubmit(returnURL,reloadURL) {

	//alert("window.opener = " + window.opener.location);
	//window.opener.location.reload();
	window.opener.location.replace(reloadURL);
	window.location.replace(returnURL);
	//window.close();

}
// end goBackAfterSubmit

//-------------openWin--------------------------------------------------------------------
// This script is setup to accomodate all popup windows.  To acheive this flexibility, 
// a number of parameters must be passed in. The following is a detailed list of this parameters.
//
// DEFAULTS
// dir				show directories		default = no
// full				show fullscreen			default = no
// loc				show location			default = no
// menu				show menubar			default = yes
// title			show titlebar			default = yes
// tool				show toolbar			default = no		

// PARAMETERS
// url				popup window URL		path.extension  
// winName			window name				string			
// resize			resizable window		yes/no
// scroll			show scrollbars			yes/no	
// H				window height			pixel size		
// W				window width			pixel size		
// popupXoffset		value offset left		pixel size		
// popupYoffset		value offset right		pixel size		

//example: openWindow('popup.html','issue','yes','yes','400','400',100,100)"

function openWindow(url,winName,resize,scroll,H,W,popupXoffset,popupYoffset) {

	var popupX, popupY;
	//positioning only works in IE
	popupX = (window.parent.screenLeft + popupXoffset);
	popupY = (window.parent.screenTop + popupYoffset);		
	
	window.open(url,winName,'resizable=' + resize + ',scrollbars=' + scroll + ',height=' + H + ',width=' + W + ',top=' + popupY + ',left=' + popupX + ',directories=no,fullscreen=no,location=no,menubar=yes,titlebar=yes,toolbar=no');
	}


//end OpenWindow


//-------------putFocus--------------------------------------------------------------------
// This function puts focus in form element, and is
// initialized in template init function.

function putFocus(elementStr)

   {
   //elementStr.value="";
   elementStr.focus();
   }
   
//end putFocus

//-------------putSelect--------------------------------------------------------------------
// This function selects string entered in form element, and is
// initialized in template init function.

function putSelect(elementStr)

   {
   //elementStr.value="";
   elementStr.select();
   }
   
//end putSelect

//-------------sniffer--------------------------------------------------------------------
// sniffer used to determine browser for datepicker display

function sniffer() {

	var browser = navigator.appName;
	var versionStr = navigator.appVersion;
	var version = parseFloat(versionStr);
	var datepickerFlag = null;
	
	if (browser != "Microsoft Internet Explorer") {
		//not IE so set datepicker flag to 0
		datepickerFlag = 0;
	}
	else {
		if (version >= "4.0") {
			//IE and version is 4 or greater, so set datepicker flag to 1
			datepickerFlag = 1;
		}
		else {
			//IE but version is less than 4, so set datpicker flag to 0
			datepickerFlag = 0;
		}
	}

}
//end sniffer


/////////////////////////////////////////////////////////////////////////////////////////
// OTHER POSSIBLE INCLUSIONS
/////////////////////////////////////////////////////////////////////////////////////////


//-------------isValidDate---------------------------------------------------------------

//return true if fieldFrom is greater than fieldTo
//used for all the report validation.
function date1GTdate2(fieldFrom, fieldTo)
{
	var dateFrom = new Date (fieldFrom.value);
	var dateTo = new Date (fieldTo.value);

	if (fieldFrom.value.length!=0 && fieldTo.value.length!=0 )
		if (dateFrom > dateTo)
			return true; 
	return false;
}









