//
// This file contains common functions and should be included in all 
// html pages.  It also contains a simple redirection if any of the 
// authentication information is missing, reducing load on the server if
// users try to bookmark pages deep inside the html structure.
//
//
//

var SIMSWebDateForm = '1';

function ShowMessage(StartDate, EndDate)
{
        //
        // This function takes two dates in the form of 'September 11, 2001'
        // and if today's date is equal to or between those two dates it
        // will display the message passed in MessageToShow.
        //
        var today = new Date();
        var today = today.getTime();
        var startDT = new Date(StartDate);
        var startDT = startDT.getTime();
        var endDT = new Date(EndDate);
        var endDT = endDT.getTime();
        var result = false;
        if (startDT <= today)
        {
                if (endDT >= today)
                {
                        result = true;
                }
        }
        return result;
}


function NLI() {
        //
        // Just a common routine to give them a Not Logged In message.
        //
        window.alert('Insufficient Privelege to access the requested function.  Are you logged in?');
}

function is_Iphone()
{
  var agent=navigator.userAgent.toLowerCase();
  var is_iph = (agent.indexOf('iphone') != -1);
  return is_iph;
}

function Chgd(fldname) {
	// Just ignore the request, they used a date picker somewhere besides
	// account maintenance....
}

function ScreenWidth() {
        //
        // Returns the width of the browser display.
        //
        var TempArray = new Array();
        TempArray = navigator.userAgent.split(';')
        var PPCfound = -1;
        var Resolution = ''
        for (var x=0;x < 15;x++) {
                var Temp = ltrim(TempArray[x]);
                if (Temp=='PPC') {
                        PPCfound = x;
                        break;                          // exit for loop
                }
        }
        if (PPCfound != -1) {
                //
                // This is a PocketPC device so get the resolution from
                // the browser useragent string.
                //
                Resolution = screen.width;
                if (Resolution == null) {
                        Resolution = ltrim(TempArray[PPCfound + 1]);
                        var found = Resolution.indexOf('x');
                        if (found != -1) {
                                Resolution = Resolution.substr(0,found)
                        }
                }
        }
        else {
                //
                // This is a real browser so try new Javascript stuff...
                //
                Resolution = window.innerWidth;
                if (Resolution == null) {
                        //
                        // Only DOM compatible browsers use innerWidth so
                        // this must be IE, use the document.body instead.
                        //
                        Resolution = document.body.clientWidth;
                }
        }
        return Resolution;
}


function getSize(which)
//
// Returns the browser width or height, call with 'w' or 'h' respectively.
// For Internet Explorer, can only be called after the body tag.
//
{
        var winW = 0, winH = 0;
        if (parseInt(navigator.appVersion)>3)
        {
           if (navigator.appName=="Netscape")
           {
              winW = window.innerWidth;
              winH = window.innerHeight;
           }
           if (navigator.appName.indexOf("Microsoft")!=-1)
           {
              winW = document.body.clientWidth;
              winH = document.body.clientHeight;
           }
        }
if (which=='w') { return winW; } else { return winH; }
}


function Copies(character, newlength) {
	//
	// Creates a string with newlength copies of character in it.
	//
	var newvar = ''
	for (x = 0; x < newlength; x++) {
		newvar = newvar + character
		}
	return newvar;
}

function NoBreak(origvalue) {
	//
	// Creates a string with all spaces converted to &nbsp; in it.
	//
	var newvar = ''
	for (x = 0; x < origvalue.length; x++) {
		var thischar = origvalue.substring(x, x + 1)
		if (thischar == ' ') { thischar = '&nbsp;' }
		newvar = newvar + thischar
		}
	return newvar;
}


function TextAreaSizeCheck(fieldname, maxlines, maxlinelength) {
	// 
	// Checks the number of lines in a textarea control to make sure the
	// maxlines number of lines are not exceeded and that the length
	// of each line doesn't exceed maxlinelength.
	//
	var temp = fieldname.value;
	var TempArray = new Array();
	TempArray = temp.split(CRLF)
	var TextLines = TempArray.length;
	var Modified = false;
	var trimmed = ''
	if (TextLines > maxlines) {
		Modified = true;
		TextLines = maxlines
	}
	for (i = 0; i < TextLines; i++) {
		if (TempArray[i].length > maxlinelength) {
			Modified = true;
			TempArray[i] = TempArray[i].substring(0,maxlinelength);		
		}
		trimmed = trimmed + TempArray[i]
		if (i < TextLines - 1) { trimmed = trimmed + CRLF }
	}
	if (Modified) {
		fieldname.style.backgroundColor = 'RED';
		fieldname.value = trimmed;
		fieldname.style.backgroundColor = '';
	}
}

function CreateNumberList(lownum, highnum) {
	//
	// Outputs a sequence of <OPTION> tags with the numbers from lownum to
	// highnum on the list, all formatted to three characters long, ie: 001
	//
	for (xnum = lownum; xnum <= highnum; xnum++) {
		if (xnum <= 9) { 
			fnum = '00' + xnum
		}
		else if (xnum <= 99) {
			fnum = '0' + xnum
		}
		else {
			fnum = xnum
		}
		document.write('<OPTION value="'+fnum+'">' + fnum + '</option>');		
	}
}

