/* ********************************************************** */
/* Global Variables and Constants *************************** */
/* ********************************************************** */

var digits = "0123456789";
var lowercaseLetters = "abcdefghijklmnopqrstuvwxyz"
var uppercaseLetters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
var blanks = " \t\n\r";  // aka whitespace chars

// decimal point character differs by language and culture
var decimalPointDelimiter = "."

// non-digit characters allowed in phone numbers
var phoneNumberDelimiters = "()- ";

// characters allowed in US phone numbers
var validUSPhoneChars = digits + phoneNumberDelimiters;

// U.S. phone numbers have 10 digits, formatted as ### ### #### or (###)###-####
var digitsInUSPhoneNumber = 10;

// non-digit characters which are allowed in ZIP Codes
var ZIPCodeDelimiters = "-";

// our preferred delimiter for reformatting ZIP Codes
var ZIPCodeDelimeter = "-"

// U.S. ZIP codes have 5 or 9 digits, formatted as ##### or #####-####
var digitsInZIPCode1 = 5
var digitsInZIPCode2 = 9

// Valid U.S. Postal Codes for states, territories, armed forces, etc.
// See http://www.usps.gov/ncsc/lookups/abbr_state.txt
var USStateCodeDelimiter = "|";
var USStateCodes = "AL|AK|AS|AZ|AR|CA|CO|CT|DE|DC|FM|FL|GA|GU|HI|ID|IL|IN|IA|KS|KY|LA|ME|MH|MD|MA|MI|MN|MS|MO|MT|NE|NV|NH|NJ|NM|NY|NC|ND|MP|OH|OK|OR|PW|PA|PR|RI|SC|SD|TN|TX|UT|VT|VI|VA|WA|WV|WI|WY|AE|AA|AE|AE|AP|al|ak|as|az|ar|ca|co|ct|de|dc|fm|fl|ga|gu|hi|id|il|in|ia|ks|ky|la|me|mh|md|ma|mi|mn|ms|mo|mt|ne|nv|nh|nj|nm|ny|nc|nd|mp|oh|ok|or|pw|pa|pr|ri|sc|sd|tn|tx|ut|vt|vi|va|wa|wv|wi|wy|ae|aa|ae|ae|ap"


/* ********************************************************** */
/* Functions ************************************************ */
/* ********************************************************** */


// Returns true if string s is empty

function isEmpty(s)
  {
  return ((s == null) || (s.length == 0));
  }


// Returns true if string s is empty or all blank chars

function isBlank(s)
  {
  var i;

  // Is s empty?
  if (isEmpty(s))
    return true;

  // Search through string's chars one by one until we find first
  // non-blank char, then return false; if we don't, return true
  for (i=0; i<s.length; i++)
    {   
    // Check that current character isn't blank
    var c = s.charAt(i);
    if (blanks.indexOf(c) == -1) 
      return false;
    }
  // All characters are blank
  return true;
  }


// Removes all characters which appear in string bag from string s

function stripCharsInBag (s, bag)
  {
  var i;
  var returnString = "";

  // Search through string's characters one by one;
  // if character is not in bag, append to returnString
  for (i = 0; i < s.length; i++)
    {   
    // Check that current character isn't blank
    var c = s.charAt(i);
    if (bag.indexOf(c) == -1) 
      returnString += c;
    }
  return returnString;
  }


// Removes all characters which do NOT appear in string bag from string s

function stripCharsNotInBag (s, bag)
  {
  var i;
  var returnString = "";

  // Search through string's characters one by one;
  // if character is in bag, append to returnString
  for (i = 0; i < s.length; i++)
    {   
    // Check that current character isn't blank
    var c = s.charAt(i);
    if (bag.indexOf(c) != -1) 
      returnString += c;
    }
  return returnString;
  }


// Removes all blank chars (as defined by blanks) from s

function stripBlanks(s)
  {
  return stripCharsInBag(s, blanks)
  }


