// common.js - javascript include file all pages.
// generic functions go here
// ToUpper(inValue)  -- converts text into all upper case for easier comparisons
// AllNumbers(theString)  -- returns true if all digits of a string are numbers, false otherwise.
// ValidDate(inDate, yrDigits, delim)  -- returns true if inDate is a valid date according to: MM/DD/YYYY where number of digits
//										"yrDigits" for Y can be specified as either 2 or 4. Default is 4.
//										Delimiter is '/' unless '-' is specified in 'delim'.
// moveSelected(fromSel, toSel)  -- use with two selection lists (multiple select) 
//                                  to move values to AND from each list see example on sec_appl.cfm
// isNonBlank( theStr ) -- determines if value is non-blank (eliminates possibility of entering a space
// isDate(this) - validates that the date is correct and reformats it to mm/dd/yyyy.  Will accept dates with - or / delimiters
//    if the date is invalid, it will display an alert box and then return focus to the invalid field.
//		calls the following functions:  checkMonthLength, checkLeapMonth, monthDayFormat
// isTime(this) - validates that the time is correct and formats it as hh:mm.  It validates against a 12 hour time format and 
//		calls the function hourMinuteFormat
// toggleOptionsTable -- hide/show a table
//		(DS022007) DBW moved from specific js files into common js

// sniffing the userAgent is terribly unreliable, as this is easily spoofed
// var agentString = navigator.userAgent.toLowerCase();
// var isSafari = agentString.indexOf("safari") > -1;
// var isFirefox = agentString.indexOf("firefox") > -1;
// var isNetscape = agentString.indexOf("netscape") > -1;
// var isMSIE = agentString.indexOf("msie") > -1;

// capability testing preferred, convenience object (parsing userAgent where it can't be helped)
if (typeof Browser == 'undefined') Browser = {
    IE:     !!(window.attachEvent && !window.opera),
    Opera:  !!window.opera,
    WebKit: navigator.userAgent.indexOf('AppleWebKit/') > -1,
    Gecko:  navigator.userAgent.indexOf('Gecko') > -1 && navigator.userAgent.indexOf('KHTML') == -1
};

// for FCKEditor, avoid issues with editor on hidden layers
// split out the function definition, since IE doesn't need it
if (Browser.IE)
	switchEditors = function(){ return; };
else {
	switchEditors = function(oNode, sType) {
		// gather all child divs of specified parent object
		var child_divs = oNode.getElementsByTagName('div');
		
		// iterate over collection, only operating if class contains "wrap_editor"
		for (var i = 0, x, div, elm, editor; div = child_divs[i]; i++) {
			
			// error checks: exists, className exists, className contains...
			if (!div || !div.className || div.className.indexOf('wrap_editor') == -1) continue;
			
			// iterate through childNodes, locating the first element (avoiding text nodes)
			x = 0; while (elm = div.childNodes[x++])
				if (elm.nodeType == 1 && elm.name) break; // is an element with a name attribute
			
			// retrieve an API instance based on the input (the first element)'s name
			editor = FCKeditorAPI.GetInstance(elm.name);
			
			// if successful, toggle designMode
			if (editor && editor.EditorDocument && editor.EditMode == FCK_EDITMODE_WYSIWYG)
				setTimeout(function(){editor.EditorDocument.designMode = sType;}, 10);
			// setTimeout is necessary for an event handler that might fire before layer switch
			// no recursion!
		}
		/*
		for (var i=0;i<oNode.childNodes.length;i++) {
			childNode = oNode.childNodes.item(i);
			editor = FCKeditorAPI.GetInstance(childNode.name);
			if (editor && editor.EditorDocument && editor.EditMode == FCK_EDITMODE_WYSIWYG) {
				editor.EditorDocument.designMode = sType;
				//editor.SwitchEditMode();
				//editor.SwitchEditMode();
			}
			switchEditors(childNode,sType);
		}
		*/
	};
}
function toggleOptionsTable(theElementID, displayMode, hideBtnID, showBtnID) {
	var kShow = "";
	var kHide = "none";
	
	document.getElementById(theElementID).style.display = displayMode;	
	if (displayMode == kShow)
	{
		document.getElementById(showBtnID).style.display = kHide;
		document.getElementById(hideBtnID).style.display = kShow;
	}
	else
	{
		document.getElementById(showBtnID).style.display = kShow;
		document.getElementById(hideBtnID).style.display = kHide;
	}	
}