function CreateDatePickerContents(fullYear) {
	var curDate = new Date();
	var curMonth = curDate.getMonth()
	var curDay = curDate.getDate()
	curMonth = curMonth + 1						// it is returned base 0
	if (fullYear) {
		var lowMonth = 1
		var lowDay = 1
	}
	else {
		var lowMonth = curMonth
		var lowDay = curDay
		if (curMonth == 12 && curDay >= 15) {
			var lowMonth = 1
			var lowDay = 1
		}
	}
	for (month = lowMonth; month <= 12; month++) {
		var highDay = 31
		if (month == 2) { highDay = 29 }
		if (month == 4) { highDay = 30 }
		if (month == 6) { highDay = 30 }
		if (month == 9) { highDay = 30 }
		if (month == 11) { highDay = 30 }
		for (day = lowDay; day <= highDay; day++) {
			var fmtMonth = month.toString()
			var fmtDay = day.toString()
			if (fmtMonth.length == 1) { fmtMonth = '0' + fmtMonth }
			if (fmtDay.length == 1) { fmtDay = '0' + fmtDay }
			var dbDate = fmtMonth+'/'+fmtDay
			if (SIMSWebDateForm == '3') {
				var showDate = fmtDay+'/'+fmtMonth
			}
			else {
				var showDate = dbDate
			}
			document.write('<OPTION value="'+dbDate+'">' + showDate + '</option>');		
		}
		if (lowDay != 1) { lowDay = 1 }
	}
}


function checkUAP(requested) {
   //
   // Decode the UAP cookie and then check to see if the level requested
   // is allowed.  Returns -1 if the access is granted, 0 if not.
   // If multiple priveleges are requested, ANY of them will satisfy.
   //
   // Syntax: if (checkUAP('A')) { do this }
   //
   var curUAP = getcookie('UAP');
   decoded = ' '+decodeit(curUAP);
   for (var x = '', i=0;i<requested.length;i++) {
       requestedflag = requested.substring(i,i+1)
       var found = decoded.indexOf(requestedflag);
       if (found != -1) { 
           // The requested privelege level is alowed
           return -1;
       }
   }
   return 0; 
}

function decodeit(encoded) {
   //
   // Decrypts the simple encryption created by encodeit.
   //
   for (var normal = '',i=encoded.length-1;i>-1;i=i-1) {
       normal += encoded.charAt(i);
   }
   for (var decoded = '', i=0;i<normal.length;i=i+2) {
   	   decoded += unescape('%'+normal.substring(i,i+2))
   }
   return decoded
}

function encodeit(value) {
   //
   // Performs a simple encryption on the value passed.
   //
   for (var text = '',i=0;i<value.length;i++) {
       text += value.charCodeAt(i).toString(16);
   }
   for (var encoded = '',i=text.length-1;i>-1;i=i-1) {
       encoded += text.charAt(i);
   }
   return encoded;
}

function setcookie(name, value, expires, path, domain, secure) {
   // 
   // Set a cookie for the current path.
   //
   document.cookie = name + "=" + value +
   ( (expires) ? ";expires=" + expires : "") +
   ( (path) ? ";path=" + path : "") +
   ( (domain) ? ";domain=" + domain : "") +
   ( (secure) ? ";secure": "");
}

function groupmask(xvar) {
   //
   // Read the UID and extract the group portion from it.
   // Returns ???? if there is no group for the current id.
   //
   var thisgroup = ''
   var curUID = getcookie('UID');
   var dash = curUID.indexOf("-");
   if (dash != -1) {
   	  thisgroup = curUID.substring(0,dash);
   }
   if (thisgroup == '') { thisgroup = '????' }
   return thisgroup;
}

function getcookie(name) {
   //
   // Read a cookie from those currently available to this document.
   //
   var start = document.cookie.indexOf(name+"=");
   var allcookie = document.cookie
   var len = start+name.length+1;
   var cookiestart = document.cookie.substring(0,name.length)
   if ((!start) && (name != cookiestart)) return null;
   var thiscookie=''
   if (start != -1) {
   	  var end = document.cookie.indexOf(";",len);
   	  if (end == -1) end = document.cookie.length;
   	  thiscookie = document.cookie.substring(len,end);
   }
   if (thiscookie == 'null') { thiscookie = '' }
   //   window.alert('cookies='+allcookie+'\nLookingfor='+name+'\nThiscookie='+thiscookie);
   return thiscookie;
}

function curTime(thisObject) {
   //
   // Returns the current time in hh:mm format into the object requested.
   //
   var Now = new Date();
   var Hrs = padZero(Now.getHours());
   var Min = padZero(Now.getMinutes());
   Now = '' + Hrs + ':' + Min
   thisObject.value = Now;
}

function curDate(thisObject) {
   //
   // Returns the current date in mm/dd/yyyy format into the object requested.
   //
   var Now = new Date();
   var Mon = Now.getMonth();
   Mon = padZero(Mon + 1);
   var Day = padZero(Now.getDate());
   var Yea = Now.getFullYear();
   Now = '' + Mon + '/' + Day + '/' + Yea
   thisObject.value = Now;
}

function sendinfo(dud) {
   //
   // Sets cookies based on the LOGON form (only used in index.html)
   //
   var uid = document.LOGON.username.value.toUpperCase();
   var uai = document.LOGON.password.value.toUpperCase();
   if (MemorizeUserName != 0) { 
	   var expdate = new Date();
	   // Calculate the date for thirty days from now to remember Username
	   expdate.setTime (expdate.getTime() + (1000 * 60 * 60 * 24 * 30));
	   expdate = expdate.toGMTString()
   }
   else { 
	   var expdate = ''
   }
   rc = setcookie('UID', uid, expdate, '/', '', '');     
   var errmsg = '\n'
   if (uid == '') { errmsg = errmsg + Txt_ERRM_UsernameRequired + '\n' }
   if (uai == '') { errmsg = errmsg + Txt_ERRM_PasswordRequired + '\n' }
   if (errmsg == '\n') {
	   var encodeduai = encodeit(uai)
	   rc = setcookie('UAI', encodeduai, '', '/', '', '');
       window.location.replace('/SW_LOGON.CMD?NEXT='+nextpage+'&SESSION='+encodeit(expdate));
   	   return false;
   }
   else {
       window.alert('ERROR\n'+errmsg);
   }
}

function OpenWindow(newurl, fieldname) {
	//
	// This opens a seperate window for the utility screens
	//
        rc = setcookie('FLD', fieldname, '', '/', '', '');     
	var w=window.open("","SIMSWeb_Util","resizable,scrollbars,status,width=600,height=310");
   	w.location = newurl;
}   