// Removes leading blank chars (as defined by blanks) from s

function stripLeadingBlanks(s)
  { 
  var i = 0;
  while ((i < s.length) && (blanks.indexOf(s.charAt(i)) != -1))
     i++;
  return s.substring(i, s.length);
  }


// Removes trailing blank chars (as defined by blanks) from s

function stripTrailingBlanks(s)
  { 
  var i = s.length - 1;
  while ((i >= 0) && (blanks.indexOf(s.charAt(i)) != -1))
     i--;
  return s.substring(0, i+1);
  }


// Removes leading+trailing blank chars (as defined by blanks) from s

function stripLeadingTrailingBlanks(s)
  { 
  s = stripLeadingBlanks(s);
  s = stripTrailingBlanks(s);
  return s;
  }


// Returns true if character c is an English letter (A .. Z, a..z)

function isLetter(c)
  {
  return (((c >= "a") && (c <= "z")) || ((c >= "A") && (c <= "Z")));
  }


// Returns true if character c is a digit (0 .. 9)

function isDigit(c)
  {
  return ((c >= "0") && (c <= "9"));
  }

function isRadioValue(c)
  {
  var value = null
  for (var i=0; i<c.length; i++){
      if (c[i].checked){
         value = c[i].value
      }
  }
  return value
  }

// Returns true if all chars in string s are numbers;
// first character is allowed to be + or -; does not 
// accept floating point, exponential notation, etc.

function isInteger(s)
  {
  if (isBlank(s))
    return false;

  // skip leading + or -
  if ((s.charAt(0) == "-") || (s.charAt(0) == "+"))
    var i = 1;
  else
    var i = 0;

  // Search through string's chars one by one until we find a 
  // non-numeric char, then return false; if we don't, return true
  for (i; i<s.length; i++)
    {   
    // Check that current character is number
    var c = s.charAt(i);
    if (!isDigit(c)) 
      return false;
    }
  // All characters are numbers
  return true;
  }


// True if string s is an unsigned floating point (real) number; 
// first character is allowed to be + or -; no exponential notation.

function isFloat(s)
  { 
  var seenDecimalPoint = false;

  if (isBlank(s)) 
    return false;
  if (s == decimalPointDelimiter) 
    return false;

  // skip leading + or -
  if ((s.charAt(0) == "-") || (s.charAt(0) == "+"))
    var i = 1;
  else
    var i = 0;

  // Search through string's chars one by one until we find a 
  // non-numeric char, then return false; if we don't, return true

  for (i; i<s.length; i++)
    {   
    // Check that current character is number
    var c = s.charAt(i);

    if ((c == decimalPointDelimiter) && !seenDecimalPoint) 
      seenDecimalPoint = true;
    else if (!isDigit(c)) 
      return false;
    }
  // All characters are numbers
  return seenDecimalPoint;
  }


// Returns true if string s is English letters (A .. Z, a..z) only

function isAlphabetic(s)
  {
  var i;

  if (isBlank(s)) 
     return false;

  // Search through string's chars one by one until we find a 
  // non-alphabetic char, then return false; if we don't, return true

  for (i = 0; i < s.length; i++)
  {   
  // Check that current character is letter
  var c = s.charAt(i);

  if (!isLetter(c))
    return false;
  }

  // All characters are letters
  return true;
  }


// Returns true if string s is English letters (A .. Z, a..z) and numbers only

function isAlphanumeric(s)
  {
  var i;

  if (isBlank(s)) 
     return false;

  // Search through string's chars one by one until we find a 
  // non-alphanumeric char, then return false; if we don't, return true

  for (i = 0; i < s.length; i++)
    {   
    // Check that current character is number or letter
    var c = s.charAt(i);

    if (! (isLetter(c) || isDigit(c) ) )
    return false;
    }

  // All characters are numbers or letters
  return true;
  }