// This function enables/disables a select list based on the value of a radio button.
function UpdateRadioSelect(selectID, radioID) {
	document.getElementById(selectID).disabled = !document.getElementById(radioID).checked;
}

function ToUpper(inValue) {
  var inString = new String(inValue);
  return inString.toUpperCase();
}

// Check to make sure all digits are numbers. 
function AllNumbers(theString) {  
	var myReg = new RegExp("[^0-9]", "g"); 
	var tempString = theString.replace(myReg, "");  

	if (tempString.length == theString.length) 
		return true;  
	else 
		return false;  
} 

// Return the string with all non number digits removed.
function NumbersOnly(inString) {
	// Remove all non digits. Translates to: Find non digits (\D), globally ('g' for All), replace with empty string.
	inString = inString.replace(/\D/g, "");
	
	return inString;
}

// Validates a date passed in. yrDigits is number of digits in the year (2 or 4), delim is the separator.
// Defaults are: 4 year digits, '/' as a separator.
function ValidDate(inDate, yrDigits, delim) {
	if (arguments.length < 3 || delim.length != 1) { delim = '/'; }
		
	if (arguments.length < 2 || (yrDigits != 2 && yrDigits != 4)) { yrDigits = 4; }
		
	var splitDate = inDate.split(delim);
	var fieldSize = new Array(2, 2, yrDigits)
	
	// Invalid if there aren't 3 parts and if total digits aren't 8 (2 digit year) or 10 (4 digit year).
	if (splitDate.length != 3 || (inDate.length != 6 + yrDigits))
		return false;
	
	for (var i = 0; i < 3; i++)
	{
		// Make sure they're all numbers.
		if (!AllNumbers(splitDate[i]))
			return false;

		// Make sure that each field size is correct. 074/3/2004 would not be valid.
		if (splitDate[i].length != fieldSize[i])
			return false;
	}
	
	return true;
}

function moveSelected(fromSel, toSel) {
// This function takes the selected values AND moves them to the TO select list
// INPUT fromSel -- the FROM selection list name (i.e. document.form2.selAllGroups)
// INPUT toSel -- the TO selection list name (i.e. document.form2.selGroups)
  var prevNew=0;
  var delArray = new Array();
  for (idx = 0; idx < fromSel.length; idx++)
	{
    if (fromSel[idx].selected == true)
		{
      var idx2 = 0;
      var newOption = new Option(fromSel[idx].text,fromSel[idx].value);
      var newPos = toSel.length;
      var newTxt = fromSel[idx].text;
      var newVal = fromSel[idx].value;
      newArrayPos = toSel.length;      

      delArray[idx] = "YES";      
      for (idx2=0; idx2 < toSel.length; idx2++)
			{
         if (ToUpper(toSel[idx2].value) == ToUpper(newVal))
				 {
            newPos = -1;  // skip cause value is already in list
         }
      }
      
      if (newPos != -1)
			{
//        toSel.options.add(newOption);		// This doesn't run on the Mac Safari browser. "add" is a non standard function.
				var selectLen = toSel.options.length;
        toSel.options[selectLen] = newOption;		// Just setting the options arrayone past the last element works correctly.
        if (newPos >= 1)
				{      
          for  (idx2 = toSel.length - 1; idx2 > prevNew; idx2--)
					{         
            if (ToUpper(toSel[idx2].value) < ToUpper(toSel[idx2 - 1].value))
						{         
              toSel[idx2].text = toSel[idx2 - 1].text;
              toSel[idx2].value = toSel[idx2 - 1].value;
              newPos = idx2 - 1;
              toSel[newPos].value = newVal;
              toSel[newPos].text = newTxt;
            }
          } 
        }
      }
    }
  }
  for (idx3=idx; idx3 >= 0; idx3--)
	{
    if (delArray[idx3] == "YES")
		{
       fromSel[idx3] = null;      
    }
  }
}