function OpenWindowLarge(newurl, fieldname) {
	//
	// This opens a seperate window for the utility screens
	//
    rc = setcookie('FLD', fieldname, '', '/', '', '');     
	var w=window.open("","SIMSWeb_Util","resizable,scrollbars,status,width=790,height=610");
   	w.location = newurl;
}   

function setfocus() {
   //
   // Sets a certain fields focus depending on if there is a saved name
   // stored in a cookie or not.  Only used in index.html
   //
   var curval = getcookie('UID')
   if (curval == '') {
		document.LOGON.username.focus()
   }
   else {
		document.LOGON.password.focus()
   }
}

function replaceAll(sourceString, lookfor, replacewith)
{
        var origString;
        do
        {
                origString = sourceString;
                sourceString = sourceString.replace(lookfor, replacewith);

        }while(sourceString != origString);
        return sourceString;
}

function SetSelection(whichobject, text) {
	// 
	// Find an item in the select list which has a value matching 'text'
	// and set the selectedIndex to it.
	//
	var maxitems = whichobject.length;
	var found = -1
	for (i = 0; i < maxitems; i++)  {
		var temp = whichobject[i].value;
		if (text == temp) { found = i }
	}
	if (found != -1) {
		whichobject.selectedIndex = found
	}
	else {
		whichobject.selectedIndex = 0
	}
	return found
}

function parsemenu(level, normaltext) {
    //
    // This function returns the text passed in normaltext IF the privelege
    // level requested is allowed.  If the privelege level requested is NOT
    // allowed then the generic spacer text is returned instead.
    //
    // This is used in the menu files (menu.html and menu_layer2.html)
    // to dynamically build the graphical buttons based on the user.
    //
	var todisplay = '<img src="/SIMSWeb/language/'+SIMSWebLanguage+'/images/mnu/mn_top_spacer.gif" width="110" height="21" border="0">'
	if (ShowDisabledMenuItems == '-1' && level != 'z') {
	    // Always show menus even if disabled EXCEPT if it's an admin menu.
	    todisplay = normaltext
	}
	else {
		if (checkUAP(level) == -1) { todisplay = normaltext }
    }
    todisplay = todisplay.replace('_LANGUAGE_',SIMSWebLanguage);
	return todisplay;
}
	
function FormatTime(aString, vObject) 
{
	var checkstring = StripFormatting(aString);
	var newstring="";
	for (var i = 0; i < checkstring.length; i++) 
		{
		var onechar = checkstring.charAt(i);
   		if (IsInteger(onechar))
			{
			if (newstring.length == 2)
				{
				newstring += ":";
			   	}
			newstring+=  onechar;
			}
	   	}
	var badtime = false;
	if (newstring.length != 5) { 
		badtime = true;
	}
	else {
		var hours = newstring.substring(0,2)
		var minutes = newstring.substring(3,5)
		if (hours >= 24) { badtime = true }
		if (hours <= -1) { badtime = true }
		if (minutes >= 60) { badtime = true }
		if (minutes <= -1) { badtime = true }
	}
	if (badtime == true) {
		if (aString != "")
		{
		vObject.value = aString;
                alert('Invalid Time Format, Try Again');
		vObject.focus();
		}
	}
	else
	{
                vObject.value = newstring;
	}
}

function StripFormatting(aField) {
var newstring="";
for (var i = 0; i < aField.length; i++) {
   var onechar = aField.charAt(i)

   if (onechar != '(' &&
       onechar != ')' &&
       onechar != '$' &&
       onechar != '-' &&
       onechar != '"' &&
       onechar != ',') 
	   {
          newstring+=onechar;

       }
   }
return newstring;
}

function IsInteger(InputVal) 
{
inputstr = "" + InputVal;
if (inputstr.length == 0) 
{ return false; 
}
for (var i = 0; i < inputstr.length; i++) {
   var onechar = inputstr.charAt(i);

   if (onechar >= "0" && onechar <= "9") 
   {
      continue;
	 }
   else 
   {
      return false; }
   }
return true;
}

function FormatHexNumber(aString, vObject, newlength)
{
	var checkstring = StripFormatting(aString);
	var CurHexSetting = AllowOnlyHexAccountNumbers;
	AllowOnlyHexAccountNumbers = '1'					// Temp over-ride
	if (IsHex(checkstring)) {
		vObject.value = padNumber(checkstring, newlength);
	}
	else {
		if (aString != "") {
			vObject.value = aString;
			vObject.focus();
			alert(Txt_InvalidHexNumber);
		}
	}
	AllowOnlyHexAccountNumbers = CurHexSetting;
}

function FormatNumber(aString, vObject, newlength)
{
	var checkstring = StripFormatting(aString);
	if (IsNbr(checkstring)) {
		vObject.value = padNumber(checkstring, newlength);
	}
	else {
		if (aString != "") {
			vObject.value = aString;
			vObject.focus();
			alert(Txt_InvalidNumber);
		}
	}
}


function IsHex(InputVal) {
	var maxalpha = 'F'
	if (AllowOnlyHexAccountNumbers == '0') { maxalpha = 'Z' }
	inputstr = "" + InputVal;
	if (inputstr.length == 0) {
		return false; 
	}
	for (var i = 0; i < inputstr.length; i++) {
	   var onechar = inputstr.charAt(i);
	   onechar = onechar.toUpperCase()
	   if (onechar >= "0" && onechar <= "9")  {
	      continue;
	   }
	   else if (onechar >= "A" && onechar <= maxalpha) {
	      continue;
	   }
	   else {
	      return false; 
	   }
    }
return true;
}

function IsNbr(InputVal) {
	inputstr = "" + InputVal;
	if (inputstr.length == 0) {
		return false; 
	}
	for (var i = 0; i < inputstr.length; i++) {
	   var onechar = inputstr.charAt(i);
	   onechar = onechar.toUpperCase()
	   if (onechar >= "0" && onechar <= "9")  {
	      continue;
	   }
	   else {
	      return false; 
	   }
    }
return true;
}