function reformatString(targetString)
  { 
  var arg;
  var sPos = 0;
  var resultString = "";

  for (var i=1; i<reformatString.arguments.length; i++)
    {
    arg = reformatString.arguments[i];
    if (i%2 == 1) 
      {
      resultString += arg;
      }
    else
      {
      resultString += targetString.substring(sPos, sPos + arg);
      sPos += arg;
      }
    }
  return resultString;
  }


// Returns true if s is valid U.S. phone number (with area code): 10 digits

function isUSPhoneNumber(s)
  { 
  if (isBlank(s)) 
    return false;
  s = stripCharsNotInBag(s, digits);
  return (isInteger(s) && (s.length == digitsInUSPhoneNumber));
  }


// Returns true if string s is a valid U.S. ZIP code: ##### or #####-####

function isZIPCode(s)
  { 
  if (isBlank(s)) 
    return false;

  s = stripLeadingTrailingBlanks(s);

  if ((isInteger(s)) && (s.indexOf("-") == -1) &&  // #####
      (s.length == digitsInZIPCode1))
    return true;

  if (s.indexOf("-") != 5)  // - in wrong place
    return false;

  s = stripCharsNotInBag(s, digits);

  if (s.length == digitsInZIPCode2)
    return true;   // #####-####
  else
    return false;  // not #####-####
  }


// Returns true if s is valid 2-letter U.S. state abbreviation

function isStateCode(s)
  { 
  if (isBlank(s)) 
    return false;
  return ((USStateCodes.indexOf(s) != -1) &&
          (s.indexOf(USStateCodeDelimiter) == -1))
  }


// Returns true if string is a valid email address: @ and . required,
// at least one char before @, at least one char before and after .

function isEmail(s)
  { 
  if (isBlank(s)) 
    return false;
  
  // there must be >= 1 character before @, so we start
  // start looking at character position 1 (i.e. second character)
  var i = 1;
  var sLength = s.length;

  // look for @
  while ((i < sLength) && (s.charAt(i) != "@"))
    i++

  if ((i >= sLength) || (s.charAt(i) != "@")) 
    return false;
  else 
    i += 2;

  // look for .
  while ((i < sLength) && (s.charAt(i) != "."))
    i++

  // there must be at least one character after the .
  if ((i >= sLength - 1) || (s.charAt(i) != ".")) 
    return false;
  else 
    return true;
  }


// Returns true if string s is an integer such that a <= s <= b

function isIntegerInRange (s, a, b)
  { 
  if (isBlank(s)) 
    return false;
  if (!isInteger(s)) 
    return false;
  var num = parseInt(s);
  return ((num >= a) && (num <= b));
  }


// Returns index of checked radio button in radio set,
// or -1 if no radio buttons are checked

function getCheckedRadioButton(radioSet)
  { 
  for (var i=0; i<radioSet.length; i++)
    if (radioSet[i].checked)
      return i;
  return -1;
  }


// Returns array containing index(es) of checked checkbox(es) 
// in checkbox set, or -1 if no checkboxes are checked

function getCheckedCheckboxes(checkboxSet)
  {
  var arr = new Array();
  for (var i=0,j=0; i<checkboxSet.length; i++)
    if (checkboxSet[i].checked)
      arr[j++] = i;
  if (arr.length > 0)
    return arr;
  else
    return -1;
  }


// Returns array containing index(es) of checked option(s) 
// in select box, or -1 if no options are selected

function getCheckedSelectOptions(select)
  {
  var arr = new Array();
  for (var i=0,j=0; i<select.length; i++)
    if (select.options[i].selected)
      arr[j++] = i;
  if (arr.length > 0)
    return arr;
  else
    return -1;
  }