function isNonBlank(theStr) {
	var retValue = false;
	var x = 0;
	while (x < theStr.length) {
		if(theStr.charAt(x) != " ") {
			retValue = true;
			x = theStr.length;
		}
		x++;
	}
	return retValue;
}

//BEGIN Date Validation Function
// from the Javscript Bible, 3rd Edition
function isDate(gField,yrDigits) {
	if (arguments.length < 2 || (yrDigits != 2 && yrDigits != 4)) {
		yrDigits = 4;
	}
	var inputStr = gField.value
	var alertText = "The date entry is not in an acceptable format.\n\nYou can enter dates in the following formats: "
	if (yrDigits == 2) {
		alertText += "mmddyy, mm/dd/yy, or mm-dd-yy."
	} else {
		alertText += "mmddyyyy, mm/dd/yyyy, or mm-dd-yyyy."
	}

// convert hypen delimiters to slashes (RL02012007, replaceString does not exist, so use string.replace instead.)
	inputStr = inputStr.replace(/-/g, '/');
	// while (inputStr.indexOf("-") != -1) {
	//	inputStr = replaceString(inputStr,'-',"/")
	// }
	
	var delim1 = inputStr.indexOf("/")
	var delim2 = inputStr.lastIndexOf("/")
	if (delim1 != -1 && delim1 == delim2) {
		// there is only one delimiter in the string
		alert (alertText)
		gField.focus()
		gField.select()
		return false
	}
	if (delim1 != -1) {
		//there are deliminters; extract component values
		var mm = parseInt(inputStr.substring(0,delim1),10)
		var dd = parseInt(inputStr.substring(delim1 + 1,delim2),10)
		var yyyy = parseInt(inputStr.substring(delim2 + 1,inputStr.length),10)
	}
	else {
		//there are no delimiters, extract component values
		var mm = parseInt(inputStr.substring(0,2),10)
		var dd = parseInt(inputStr.substring(2,4),10)
		var yyyy = parseInt(inputStr.substring(4,inputStr.length),10)
	}
	if (isNaN(mm) || isNaN(dd) || isNaN(yyyy)) {
		// there is a non-numeric character in one of the componenet values
		alert (alertText)
		gField.focus()
		gField.select()
		return false
	}
	if (mm < 1 || mm > 12) {
		// the month value is not 1 thru 12
		alert ("Months must be entered between 01 (January) and 12 (December).")
		gField.focus()
		gField.select()
		return false
	}
	if (dd < 1 || dd > 31) {
		// the date value is not 1 thru 31
		alert ("Days must entered between 01 and 31 (depending on the month and year).")
		gField.focus()
		gField.select()
		return false
	}
	// validate year.
	if (yyyy < 100 && yrDigits == 4) {
		// entered value is two digits, which will be allowed for 1960 - 2059
		if (yyyy >= 60) {
			yyyy += 1900
		}
		else {
			yyyy += 2000
		}
	} else if (yyyy > 100 && yyyy < 1000 && yrDigits == 2) {
			alert ("A two digit year must be entered.")
			gField.focus()
			gField.select()
			return false
	}	else if (yrDigits == 2 && yyyy > 999){
			// entered value is four digits, but we only want the last two
			var hold_yyyy = yyyy.toString()
			yyyy = parseInt(hold_yyyy.substring(2,4),10)
	}
	if (!checkMonthLength(mm,dd)) {
		gField.focus()
		gField.select()
		return false
	}
	if (mm == 2) {
		if (!checkLeapMonth(mm,dd,yyyy)) {
			gField.focus()
			gField.select()
			return false
		}
	}
	gField.value = monthDayFormat(mm) + "/" + monthDayFormat(dd) + "/"
	if (yrDigits == 4) {
		gField.value += yyyy
	}
	else {
		gField.value += monthDayFormat(yyyy)
	}
	return true
}