function FormatAccount(aString, vObject) 
// Account Number Formatting
{
	var valid = "-";
	if (aString.indexOf(valid,2) > 1 && aString.indexOf(valid,5) > 1) {
	}
	else {
	var checkstring = StripFormatting(aString);
	var newstring="";
	if (checkstring.length <= 7 && checkstring.length >= 3)
	{
	for (var i = 0; i < checkstring.length; i++) 
		{
		var onechar = checkstring.charAt(i);
   		if (IsHex(onechar))
			{
			if (newstring.length == 0)
				{
				 newstring +="0";
			   	 }
			if (newstring.length == 2)
				{
				 newstring +="-";
			   	 }
			if (newstring.length == 3)
				{
				 newstring +="0";
			   	 }
			if (newstring.length == 5)
				{
				newstring += "-";
			    }
			newstring+=  onechar;
			}
	   	}
	}
	if (checkstring.length >= 8 && checkstring.length <= 9)
	{
	for (var i = 0; i < checkstring.length; i++) 
		{
		var onechar = checkstring.charAt(i);
   		if (IsHex(onechar))
			{
			if (newstring.length == 2)
				{
				 newstring +="-";
			   	 }
			if (newstring.length == 5)
				{
				newstring += "-";
			    }
			newstring+=  onechar;
			}
	   	}
	}
	if (newstring.length < 3)
	{
		if (aString != "")
		{
		vObject.value = aString;
		vObject.focus();
		alert(Txt_InvalidAccountNumber);
		}
	}
	else
	{
	vObject.value = newstring.toUpperCase();
	}
}

function StripFormatting(aField) {
var newstring="";
for (var i = 0; i < aField.length; i++) {
   var onechar = aField.charAt(i)

   if (onechar != '(' &&
       onechar != ')' &&
       onechar != '$' &&
       onechar != '-' &&
       onechar != '"' &&
       onechar != ',') 
	   {
          newstring+=onechar;

       }
   }
return newstring;
}
}

function IsInteger(InputVal) 
{
inputstr = "" + InputVal;
if (inputstr.length == 0) 
{ return false; 
}
for (var i = 0; i < inputstr.length; i++) {
   var onechar = inputstr.charAt(i);

   if (onechar >= "0" && onechar <= "9") 
   {
      continue;
	 }
   else 
   {
      return false; }
   }
return true;
}

function GenericPhoneFormatter(InputVal) {
	var inputstr = "" + InputVal;
	var outputstr = ""
	var allowed = '0123456789 +-(),'
	if (inputstr.length == 0) { 
		return outputstr; 
	}
	for (var i = 0; i < inputstr.length; i++) {
	   	var onechar = inputstr.charAt(i);
       	var found = allowed.indexOf(onechar);
	    if (found != -1) { 
	    	outputstr += onechar
		}
	}
	return outputstr; 
}


function FormatPhone(aString, vObject) 
// Function:  Phone Number Formatting 
{
	var locale = SIMSWebPhoneFormat
	var lineend = aString.lastIndexOf(",");
	var prefix = aString.substring(0, lineend + 1);
	var phone = aString.substring(lineend + 1, aString.Length);
	var phone = GenericPhoneFormatter(phone) 
	var newstring="";
	if (locale == "American") {
		var checkstring = StripFormatting(phone);
		if (checkstring.length == 6)
		{
		for (var i = 0; i < checkstring.length; i++) 
			{
			var onechar = checkstring.charAt(i);
   			if (IsInteger(onechar))
				{
				if (newstring.length == 2)
					{
					newstring += "-";
			    	}
				newstring+=  onechar;
				}
	   		}
		}
		if (checkstring.length == 7)
		{
		for (var i = 0; i < checkstring.length; i++) 
			{
			var onechar = checkstring.charAt(i);
  	 		if (IsInteger(onechar))
				{
				if (newstring.length == 3)
					{
					newstring += "-";
				    }
				newstring+=  onechar;
				}
	   		}
		}
		if (checkstring.length == 8)
		{
		for (var i = 0; i < checkstring.length; i++) 
			{
			var onechar = checkstring.charAt(i);
   			if (IsInteger(onechar))
				{
				if (newstring.length == 4)
					{
					newstring += "-";
				    }
				newstring+=  onechar;
				}
		   	}
		}
		if (checkstring.length == 9)
		{
		for (var i = 0; i < checkstring.length; i++) 
			{
			var onechar = checkstring.charAt(i);
   			if (IsInteger(onechar))
				{
				if (newstring.length == 0)
					{
					 newstring +="(";
				   	 }
				if (newstring.length == 3)
					{
					newstring += ")";
				    }
				if (newstring.length == 7)
					{
					newstring += "-";
				    }
				newstring+=  onechar;
				}
		   	}
		}
		if (checkstring.length == 10)
		{
		for (var i = 0; i < checkstring.length; i++) 
			{
			var onechar = checkstring.charAt(i);
	   		if (IsInteger(onechar))
				{
				if (newstring.length == 0)
					{
					 newstring +="(";
				   	 }
				if (newstring.length == 4)
					{
					newstring += ")";
				    }
				if (newstring.length == 8)
					{
					newstring += "-";
				    }
				newstring+=  onechar;
				}
		   	}
		}
		if (checkstring.length == 11)
		{
		for (var i = 0; i < checkstring.length; i++) 
			{
			var onechar = checkstring.charAt(i);
	   		if (IsInteger(onechar))
				{
				if (newstring.length == 1)
					{
					 newstring +="(";
				   	 }
				if (newstring.length == 5)
					{
					newstring += ")";
				    }
				if (newstring.length == 9)
					{
					newstring += "-";
				    }
				newstring+=  onechar;
				}
		   	}
		}
		if (checkstring.length == 12)
		{
		for (var i = 0; i < checkstring.length; i++) 
			{
			var onechar = checkstring.charAt(i);
	   		if (IsInteger(onechar))
				{
				if (newstring.length == 2)
					{
					 newstring +="(";
				   	 }
				if (newstring.length == 6)
					{
					newstring += ")";
				    }
				if (newstring.length == 10)
					{
					newstring += "-";
				    }
				newstring+=  onechar;
				}
		   	}
		}
		if (checkstring.length < 6)
		{
			var newstring = aString;
		}
		if (checkstring.length > 12)
		{
			var newstring = aString;
		}
		else
		{
		vObject.value = prefix + newstring;
		}
	}
	if (locale == "Australian") {
		var checkstring = StripFormatting(phone);
		var First = "0";
		if (checkstring.length == 10 && aString.indexOf(First,0) < 1)
		{
		for (var i = 0; i < checkstring.length; i++) 
			{
			var onechar = checkstring.charAt(i);
   			if (IsInteger(onechar))
				{
				if (newstring.length == 2)
					{
					newstring += " ";
				    }
				if (newstring.length == 7)
					{
					newstring += "-";
				    }
				newstring+=  onechar;
				}
		   	}
		}
		if (checkstring.length == 8)
		{
		for (var i = 0; i < checkstring.length; i++) 
			{
			var onechar = checkstring.charAt(i);
	   		if (IsInteger(onechar))
				{
				if (newstring.length == 4)
					{
					newstring += "-";
				    }
				newstring+=  onechar;
				}
		   	}
		}
		if (checkstring.length == 9)
		{
		for (var i = 0; i < checkstring.length; i++) 
			{
			var onechar = checkstring.charAt(i);
   			if (IsInteger(onechar))
				{
				if (newstring.length == 0)
					{
					 newstring +="(";
				   	 }
				if (newstring.length == 2)
					{
					newstring += ")";
				    }
				if (newstring.length == 7)
					{
					newstring += "-";
				    }
				newstring+=  onechar;
				}
		   	}
		}
		if (checkstring.length == 10 && aString.indexOf(First,0) > 1)
		{
		for (var i = 0; i < checkstring.length; i++) 
			{
			var onechar = checkstring.charAt(i);
   			if (IsInteger(onechar))
				{
				if (newstring.length == 0)
					{
					 newstring +="(";
				   	 }
				if (newstring.length == 3)
					{
					newstring += ")";
				    }
				if (newstring.length == 8)
					{
					newstring += "-";
				    }
				newstring+=  onechar;
				}
		   	}
		}
		if (checkstring.length < 8)
		{
			var newstring = aString;
		}
		if (checkstring.length > 10)
		{
			var newstring = aString;
		}
		else
		{
		vObject.value = newstring;
		}
	}
	else {
		vObject.value = phone;
	}
}