function isDate(a)
{
  var err = 0
  var psj = 0;
  if (a != ""){
     if (a.length != 10) err=1
     b = a.substring(0, 2)// month
     c = a.substring(2, 3)// '/'
     d = a.substring(3, 5)// day
     e = a.substring(5, 6)// '/'
     f = a.substring(6, 10)// year

     // basic error checking
     if (b<1 || b>12) err = 1
     if (c != '/') err = 1
     if (d<1 || d>31) err = 1
     if (e != '/') err = 1
     if (f<1900 || f>2099) err = 1
     if (f.length < 4) err = 1
     // advanced error checking
     // months with 30 days
     if (b==4 || b==6 || b==9 || b==11){
	if (d==31) err=1
     }

     // february, leap year
     if (b==2){
	// feb
	var g=parseInt(f/4)
	if (isNaN(g)) {
		err=1
	}

	if (d>29) err=1
	if (d==29 && ((f/4)!=parseInt(f/4))) err=1
     }

     if (err==1){
	return -1;
     }
  }
}

function textMax(c,tl)
{
  if (c.length > tl)
    return -1;
}

function maxWords(c,m)
{
   var ctext = c.split(" ")
   if (ctext.length > m)
     {
      alert("Please restrain your input to " + m + " or less words!");
      return -1;
     }
}

function GP_AdvOpenWindow(theURL,winName,features,popWidth,popHeight,winAlign,ignorelink,alwaysOnTop,autoCloseTime,borderless) { //v2.0
  var leftPos=0,topPos=0,autoCloseTimeoutHandle, ontopIntervalHandle, w = 480, h = 340;
  if (popWidth > 0) features += (features.length > 0 ? ',' : '') + 'width=' + popWidth;
  if (popHeight > 0) features += (features.length > 0 ? ',' : '') + 'height=' + popHeight;
  if (winAlign && winAlign != "" && popWidth > 0 && popHeight > 0) {
    if (document.all || document.layers || document.getElementById) {w = screen.availWidth; h = screen.availHeight;}
		if (winAlign.indexOf("center") != -1) {topPos = (h-popHeight)/2;leftPos = (w-popWidth)/2;}
		if (winAlign.indexOf("bottom") != -1) topPos = h-popHeight; if (winAlign.indexOf("right") != -1) leftPos = w-popWidth;
		if (winAlign.indexOf("left") != -1) leftPos = 0; if (winAlign.indexOf("top") != -1) topPos = 0;
    features += (features.length > 0 ? ',' : '') + 'top=' + topPos+',left='+leftPos;}
  if (document.all && borderless && borderless != "" && features.indexOf("fullscreen") != -1) features+=",fullscreen=1";
  if (window["popupWindow"] == null) window["popupWindow"] = new Array();
  var wp = popupWindow.length;
  popupWindow[wp] = window.open(theURL,winName,features);
  if (popupWindow[wp].opener == null) popupWindow[wp].opener = self;
  if (document.all || document.layers || document.getElementById) {
    if (borderless && borderless != "") {popupWindow[wp].resizeTo(popWidth,popHeight); popupWindow[wp].moveTo(leftPos, topPos);}
    if (alwaysOnTop && alwaysOnTop != "") {
    	ontopIntervalHandle = popupWindow[wp].setInterval("window.focus();", 50);
    	popupWindow[wp].document.body.onload = function() {window.setInterval("window.focus();", 50);}; }
    if (autoCloseTime && autoCloseTime > 0) {
    	popupWindow[wp].document.body.onbeforeunload = function() {
  			if (autoCloseTimeoutHandle) window.clearInterval(autoCloseTimeoutHandle);
    		window.onbeforeunload = null;	}
   		autoCloseTimeoutHandle = window.setTimeout("popupWindow["+wp+"].close()", autoCloseTime * 1000); }
  	window.onbeforeunload = function() {for (var i=0;i<popupWindow.length;i++) popupWindow[i].close();}; }
  document.MM_returnValue = (ignorelink && ignorelink != "") ? false : true;
}

function MM_jumpMenu(targ,selObj,restore){ //v3.0
  eval(targ+".location='"+selObj.options[selObj.selectedIndex].value+"'");
  if (restore) selObj.selectedIndex=0;
}

