//  Updated 5/14/11 (use this one on every site)

//  Notes: 
//  1. A variable initialized inside a function WITHOUT var has global scope.

//  Add a method to the Array object. Ref: www.javascriptkit.com/javatutors/proto.shtml
if (!Array.indexOf) {  //  Define indexOf if not already defined.
  Array.prototype.indexOf = function (obj, start) {
    for (var i = (start || 0); i < this.length; i++) 
			if (this[i] == obj) return i;
    return -1;
  }
}
// ---------------------------------------------------------------------------------
function pop_up (url,w,h,x,y,windows_parms) {
if (!w) w=400;
if (!h) h=400;
if (!x) x=40;
if (!y) y=40;
//  windows_parms = parms passed to window.open function, sep by commas.
if (typeof windows_parms == "undefined") {
		Menu_on = 'no';
		windows_parms='';
} else if (windows_parms=='no' || windows_parms=='yes') { //  For compatability with previous versions of pop_up function.
		Menu_on = windows_parms;
}
parm_ar=windows_parms.split(',');
// FIX: This doesn't work because the parm is like "width=200" which would not match.
// idx=parm_ar.indexOf('width',0); if (idx>=0) parm_ar.splice(idx,1);   // Ignore parm

/* window.open parms: number or 'yes' or 'no' (0 or 1 works too)
alwaysLowered  		creates a window that always floats below other windows. 
alwaysRaised  		creates a window that always floats above other windows. 
dependent  				new window is created as a child (closes when the parent window closes 
										and does not appear on the task bar on Windows platforms) of the current window. 
directories 			new window has the standard directory buttons. 
height 						sets the height of the new window in pixels. 
hotkeys  					If 'no', disables the use of hotkeys (except security and quit hotkeys) in a window without a menubar. 
innerHeight  			sets the inner height of the window in pixels. 
innerWidth  			sets the inner width of the window in pixels. 
location 					creates the standard Location entry field in the new browser window. 
menubar 					creates a new browser window with the standard menu bar (File, Edit, View, etc.). 
outerHeight  			sets the outer height of the new window in pixels. 
outerWidth  			sets the outer width of the new window in pixels. 
resizable 				allows the resizing of the new window by the user. 
screenX  					new window is created at a specified number of pixels from the left side of the screen. 
screenY  					new window is created at a specified number of pixels from the top of the screen. 
scrollbars 				new window is created with the standard horizontal and vertical scrollbars, where needed 
status 						new window will have the standard browser status bar at the bottom. 
titlebar  				new window will have the standard title bar. 
toolbar 					new window will have the standard browser tool bar (Back, Forward, etc). Default is YES.
width 						sets the width of the new window in pixels. 
z-lock  					prevents the new window from rising above other windows when it is made active (given focus). 
*/
// FIX: The following parms still display the location and status bar on Firefox.
parms='resizable=yes,toolbar=no,location=no,directories=no,status=no,scrollbars=yes';
parms+=',top=' + y + ',left=' + x;  //  OK for Netscape too
parms+=',width=' + w + ',height=' + h + ',menubar=' + Menu_on;
// alert(url + ',' + parms);
window_name='pop_up_window';
return window.open(url,window_name,parms);   // returns hWindow. If not needed, call like this "javascript:void pop_up (url,w,h,x,y,windows_parms)"
}
// ---------------------------------------------------
function is_only_digits (str) {
var regex = new RegExp("([0-9]){" + str.length + "}");
return regex.test(str); 
}
// ---------------------------------------------------
function to24hr(tm12hr) {  // Return 24 hr clock given input like 8:00am, 11:00pm, 0:00a, or 12:00p
var tm12hr=trim(tm12hr.toLowerCase());
var tm12hr=tm12hr.replace(/m/,'');  //  drop any 'm'
var len=tm12hr.length;
//  FIX: use reg expr
if (len!=5 && len!=6)  return 'badtime';  //  1 or 2 digit hour
if (len==5)  {
	tm12hr='0' + tm12hr;  // make it 6 long, like 08:00a or 11:00p
	len+=1;
}
if (tm12hr.substr(2,1)!=':')  return 'badtime'; 
var hh=1 * tm12hr.substr(0,2);
var mm=1 * tm12hr.substr(3,2);
var a_or_p=tm12hr.substr(5,1);
if (hh==12 && a_or_p=='a') //  change 12:mm to 00:mm 
  hh=0;
if (hh<12 && a_or_p=='p')   
	hh+=12;
return (FormatNumber(hh,'00') + ':' + FormatNumber(mm,'00')); 
}
// ---------------------------------------------------
function to12hr(tm24hr) {  //  Return 12 hr clock given 24 hr clock (00:00-23:59)
var suffix;
var tm24hr=trim(tm24hr);
if (tm24hr.substr(2,1)!=':' || tm24hr.length !=5)  return 'badtime';  //  must be dd:dd
var tm=tm24hr;
var hrs=1 * tm.substr(0,2);
if (hrs >= 12) {
	if (hrs > 12) hrs-=12;
	suffix='p';	
} else 
	suffix='a';	
if (hrs==0) hrs=12;  //  special case - midnight hour
tm=FormatNumber(hrs,'0') + tm.substr(2) + suffix;
return tm;
}
// -------------------------------------------
function ValidEmail(email) {
/*     . matches any singular character.
       ? matches one or none of the preceding character.
       + matches at least one of ...
       * matches none or all of ...
     {n} matches exactly n occurrences of ...
    {n,} matches at least n occurrences of ...
   {n,m} matches at least n to m occurrences of ...
       ^ matches the absolute beginning of the string.
       $ matches the absolute end of the string.
     \w+ matches a whole word.
      \w matches a "word" character (alphanumerics and the "_" character).
     \W+ matches whitespace.
     x|y matches one or the other of x or y.
  [0..9] matches ONE number, ranging from 0 to 9.
[A-Za-z] matches any letter, uppercase or lowercase.

See http://en.wikipedia.org/wiki/E-mail_address
The format of Internet e-mail addresses is defined in RFC 2822.

The part before the @ sign is the "LOCAL-PART" of the address.
It can contain the chars, ! # $ % & ' * + - / = ? ^ _ ` { | } ~ (and periods if not the first or last char).
Also, local-part may be a quoted-string, as in "John Doe"@example.com, thus allowing chars that 
	would not otherwise be prohibited.

HOST NAMES must start with a letter, end with a letter or digit, and have as interior
chars only letters, digits, and hyphen. Length can be up to 63 char w/o ext, 67 w/ ext.
The domain name must be a min of 2 char, excl ext, and must start w/ a letter or digit.
*/
// var re1 = /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/;
// var re1 = /^\w+((-\w+)|(\.\w+))*@[a-z0-9]{2,}((\.|-)[a-z0-9]{2,})*\.[a-z0-9]{2,5}$/;
var e=email.toLowerCase();
var re1 = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
if (!re1.test(e)) return false;
return true
}
//  -------------------------------------------
function ValidTime(str) {
//  like 8:30a or 7:45pm;
var re=/^(0?[1-9]|1[0-2]):[0-5]\d(a|am|p|pm| a| am| p| pm)$/;    //  Like 11:11am or 11:11 am
return re.test(str);
}
// -------------------------------------
function ValidDate(str,yr_must_be_4_digits) { 
// Returns milliseconds since UNIX epoch or FALSE.
var args=ValidDate.arguments;
if (args.length==1) yr_must_be_4_digits=false;  //  default: allow 2 or 4 digit yr
var regexp = /^\d{1,2}\/\d{1,2}\/(\d\d|\d\d\d\d)$/;  // checks format of string 
if (!regexp.test(str))  return false;;
var ary=str.split('/');  //  array of m,d,y substrings
// parseInt(string [,radix]): If the input string begins with 
//  "0x", the radix is 16 (hexadecimal).
//  "0", the radix is eight (octal).
//  any other value, the radix is 10 (decimal).
var mo=parseInt(ary[0],10);  //  1-12
var dy=parseInt(ary[1],10);
var yr=parseInt(ary[2],10);
var yr_str=ary[2];
//if (yr_str.length!=2 && yr_str.length!=4) return false;
if (yr_must_be_4_digits && yr_str.length!=4) return false;
if (yr_str.length==2) 	//  2 digit year. make assumptions
	if (yr>50) 
		yr+=1900;
	else
		yr+=2000;
if (yr<1000 || yr>2099)  return false;
if (mo<1 || mo>12 || dy<1 || dy>31)  return false;  // first checks
if ((mo==9 || mo==4 || mo==6 || mo==11) && (dy==31))  // months with 30 days
	return false
else
	if (mo==2) {
		// February has 29 days in any year evenly divisible by four,
		//   EXCEPT for centurial years which are not also divisible by 400.
		var daysInFebruary=(((yr % 4 == 0) && ( (!(yr % 100 == 0)) || (yr % 400 == 0))) ? 29 : 28 );
		if (dy > daysInFebruary)  return false; 
	}
mo=mo-1;  //  "new Date" needs 0 to 11.
var dat=new Date(yr,mo,dy);
//var dat=new Date(str);  //  this would work if we had a 4 digit yr.
return dat.getTime(); 
}
// -----------------------------------------------------------
function trim(str) {
while (''+str.charAt(0)==' ') str=str.substring(1,str.length);
while (''+str.charAt(str.length-1)==' ') str=str.substring(0,str.length-1);
return str;
}
// -------------------------------------
function fieldempty (fld) {
// alert('fieldempty?: ' + fld.name);
return (fld.value.length == 0 || fld.value.substring(0,1) == " ")
}
// ------------------------------------------------------
function WordCount (str) {
// Use "var" otherwise variable is global within this page
var char_count = str.length;
var fullStr = str + " ";
var initial_whitespace_rExp = /^[^A-Za-z0-9]+/gi;
var left_trimmedStr = fullStr.replace(initial_whitespace_rExp, "");
var non_alphanumerics_rExp = rExp = /[^A-Za-z0-9]+/gi;
var cleanedStr = left_trimmedStr.replace(non_alphanumerics_rExp, " ");
var splitString = cleanedStr.split(" ");
var word_count = splitString.length -1;
if (fullStr.length <2) {word_count = 0;}
return word_count;
}
// --------------------------------------------------------
function FormatNumber(number, format, print) {  // use: FormatNumber(number, "format",[true])
// Original JavaScript code by Duncan Crombie: dcrombie@chirp.com.au
// Modified slightly here.
// http://members.ozemail.com.au/~dcrombie/format.html
// '#' means that a decimal place is shown if required. 
// '0' means that a decimal place or leading zero is always shown. 
// ',' indicates the number should be broken into thousands
// '%' or "$" converts the number to that type.
//  Example: FormatNumber(31415962, "$,##0.00") => $31,415,962.00

// CONSTANTS - I added 'f_' to these to avoid conflicts with other functions not related to FormatNumber()
var f_separator = ",";  // use comma as 000's separator
var f_decpoint = ".";  // use period as decimal point
var f_percent = "%";
var f_currency = "$";  // use dollar sign for currency

if (print) document.write("FormatNumber(" + number + ", \"" + format + "\")<br>");  //  for testing

if (number - 0 != number) return null;  // if number is NaN return null
var useSeparator = format.indexOf(f_separator) != -1;  // use separators in number
var usePercent = format.indexOf(f_percent) != -1;  // convert output to percentage
var useCurrency = format.indexOf(f_currency) != -1;  // use currency format
var isNegative = (number < 0);
number = Math.abs (number);
if (usePercent) number *= 100;
format = f_strip(format, f_separator + f_percent + f_currency);  // remove key characters
number = "" + number;  // convert number input to string

 // split input value into LHS and RHS using decpoint as divider
var dec = number.indexOf(f_decpoint) != -1;
var nleftEnd = (dec) ? number.substring(0, number.indexOf(".")) : number;
var nrightEnd = (dec) ? number.substring(number.indexOf(".") + 1) : "";

 // split format string into LHS and RHS using decpoint as divider
dec = format.indexOf(f_decpoint) != -1;
var sleftEnd = (dec) ? format.substring(0, format.indexOf(".")) : format;
var srightEnd = (dec) ? format.substring(format.indexOf(".") + 1) : "";

 // adjust decimal places by cropping or adding zeros to LHS of number
if (srightEnd.length < nrightEnd.length) {
  var nextChar = nrightEnd.charAt(srightEnd.length) - 0;
  nrightEnd = nrightEnd.substring(0, srightEnd.length);
  if (nextChar >= 5) nrightEnd = "" + ((nrightEnd - 0) + 1);  // round up

 // patch provided by Patti Marcoux 1999/08/06
  while (srightEnd.length > nrightEnd.length) {
    nrightEnd = "0" + nrightEnd;

  }

  if (srightEnd.length < nrightEnd.length) {
    nrightEnd = nrightEnd.substring(1);
    nleftEnd = (nleftEnd - 0) + 1;
  }
} else {
  for (var i=nrightEnd.length; srightEnd.length > nrightEnd.length; i++) {
    if (srightEnd.charAt(i) == "0") nrightEnd += "0";  // append zero to RHS of number
    else break;
  }
}

 // adjust leading zeros
sleftEnd = f_strip(sleftEnd, "#");  // remove hashes from LHS of format
while (sleftEnd.length > nleftEnd.length) {
  nleftEnd = "0" + nleftEnd;  // prepend zero to LHS of number
}

if (useSeparator) nleftEnd = f_separate(nleftEnd, f_separator);  // add separator
var output = nleftEnd + ((nrightEnd != "") ? "." + nrightEnd : "");  // combine parts
output = ((useCurrency) ? f_currency : "") + output + ((usePercent) ? f_percent : "");
if (isNegative) {
  // patch suggested by Tom Denn 25/4/2001
  output = (useCurrency) ? "(" + output + ")" : "-" + output;
}
return output;
}
// ---------------------------------------------------------------------------------
function f_strip(input, chars) {  // strip all characters in 'chars' from input
var output = "";  // initialise output string
for (var i=0; i < input.length; i++)
  if (chars.indexOf(input.charAt(i)) == -1)
    output += input.charAt(i);
return output;
}
// ---------------------------------------------------------------------------------
function f_separate(input, sep) {  // format input using separator to mark 000's
input = "" + input;
var output = "";  // initialise output string
for (var i=0; i < input.length; i++) {
  if (i != 0 && (input.length - i) % 3 == 0) output += sep;
  output += input.charAt(i);
}
return output;
}
// --------------------------------------------------------------
function dump_array(arr) {
for (var idx=0; idx<arr.length; idx++) {
document.write("<b>arr["+idx+"] is </b>=>"+arr[idx]+"<br>");
}
}
// --------------------------------------------------------------