function trimCRLF(oldvalue) {
	//
	// Removes all CR/LF's from a string
	//
	var strLen = oldvalue.length
	var newstring = ''
    for (var i = 0; i <= strLen; i++) {
    	var thisChar = oldvalue.substring(i,i+1)
    	if (thisChar == CR) { thisChar = '' }
    	if (thisChar == LF) { thisChar = '' }
    	if (thisChar != '') {
    		newstring = newstring + thisChar
    	}
    }
	return(newstring);
}

function ltrim(oldvalue) {
	//
        // Removes all leading spaces and nulls from a string
	//
	if (oldvalue == '') { return(oldvalue); }
        if (oldvalue == null) { return(oldvalue); }
	var strLen = oldvalue.length;
        for (var i = 0; i < strLen; i++) {
                var thisChar = oldvalue.substring(i,i+1)
                if (thisChar == '') { thisChar = ' ' }
                if (thisChar != ' ') { break }
                strLen = strLen - 1
        }
        var newvalue = oldvalue.substring(i,strLen+1)
	if (newvalue == ' ') { newvalue = '' }
	return(newvalue);
}

function rtrim(oldvalue) {
	//
	// Removes all trailing spaces and nulls from a string
	//
	if (oldvalue == '') { return(oldvalue); }
	var strLen = oldvalue.length;
    for (var i = strLen; i > 0; i = i - 1) {
    	var thisChar = oldvalue.substring(i,i+1)
    	if (thisChar == '') { thisChar = ' ' }
    	if (thisChar != ' ') { break }
    	strLen = strLen - 1
    }
	var newvalue = oldvalue.substring(0,strLen+1)
	if (newvalue == ' ') { newvalue = '' }
	return(newvalue);
}

function padded(oldvalue, newlength) {
	//
	// This adds as many spaces as needed to make the oldvalue the
	// newlength, or trims characters if it's too long.
	//
	var curlen = oldvalue.length
	var diff = newlength - curlen
    for (var pads = '', i = 0; i <= diff; i++) {
    	pads = pads + ' '
    }
	var newvalue = oldvalue + pads
	newvalue = newvalue.substring(0,newlength)
	return(newvalue)
}

function get(database, startpos, fieldlength) {
	//
	// This is a global function which gets a field from a form called ORIG
	// and the form element named in database.  It then gets the fieldlength
	// number of characters starting at starpos and returns that.
	// startpos is passed as 1 based, not 0 based so it matches the fields
	// used in SW_SAVE.CMD
	//
	var temp = eval('document.ORIG.'+database+'.value');
	startpos = startpos - 1
	var thisfield = temp.substring(startpos, startpos + fieldlength)
	return(thisfield)
}

function put(database, startpos, fieldlength, newvalue) {
	//
	// This is a global function which puts a field into a string
	// from the form element named in database.  It is used opposite the
	// get function in database work.  Note that the variable startpos
	// is passed as 1 based, not 0 based so it matches the fields
	// used in SW_SAVE.CMD
	//
	var empty = '                                                                                                    '
	var temp = eval('document.ORIG.'+database+'.value');
	startpos = startpos - 1
	var pretext = temp.substring(0, startpos)
	var posttext = temp.substring(startpos + fieldlength, temp.length)
	newvalue = newvalue + empty
	newvalue = newvalue.substring(0, fieldlength)
	var fullrecord = pretext + newvalue + posttext
	return(fullrecord)
}