function popCalendar(param) {
  var newWindow;
  var urlstring = "/includes/dateCal.asp?objForm=" + param
  newWindow = window.open(urlstring,'','height=200,width=280,toolbar=no,minimize=no,status=no,memubar=no,location=no,scrollbars=no')
}//popCalendar

function MM_openBrWindow(theURL,winName,features) { //v2.0
  window.open(theURL,winName,features);
}

function checkdate(objName) {
	if (!chkdate(objName)) {
		objName.select();
		alert("That date is invalid. Please try again.");
		objName.focus();
		return false;
	}
	return true;
}//checkdate

/*check valid date*/
function chkdate(objName) {
	var strDate = objName.value;
	var dd, mm, yyyy;
	var booNotFound = true;
	var strSeparatorArray = new Array('-',' ','/','.');
	if (strDate==null || strDate=="") { return false; }
	if (strDate.length < 1) { return true; }
	for (var itr = 0; itr < strSeparatorArray.length; itr++) {
		if (strDate.indexOf(strSeparatorArray[itr]) != -1) {
			var strDateArray = strDate.split(strSeparatorArray[itr]);
			if (strDateArray.length != 3) { return false; }
			dd   = parseInt(strDateArray[1],10);
			mm   = parseInt(strDateArray[0],10);
			yyyy = parseInt(strDateArray[2],10);
			if ((isNaN(dd) || isNaN(mm) || isNaN(yyyy))) { return false; }
			booNotFound = false;
			break;
		}
	}
	if (booNotFound) { return false; }

	if (yyyy < 100) { yyyy += 2000; }
	
	switch(mm) {
	case 1:
	case 3:
	case 5:
	case 7:
	case 8:
	case 10:
	case 12:
		return (dd >= 1 && dd <= 31);
		break;
	case 4:
	case 6:
	case 9:
	case 11:
		return (dd >= 1 && dd <= 30);
		break;
	case 2:
		return (LeapYear(yyyy))?(dd >= 1 && dd <= 29):(dd >= 1 && dd <= 28);
		break;
	default:
		return false;
	}//switch
}//chkdate

function LeapYear(intYear) {
	if (intYear % 100 == 0) {
		if (intYear % 400 == 0) { return true; }
	} else {
		if ((intYear % 4) == 0) { return true; }
	}
	return false;
}//LeapYear

function taLimit() {
	var taObj=event.srcElement;
	if (taObj.value.length==taObj.maxLength*1) return false;
}

function taCount(visCnt) { 
	var taObj=event.srcElement;
	if (taObj.value.length>taObj.maxLength*1) taObj.value=taObj.value.substring(0,taObj.maxLength*1);
	if (visCnt) visCnt.innerText=taObj.maxLength-taObj.value.length;
}

/* change row colour on selected/deselected row */
function checkRow(e,bgc) {
  e.srcElement.parentElement.style.backgroundColor = bgc;
}//checkRow

function formatCurrency(num) {
  num = num.toString().replace(/\$|\,/g,'');
  if(isNaN(num))
   num = "0";
   sign = (num == (num = Math.abs(num)));
   num = Math.floor(num*100+0.50000000001);
   cents = num%100;
   num = Math.floor(num/100).toString();
   if(cents<10)
     cents = "0" + cents;
     for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
       num = num.substring(0,num.length-(4*i+3))+','+
       num.substring(num.length-(4*i+3));
     return (((sign)?'':'-') + num + '.' + cents);
}

function popUp2(strURL,strType,strHeight,strWidth) {
var strOptions="";
if (strType=="console") strOptions="resizable,height="+strHeight+",width="+strWidth;
if (strType=="fixed") strOptions="status,height="+strHeight+",width="+strWidth;
if (strType=="elastic") strOptions="toolbar,menubar,scrollbars,resizable,location,height="+strHeight+",width="+strWidth;
window.open(strURL, 'newWin', strOptions);
}