// check February day values for leap years or too high of day value
function checkLeapMonth(mm,dd,yyyy) {
	if (yyyy % 4 > 0 && dd > 28) {
		alert ("February of " + yyyy + " has only 28 days.")
		return false
	}
	else if (dd > 29) {
		alert ("February of " + yyyy + " has only 28 days.")
		return false
	}
	return true
}

// check the month for too high of day value
function checkMonthLength(mm,dd) {
	var months = new Array("","January","February","March","April","May","June","July","August","September","October","November","December")
	if ((mm == 4 || mm == 6 || mm == 9 || mm == 11) && dd > 30) {
		alert(months[mm] + " has only 30 days.")
		return false
	}
	else if (dd > 31) {
		alert (months[mm] + " has only 31 days.")
		return false
	}
	return true
}

// convert month or day number to string,
// padding with leading zero if needed
function monthDayFormat(val) {
   if (isNaN(val) || val == 0) {
      return "01"
   } else if (val < 10) {
      return "0" + val
   }
   return "" + val
}
//END Date Validation Function

function isAmt(field,done) {
   tstr=""+field.value;
   OK = true;
   nofPoints = 0;
   for (var i=0;i<tstr.length;i++) {
      if ('0123456789.-,'.indexOf(tstr.charAt(i)) ==-1) {
         alert('Numbers, negative sign, comma and decimal point only');
         OK=false;
         break;
      }
      else if (tstr.charAt(i)=='.') nofPoints++;
      if (nofPoints > 1) {
         alert('ONE decimal point only');
         OK=false;
         break;        
      }
			else if (tstr.charAt(i)=='-') nofPoints++;
      if (nofPoints > 1) {
         alert('ONE negative indicator only');
         OK=false;
         break;        
      }
   }
   if (!OK) {
      if (i>0) field.value=tstr.substring(0,i);
      else field.value ='';
   }
   else if (done) {
      dotPos = tstr.indexOf('.')
      decimals = tstr.substring(dotPos+1)  
      if (nofPoints > 0) {
         if (decimals.length < 2) {
            field.value += '00'.substring(0,2-decimals.length);
           
         }
         else field.value = tstr.substring(0,dotPos) + "" + tstr.substring(dotPos,dotPos+3)  
      }
      else field.value += '.00';
   }
   return OK;
}

function isTime(gField) {
	var inputStr = gField.value
	var alertText = "The time must be entered as HH:MM. "
	var delim1 = inputStr.indexOf(":")
	if (delim1 != -1) {
		//there are deliminters; extract component values
		var hh = parseInt(inputStr.substring(0,delim1),10)
		var mm = parseInt(inputStr.substring(delim1 + 1,inputStr.length),10)
	}
	else {
		//there are no delimiters, display alter text
		alert (alertText)
		gField.focus()
		gField.select()
		return false
	}
	if (isNaN(hh) || isNaN(mm)) {
		// there is a non-numeric character in one of the component values
		alert (alertText)
		gField.focus()
		gField.select()
		return false
	}
	if (hh < 1 || hh > 12) {
		// the hour value is not 1 thru 12
		alert ("Hours must be entered between 01 and 12")
		gField.focus()
		gField.select()
		return false
	}
	if (mm < 0 || mm > 59) {
		// the minute value is not 1 thru 59
		alert ("Minutes must entered between 00 and 59")
		gField.focus()
		gField.select()
		return false
	}
	gField.value = hourMinuteFormat(hh) + ":" + hourMinuteFormat(mm) 
	return true
}

// convert hour or minutes number to string,
// padding with leading zero if needed
function hourMinuteFormat(val) {
   if (isNaN(val) || val == 0) {
      return "00"
   } else if (val < 10) {
      return "0" + val
   }
   return "" + val
}