function StripFormatting(aField) {
var newstring="";
for (var i = 0; i < aField.length; i++) {
   var onechar = aField.charAt(i)

   if (onechar != '(' &&
       onechar != ')' &&
       onechar != '$' &&
       onechar != '-' &&
       onechar != '"' &&
       onechar != '+' &&
       onechar != ',') 
	   {
          newstring+=onechar;

       }
   }
return newstring;
}
function IsInteger(InputVal) 
{
inputstr = "" + InputVal;
if (inputstr.length == 0) 
{ return false; 
}
for (var i = 0; i < inputstr.length; i++) {
   var onechar = inputstr.charAt(i);

   if (onechar >= "0" && onechar <= "9") 
   {
      continue;
	 }
   if (onechar == "?") 
   {
      continue;
	 }
   else 
   {
      return false; }
   }
return true;
}



function currencyFormat(fld, milSep, decSep, e) {
var key = '';
var whichCode = (window.Event) ? e.which : e.keyCode;
key = String.fromCharCode(whichCode);  // Get key value from key code
var strCheck = '0123456789. ';
if (strCheck.indexOf(key) == -1) return false;  // Not a valid key
return true;
}

function oldcurrencyFormat(fld,milSep, decSep, e) {
// Currency Formatting    
var sep = 0;
var key = '';
var i = j = 0;
var len = len2 = 0;
var strCheck = '0123456789';
var aux = aux2 = '';
var whichCode = (window.Event) ? e.which : e.keyCode;
if (whichCode == 13) return true;  // Enter
key = String.fromCharCode(whichCode);  // Get key value from key code
if (strCheck.indexOf(key) == -1) return false;  // Not a valid key
len = fld.value.length;
for(i = 0; i < len; i++)
if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) break;
aux = '';
for(; i < len; i++)
if (strCheck.indexOf(fld.value.charAt(i))!=-1) aux += fld.value.charAt(i);
aux += key;
len = aux.length;
if (len == 0) fld.value = '';
if (len == 1) fld.value = '0'+ decSep + '0' + aux;
if (len == 2) fld.value = '0'+ decSep + aux;
if (len > 2) {
aux2 = '';
for (j = 0, i = len - 3; i >= 0; i--) {
if (j == 3) {
aux2 += milSep;
j = 0;
}
aux2 += aux.charAt(i);
j++;
}
fld.value = '';
len2 = aux2.length;
for (i = len2 - 1; i >= 0; i--)
fld.value += aux2.charAt(i);
fld.value += decSep + aux.substr(len - 2, len);
}
return false;
}

var isNav4 = false, isNav5 = false, isIE4 = false
var strSeperator = "/"; 
// If you are using any Java validation on the back side you will want to use the / because 
// Java date validations do not recognize the dash as a valid date separator.
var vDateType = SIMSWebDateForm   // Set in SITE.JS
//                1 = mm/dd/yyyy
//                2 = yyyy/dd/mm  (Unable to do date check at this time)
//                3 = dd/mm/yyyy
var vYearType = 4; //Set to 2 or 4 for number of digits in the year for Netscape
var vYearLength = 2; // Set to 4 if you want to force the user to enter 4 digits for the year before validating.
var err = 0; // Set the error code to a default of zero
if(navigator.appName == "Netscape") {
if (navigator.appVersion < "5") {
isNav4 = true;
isNav5 = false;
}
else
if (navigator.appVersion > "4") {
isNav4 = false;
isNav5 = true;
   }
}
else {
isIE4 = true;
}
function DateFormat(vDateName, vDateValue, e, dateCheck, dateType) {
vDateType = SIMSWebDateForm;
// vDateName = object name
// vDateValue = value in the field being checked
// e = event
// dateCheck 
// True  = Verify that the vDateValue is a valid date
// False = Format values being entered into vDateValue only
// vDateType
// 1 = mm/dd/yyyy
// 2 = yyyy/mm/dd
// 3 = dd/mm/yyyy
//Enter a question sign for the first number and you can check the variable information.
if (vDateValue == "?") {
	alert("AppVersion = "+navigator.appVersion+" \nNav. 4 Version = "+isNav4+" \nNav. 5 Version = "+isNav5+" \nIE Version = "+isIE4+" \nYear Type = "+vYearType+" \nDate Type = "+vDateType+" \nSeparator = "+strSeperator);
	vDateName.value = "";
	vDateName.focus();
	return true;
}
var whichCode = (window.Event) ? e.which : e.keyCode;
if (e == '999') { whichCode = 0 }
// Check to see if a seperator is already present.
// bypass the date if a seperator is present and the length greater than 8
if (vDateValue.length > 8 && isNav4) {
	if ((vDateValue.indexOf("-") >= 1) || (vDateValue.indexOf("/") >= 1))
	return true;
}
//Eliminate all the ASCII codes that are not valid
var alphaCheck = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/-";
if (alphaCheck.indexOf(vDateValue) >= 1) {
	if (isNav4) {
		vDateName.value = "";
		vDateName.focus();
		vDateName.select();
		return false;
	}
	else {
		vDateName.value = vDateName.value.substr(0, (vDateValue.length-1));
		return false;
   	}
}
if (whichCode == 8) //Ignore the Netscape value for backspace. IE has no value
	return false;
else {
	//Create numeric string values for 0123456789/-
	//The codes provided include both keyboard and keypad values
	var strCheck = '47,48,49,50,51,52,53,54,55,56,57,58,59,95,96,97,98,99,100,101,102,103,104,105,191,189';
	if (strCheck.indexOf(whichCode) != -1) {
		if (isNav4) {
			if (((vDateValue.length < 6 && dateCheck) || (vDateValue.length == 7 && dateCheck)) && (vDateValue.length >=1)) {
				alert(Txt_InvalidDate);
				vDateName.value = "";
				vDateName.focus();
				vDateName.select();
				return false;
			}
			if (vDateValue.length == 6 && dateCheck) {
				var mDay = vDateName.value.substr(2,2);
				var mMonth = vDateName.value.substr(0,2);
				var mYear = vDateName.value.substr(4,4)
				//Turn a two digit year into a 4 digit year
				if (mYear.length == 2 && vYearType == 4) {
					var mToday = new Date();
					//If the year is greater than 30 years from now use 19, otherwise use 20
					var checkYear = mToday.getFullYear() + 30; 
					var mCheckYear = '20' + mYear;
					if (mCheckYear >= checkYear)
						mYear = '19' + mYear;
					else
						mYear = '20' + mYear;
				}
				var vDateValueCheck = mMonth+strSeperator+mDay+strSeperator+mYear;
				if (!dateValid(vDateValueCheck)) {
					alert(Txt_InvalidDate);
					vDateName.value = "";
					vDateName.focus();
					vDateName.select();
					return false;
				}
				return true;
			}
			else {
				// Reformat the date for validation and set date type to a 1
				if (vDateValue.length >= 8  && dateCheck) {
					if (vDateType == 1) // mmddyyyy
					{
						var mDay = vDateName.value.substr(2,2);
						var mMonth = vDateName.value.substr(0,2);
						var mYear = vDateName.value.substr(4,4)
						vDateName.value = mMonth+strSeperator+mDay+strSeperator+mYear;
					}
					if (vDateType == 2) // yyyymmdd
					{
						var mYear = vDateName.value.substr(0,4)
						var mMonth = vDateName.value.substr(4,2);
						var mDay = vDateName.value.substr(6,2);
						vDateName.value = mYear+strSeperator+mMonth+strSeperator+mDay;
					}
					if (vDateType == 3) // ddmmyyyy
					{
						var mMonth = vDateName.value.substr(2,2);
						var mDay = vDateName.value.substr(0,2);
						var mYear = vDateName.value.substr(4,4)
						vDateName.value = mDay+strSeperator+mMonth+strSeperator+mYear;
					}
					//Create a temporary variable for storing the DateType and change
					//the DateType to a 1 for validation.
					var vDateTypeTemp = vDateType;
					vDateType = 1;
					var vDateValueCheck = mMonth+strSeperator+mDay+strSeperator+mYear;
					if (!dateValid(vDateValueCheck)) {
						alert(Txt_InvalidDate);
						vDateType = vDateTypeTemp;
						vDateName.value = "";
						vDateName.focus();
						vDateName.select();
						return false;
					}
					vDateType = vDateTypeTemp;
					return true;
				}
				else {
					if (((vDateValue.length < 8 && dateCheck) || (vDateValue.length == 9 && dateCheck)) && (vDateValue.length >=1)) {
						alert(Txt_InvalidDate);
						vDateName.value = "";
						vDateName.focus();
						vDateName.select();
						return false;
					}
				}
			}
		}
		else {
			// Non isNav Check
			// Reformat date to format that can be validated. mm/dd/yyyy
			if (vDateValue.length >= 1 && dateCheck) {
				// Additional date formats can be entered here and parsed out to
				// a valid date format that the validation routine will recognize.
				var strSeparatorArray = new Array("-"," ","/",".");
		    	var intElementNr;
				var strDate = vDateName.value;
				var strDateArray;
				var splitdone = 0;
				var reformatfield = 0;
				var mMonth = '0';
				var mDay = '0';
				var mYear = '0';
				for (intElementNr = 0; intElementNr < strSeparatorArray.length; intElementNr++) {
					if (strDate.indexOf(strSeparatorArray[intElementNr]) != -1) {
						strDateArray = strDate.split(strSeparatorArray[intElementNr]);
						splitdone = -1;
					}
				}
				if (splitdone == 0) {
					// no seperators, so seperate it ourselves
					var temp = strDate.substring(0,2) + '/' + strDate.substring(2,4) + '/' + strDate.substring(4,8)
					strDateArray = temp.split('/');
					reformatfield = -1
				}

				if (vDateType == 1) // mm/dd/yyyy
				{
					var mMonth = strDateArray[0]
					var mDay = strDateArray[1]
					var mYear = strDateArray[2]
				}
				if (vDateType == 2) // yyyy/mm/dd
				{
					var mYear = strDateArray[0]
					var mMonth = strDateArray[1]
					var mDay = strDateArray[2]
				}
				if (vDateType == 3) // dd/mm/yyyy
				{
					var mDay = strDateArray[0]
					var mMonth = strDateArray[1]
					var mYear = strDateArray[2]
				}
				if (mMonth.length == 1) { 
					mMonth = '0' + mMonth 
					reformatfield = -1
				}
				if (mDay.length == 1) { 
					mDay = '0' + mDay
					reformatfield = -1
				}
				if (mYear.length == 1) { 
					mYear = '200' + mYear
					reformatfield = -1
				}
				if (mYear.length == 2) { 
					if (mYear >= 50) {
						mYear = '19' + mYear
					}
					else {
						mYear = '20' + mYear
					}
					reformatfield = -1
				}
				if (vYearLength == 4) {
					if (mYear.length < 4) {
						alert(Txt_InvalidDate);
						vDateName.value = "";
						vDateName.focus();
						return true;
					}
				}
				// Create temp. variable for storing the current vDateType
				var vDateTypeTemp = vDateType;
				// Change vDateType to a 1 for standard date format for validation
				// Type will be changed back when validation is completed.
				vDateType = 1;
				// Store reformatted date to new variable for validation.

				var vDateValueCheck = mMonth+strSeperator+mDay+strSeperator+mYear;
				if (mYear.length == 2 && vYearType == 4 && dateCheck) {
					//Turn a two digit year into a 4 digit year
					var mToday = new Date();
					//If the year is greater than 30 years from now use 19, otherwise use 20
					var checkYear = mToday.getFullYear() + 30; 
					var mCheckYear = '20' + mYear;
					reformatfield = -1
					if (mCheckYear >= checkYear)
						mYear = '19' + mYear;
					else
						mYear = '20' + mYear;
				}
				if (reformatfield == -1) {
					vDateValueCheck = mMonth+strSeperator+mDay+strSeperator+mYear;
					// Store the new value back to the field.  This function will
					// not work with date type of 2 since the year is entered first.
					if (vDateTypeTemp == 1) // mm/dd/yyyy
						vDateName.value = mMonth+strSeperator+mDay+strSeperator+mYear;
					if (vDateTypeTemp == 3) // dd/mm/yyyy
						vDateName.value = mDay+strSeperator+mMonth+strSeperator+mYear;
				} 
				if (!dateValid(vDateValueCheck)) {
					alert(Txt_InvalidDate);
					vDateType = vDateTypeTemp;
					vDateName.value = "";
					vDateName.focus();
					return true;
				}
				vDateType = vDateTypeTemp;
				return true;
			}
			else {
				return true;
			}
		}
  //  	if (vDateValue.length == 10&& dateCheck) {
//			if (!dateValid(vDateName)) {
//				// Un-comment the next line of code for debugging the dateValid() function error messages
//				//alert(err);  
//				alert("Invalid Date\nPlease Re-Enter");
//				vDateName.focus();
//				vDateName.select();
//			}
//		}
		return false;
	}
	else {
		// If the value is not in the string return the string minus the last
		// key entered.
//		window.alert(whichCode);
		if (isNav4) {
			vDateName.value = "";
			vDateName.focus();
			vDateName.select();
			return false;
		}
		else
		{
			if (whichCode == 13) {
				// This is ENTER, it's not really added to our string,
				// blur then focus the field so it formats properly.
				vDateName.blur()
				vDateName.focus()
			}
			else {
				// Remove the bad code
				vDateName.value = vDateName.value.substr(0, (vDateValue.length-1));
			}
			return false;
		}
	}
}
}

function padZero(num) {
	//
	// If the number is less than 10 then add a zero to the front
	//
	return ((num <= 9) ? ("0" + num) : num);
}

function padNumber(oldvalue, newlength) {
	//
	// This adds as many leading 0's as needed to make the oldvalue the
	// newlength, or trims characters if it's too long.
	//
	var curlen = oldvalue.length
	var diff = newlength - curlen
        for (var pads = '', i = 0; i < diff; i++) {
            pads = pads + '0'
        }
	var newvalue = pads + oldvalue 
	newvalue = newvalue.substring(0,newlength)
	return(newvalue)
}



function dateValid(objName) {
var strDate;
var strDateArray;
var strDay;
var strMonth;
var strYear;
var intday;
var intMonth;
var intYear;
var booFound = false;
var datefield = objName;
var strSeparatorArray = new Array("-"," ","/",".");
var intElementNr;
// var err = 0;
var strMonthArray = new Array(12);
strMonthArray[0] = Txt_MONTH1;
strMonthArray[1] = Txt_MONTH2;
strMonthArray[2] = Txt_MONTH3;
strMonthArray[3] = Txt_MONTH4;
strMonthArray[4] = Txt_MONTH5;
strMonthArray[5] = Txt_MONTH6;
strMonthArray[6] = Txt_MONTH7;
strMonthArray[7] = Txt_MONTH8;
strMonthArray[8] = Txt_MONTH9;
strMonthArray[9] = Txt_MONTH10;
strMonthArray[10] = Txt_MONTH11;
strMonthArray[11] = Txt_MONTH12;
//strDate = datefield.value;
strDate = objName;
if (strDate.length < 1) {
return true;
}
for (intElementNr = 0; intElementNr < strSeparatorArray.length; intElementNr++) {
if (strDate.indexOf(strSeparatorArray[intElementNr]) != -1) {
strDateArray = strDate.split(strSeparatorArray[intElementNr]);
if (strDateArray.length != 3) {
err = 1;
return false;
}
else {
strDay = strDateArray[0];
strMonth = strDateArray[1];
strYear = strDateArray[2];
}
booFound = true;
   }
}
if (booFound == false) {
if (strDate.length>5) {
strDay = strDate.substr(0, 2);
strMonth = strDate.substr(2, 2);
strYear = strDate.substr(4);
   }
}
//Adjustment for short years entered
if (strYear.length == 2) {
strYear = '20' + strYear;
}
strTemp = strDay;
strDay = strMonth;
strMonth = strTemp;
intday = parseInt(strDay, 10);
if (isNaN(intday)) {
err = 2;
return false;
}
intMonth = parseInt(strMonth, 10);
if (isNaN(intMonth)) {
for (i = 0;i<12;i++) {
if (strMonth.toUpperCase() == strMonthArray[i].toUpperCase()) {
intMonth = i+1;
strMonth = strMonthArray[i];
i = 12;
   }
}
if (isNaN(intMonth)) {
err = 3;
return false;
   }
}
intYear = parseInt(strYear, 10);
if (isNaN(intYear)) {
err = 4;
return false;
}
if (intMonth>12 || intMonth<1) {
err = 5;
return false;
}
if ((intMonth == 1 || intMonth == 3 || intMonth == 5 || intMonth == 7 || intMonth == 8 || intMonth == 10 || intMonth == 12) && (intday > 31 || intday < 1)) {
err = 6;
return false;
}
if ((intMonth == 4 || intMonth == 6 || intMonth == 9 || intMonth == 11) && (intday > 30 || intday < 1)) {
err = 7;
return false;
}
if (intMonth == 2) {
if (intday < 1) {
err = 8;
return false;
}
if (LeapYear(intYear) == true) {
if (intday > 29) {
err = 9;
return false;
   }
}
else {
if (intday > 28) {
err = 10;
return false;
      }
   }
}
return true;
}
function LeapYear(intYear) {
if (intYear % 100 == 0) {
if (intYear % 400 == 0) { return true; }
}
else {
if ((intYear % 4) == 0) { return true; }
}
return false;
}

var isReady = true;


