//
// 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.
//

function asc( thisChar)
{
        //
        // Return the Ascii code for the character specified.
        //
        var thisAsc = thisChar.charCodeAt( 0);
        return thisAsc;
}

function chr( asciiCode)
{
        //
        // Return a character from the ASCII code specified.
        //
        thisChar = String.fromCharCode( asciiCode);
        return thisChar;
}

function unHex(hexIn)
{
        return parseInt(hexIn,16);
}

//
// Checks if a number is in a numerical range and returns the source
// number if it is, or returns -1 if it is not.
//
function checkNumericRange(thisNum, low, high)
{
        var showMsg = false;
        if (thisNum < low) { showMsg = true; }
        if (thisNum > high) { showMsg = true; }
        if (showMsg)
        {
                window.alert(Txt_InvalidNumberRange + low + ' - ' + high);
                return -1;
        }
        return thisNum;
}

function unpackDate(packedDate)
{
        //
        // Unpacks a standard Dos-packed Date into a pretty mm/dd/yyyy date
        //
        var bin1 = binaryFromChar(packedDate.substr(0,1));
        var bin2 = binaryFromChar(packedDate.substr(1,1));
        var tempBin = bin2 + bin1;
        if (tempBin == '0000000000000000') { return ''; }
        var binYr = '0' + tempBin.substr(0,7);
        var binMo = '0000' + tempBin.substr(7,4);
        var binDa = '000' + tempBin.substr(11,5);
        var Yr = binaryToInt(binYr) + 1900;
        var Mo = binaryToInt(binMo);
        var Da = binaryToInt(binDa);
        var outDate = padzero(Mo,2)+"/"+padzero(Da,2)+"/"+padzero(Yr,4);
        return convertDate(outDate, 'A', SIMSWebDateForm);
}

//
// Converts a date from one date format to another.   Accepts either the
// numerical format identifier or the first letter of the language.
//
function convertDate(dateIn, fmtIn, fmtOut)
{
        //
        // 1 = American        mm/dd/yyyy
        // 2 = International   yyyy/mm/dd
        // 3 = European        dd/mm/yyyy
        //
        var dateOut = dateIn;
        var mo = -1;
        var da = -1;
        var yr = -1;
        var sep = '/';
        if (fmtIn == 'A') fmtIn = 1;
        if (fmtIn == 'I') fmtIn = 2;
        if (fmtIn == 'E') fmtIn = 3;
        if (fmtIn == 1)       { mo = 0; da = 3; yr = 6; sep = 2; }
        else if (fmtIn == 2)  { yr = 0; mo = 5; da = 8; sep = 4; }
        else if (fmtIn == 3)  { da = 0; mo = 3; yr = 6; sep = 2; }
        if ((mo + da + yr) > 3)
        {
                var sepChar = dateIn.substr(sep,1);
                if (fmtOut == 'A') fmtOut = 1;
                if (fmtOut == 'I') fmtOut = 2;
                if (fmtOut == 'E') fmtOut = 3;
                if (fmtOut == 1) { dateOut = '' + dateIn.substr(mo,2) + sepChar + dateIn.substr(da,2) + sepChar + dateIn.substr(yr,4); }
                if (fmtOut == 2) { dateOut = '' + dateIn.substr(yr,4) + sepChar + dateIn.substr(mo,2) + sepChar + dateIn.substr(da,2); }
                if (fmtOut == 3) { dateOut = '' + dateIn.substr(da,2) + sepChar + dateIn.substr(mo,2) + sepChar + dateIn.substr(yr,4); }
        }
        return dateOut;
}


function unpackTime(packedTime)
{
        //
        // Unpacks a standard Dos-packed Time into a pretty hh:mm:ss time
        //
        var bin1 = binaryFromChar(packedTime.substr(0,1));
        var bin2 = binaryFromChar(packedTime.substr(1,1));
        var tempBin = bin2 + bin1;
        if (tempBin == '0000000000000000') { return ''; }
        var binHr = '000' + tempBin.substr(0,5);
        var binMi = '00' + tempBin.substr(5,6);
        var binSe = '000' + tempBin.substr(11,5);
        var Hr = binaryToInt(binHr);
        var Mi = binaryToInt(binMi);
        var Se = binaryToInt(binSe);
        var outTime = padZero(Hr,2)+":"+padZero(Mi,2)+":"+padZero(Se,2);
        return outTime;
}

function intToTwoBytes(tempInt)
{
        var bit1 = Math.floor(tempInt / 256);
        var bit2 = Math.floor(tempInt % 256);
        var comb = chr(bit2) + chr(bit1);
//        window.alert('intToTwoBytes('+tempInt+')='+comb.charCodeAt(0)+","+comb.charCodeAt(1));
        return comb;
}


function packTime(unpackedTime)
{
        //
        // Packs a pretty time into a Dos-packed time of two characters.
        //
        var Hr = binaryFromInt(unpackedTime.substr(0,2));
        var Mi = binaryFromInt(unpackedTime.substr(3,2));
        var Se = binaryFromInt(unpackedTime.substr(6,2));
        var binHr = Hr.substr(3,5);
        var binMi = Mi.substr(2,6);
        var binSe = Se.substr(3,5);
        var binLong = binHr + binMi + binSe;
//        window.alert('Hr='+Hr+' Mi='+Mi+' Se='+Se+'\n'+binLong);
        var bin1 = binLong.substr(0,8);
        var bin2 = binLong.substr(8,8);
        var int1 = binaryToInt(bin1);
        var int2 = binaryToInt(bin2);
        return chr(int2) + chr(int1);
}

function packDate(unpackedDate)
{
        //
        // Packs a pretty date into a Dos-packed date of two characters.
        //
        unpackedDate = convertDate(unpackedDate, SIMSWebDateForm, 'A');
        var bYr = unpackedDate.substr(6,4) - 0;
        if (bYr > 1900)
        {
           bYr = bYr - 1900;
//           if (bYr > 99) { bYr = bYr - 100; }
        }
        var bMo = unpackedDate.substr(0,2) - 0;
        var bDa = unpackedDate.substr(3,2) - 0;
        var Yr = binaryFromInt(bYr);
        var Mo = binaryFromInt(bMo);
        var Da = binaryFromInt(bDa);
        var binYr = Yr.substr(1,7);
        var binMo = Mo.substr(4,4);
        var binDa = Da.substr(3,5);
        var binLong = binYr + binMo + binDa;
//      window.alert('Yr='+Yr+'/'+bYr+' Mo='+Mo+'/'+bMo+' Da='+Da+'/'+bDa+'\n'+binLong.substr(0,8)+' '+binLong.substr(8,8));
        var bin1 = binLong.substr(0,8);  
        var bin2 = binLong.substr(8,8);
        var int1 = binaryToInt(bin1);
        var int2 = binaryToInt(bin2);
        return chr(int2) + chr(int1);
}


function OpenCal(thisField)
{
        var tempURL = '/js/calendar/cal-mini.htm';
        var thisLeft = 0; 
        var thisTop = 0; 
        if (isIE())
        {
                thisLeft = window.screenLeft + thisLeft;
                thisTop = window.screenTop + thisTop;
        }
        else {
                thisLeft = window.screenX + thisLeft;
                thisTop = window.screenY + thisTop;
        }

        var obj = document.getElementById(thisField);
        x = 0;
        while (obj.offsetParent != null)
        {
                x += obj.offsetLeft;
                obj = obj.offsetParent;
        }
        x += obj.offsetLeft;
        var obj = document.getElementById(thisField);
        y = 0;
        while (obj.offsetParent != null)
        {
                y += obj.offsetTop;
                obj = obj.offsetParent;
        }
        y += obj.offsetTop;
        thisLeft += x;
        thisTop += y;

        var w=window.open("","CALMINI","resizable,scrollbars=no,status=no,left="+thisLeft+",top="+thisTop+",width=400,height=200");
        //
        // Set the focus now so even if it was behind another window, it will
        // come back to the front.
        //
        w.focus();
        //
        var needAmp = false;
        var dateForm = 'A';
        if (SIMSWebDateForm == 2) { dateForm = 'I'; }
        if (SIMSWebDateForm == 3) { dateForm = 'E'; }
        var defaultYear = '';
        var defaultMonth = '';
        var tempValue = document.getElementById(thisField).value;
        if (tempValue != '')
        {
                if (dateForm == 'A')
                {
                        defaultYear = tempValue.substr(6,4);
                        defaultMonth = tempValue.substr(0,2);
                }
                if (dateForm == 'E')
                {
                        defaultYear = tempValue.substr(6,4);
                        defaultMonth = tempValue.substr(3,2);
                }
                if (dateForm == 'I')
                {
                        defaultYear = tempValue.substr(0,4);
                        defaultMonth = tempValue.substr(5,2);
                }
        }
        if (dateForm != undefined)
        {
                if (needAmp) { tempURL += '&'; } else { tempURL += '?'; }
                tempURL += 'dateForm=' + dateForm;
                needAmp = true;
        }
        if (defaultYear < 1) { defaultYear = undefined; }
        if (defaultYear != undefined)
        {
                if (needAmp) { tempURL += '&'; } else { tempURL += '?'; }
                tempURL += 'Year=' + defaultYear;
                needAmp = true;
        }
        if (defaultMonth < 1) { defaultMonth = undefined; }
        if (defaultMonth != undefined)
        {
                if (needAmp) { tempURL += '&'; } else { tempURL += '?'; }
                tempURL += 'Month=' + defaultMonth;
                needAmp = true;
        }
        if (needAmp) { tempURL += '&'; } else { tempURL += '?'; }
        tempURL += '&Source=' + thisField;
        w.location.href = tempURL;
        return w;
}

function isIE()
{
        //
        // isIE returns true if we are using Internet Explorer, otherwise
        // assumes it's a fully DOM compliant browser.
        //
        var result = false;
        if (navigator.userAgent.indexOf('MSIE') >= 1) { result= true; }
        if (navigator.userAgent.indexOf('Internet Explorer') >= 1) { result= true; }
        return result;
}


function Chgd(fldname) {
	// Just ignore the request, they used a date picker somewhere besides
	// account maintenance....
}

function ScreenWidth() {
        //
        // This function returns the screen width for PocketPC devices as well
        // as for regular browsers.  Note that it gives the SCREEN width not
        // the viewable area in the current browser window.
        //
        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 = screen.width;
                }
        }
        return Resolution;
}

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;
        if (isNaN(strLen)) { return(oldvalue); }
        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 ShowImage(imagetag, imagename) {
	//
	// This function writes the image src= attribute based on the
	// language that is selected.  Syntax is:
	//
	// <scr ipt language="Javascript">ShowImage('width="40"',"hd/xyz.gif");</scr ipt>
	//
	// which will produce:
	//
	// <img width="40" src="/language/English/images/hd/xyz.gif">
	//
	var fulltag = '<img '+imagetag+' src="/language/' + SIMSWebLanguage + '/images/' + imagename + '" border=0>'
	document.write(fulltag);
}

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, fixIt) {
	// 
	// 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.
        // If fixIt is true, then the fields will be reformatted.  If fixIt
        // is false then it will just warn them by changing the background
        // color if it's not currently an acceptable format.
	//
	var temp = fieldname.value;
        temp = temp.replace(CRLF,LF);
	var TempArray = new Array();
        TempArray = temp.split(LF)
	var TextLines = TempArray.length;
	var Modified = false;
        var trimmed = ''
	if (TextLines > maxlines) {
		Modified = true;
                if (fixIt)
                {
                        TextLines = maxlines;
                }
	}
	for (i = 0; i < TextLines; i++)
        {
		if (TempArray[i].length > maxlinelength) {
			Modified = true;
                        if (fixIt)
                        {
                                TempArray[i] = TempArray[i].substring(0,maxlinelength);
                        }
		}
		trimmed = trimmed + TempArray[i]
                if (i < TextLines - 1) { trimmed = trimmed + LF }
	}
        if (!fixIt)
        {
                if (Modified)
                {
                        fieldname.style.backgroundColor = 'RED';
                }
                else
                {
                        fieldname.style.backgroundColor = '';
                }
        }
        else
        {
                if (Modified)
                {
                        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>');  
                        document.write('<OPTION value="'+showDate+'">' + 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 }
   //
   decoded = getPriv();
   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 getPriv() {
   //
   // Decode the UAP cookie and return it.
   //
   // Syntax: decoded = getPriv();
   //
   var curUAP = getcookie('UAP');
   decoded = ' '+decodeit(curUAP);
   return decoded;
}

function decodeit(encoded) {
   //
   // Decrypts the simple encryption created by encodeit.
   //
   var decoded = '';
   try
   {
           for (var normal = '',i=encoded.length-1;i>-1;i=i-1) {
               normal += encoded.charAt(i);
           }
           for (var i=0;i<normal.length;i=i+2) {
                   var thiscode = '%'+normal.substring(i,i+2);
                   decoded += unescape(thiscode)
           }
           var tp = '';
           for (var x=0;x<18;x++)
           {
                tp = tp + ' ' + decoded.charCodeAt(x);
           }
           // window.alert('in='+encoded+'\noutput length='+decoded.length+'\n'+tp);
   }
   catch(err)
   {
   }
   return decoded
}

function encodeit(value) {
   //
   // Performs a simple encryption on the value passed.
   //
   for (var text = '',i=0;i<value.length;i++) {
       var thiscode = value.charCodeAt(i).toString(16);
       if (thiscode.length < 2) { thiscode = '0' + thiscode; }
       text += thiscode;
   }
   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.
   //
   // If they are logged on with an account number then return ????
   // as well so the search screens look proper.
   //
   var thisgroup = ''
   var curUID = decodeit(getcookie('UID'));
   var dash = curUID.indexOf("-");
   if (curUID.substring(2,3) == '-') {
	   if (curUID.substring(5,6) == '-') {
			dash = -1;	   		
	   }
   }
   if (dash != -1) {
   	  thisgroup = curUID.substring(0,dash);
   }
   if (thisgroup == '') { thisgroup = '????' }
   return thisgroup;
}

function custaccess(dud) {
   //
   // Read the UID and determine if we are a customer logging in
   // or a dealer     
   // 
   // Returns the account number if it's a customer and not a dealer.
   //
   var curUID = decodeit(getcookie('UID'));
   var accountNumber = ''
   if (curUID.substring(2,3) == '-') {
	   if (curUID.substring(5,6) == '-') {
			accountNumber = curUID;	   		
	   }
   }
   return accountNumber;
}


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 sendinfo(dud) {
   //
   // Sets cookies based on the LOGON form (only used in index.html)
   //
   var uid = document.LOGON.username.value;
   var uai = document.LOGON.password.value;
   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', encodeit(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('/SIMSWeb/SIMSWeb.cgi?mode=login&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
	//
        if (checkUAP('Y')) {
                window.alert('List Disabled');
        } else {
                rc = setcookie('FLD', fieldname, '', '/', '', '');     
                var w=window.open("","SIMSWeb_Util","resizable,scrollbars,status,width=600,height=335");
                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 userInfo(thisPrompt)
{
        var rc = window.prompt(thisPrompt);
        if (rc == decodeit(getcookie('UID')))
        {
                OpenWindowLarge('/SIMSWeb/SIMSWeb.cgi?mode=userinfo', 'none');
        }
}

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 = decodeit(getcookie('UID'))
   if (curval == '') {
		document.LOGON.username.focus()
   }
   else {
		document.LOGON.password.focus()
   }
}

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="/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;
              vObject.focus();
              alert(Txt_InvalidTime);
         }
     }
     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 != ' ' &&
          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();
                        window.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;
			alert(Txt_InvalidNumber);
//                        vObject.focus();
		}
	}
}


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;
		alert(Txt_InvalidAccountNumber);
		}
	}
	else
	{
	vObject.value = newstring.toUpperCase();
	}
}
}


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:  Phone Number Formatting 
function FormatPhone(aString, vObject) 
{
	var locale = SIMSWebPhoneFormat
        var prefix = '';
        var phone = aString;
	var lineend = aString.lastIndexOf(",");
        if (lineend > -1)
        {
                prefix = aString.substring(0, lineend + 1);
                phone = aString.substring(lineend + 1);
        }


	var phone = GenericPhoneFormatter(phone) 


	var newstring="";
	if (locale == "American") {
		var checkstring = StripFormatting(phone);

//                window.alert('American stripped='+checkstring+'!! length='+checkstring.length);

		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 == 9)
					{
					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 == 6)
					{
                                        newstring += ") ";
				    }
                                if (newstring.length == 11)
					{
					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;
		}
	}
        else if (locale == "Australian") {
		var checkstring = StripFormatting(phone);
		var First = "0";
		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 == 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 == 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 = prefix + newstring;
		}
	}
        else if (locale == "Dutch") {
		var checkstring = StripFormatting(phone);
		var First = "0";
                if (checkstring.length == 10)
		{
		for (var i = 0; i < checkstring.length; i++) 
			{
			var onechar = checkstring.charAt(i);
   			if (IsInteger(onechar))
				{
                                if (newstring.length == 2)
                                {
                                    if (newstring == '06')
                                    {
                                        newstring += "-";
                                    }
                                }
                                else
                                    {
                                    if (newstring.length == 3)
                                        {
                                            if (newstring != '06-')
                                            {
                                                newstring += "-";
                                            }
                                        }
				    }
				newstring+=  onechar;
				}
		   	}
		}
                else
		{
                vObject.value = phone;
		}
	}
	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 stripNBSP(stringtochange) {
        //
        // This removes all &nbsp; strings from the string then trims it.
        //
        stringtochange = stringtochange.replace('&nbsp;','');
        stringtochange = stringtochange.replace('&nbsp;','');
        stringtochange = ltrim(stringtochange);
        return stringtochange;
}

function rtrimcolon(oldvalue) {
	//
        // Removes all trailing spaces, nulls and colons from the 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)
                var thisAsci = thisChar.charCodeAt(0);
                if (thisAsci > 65000) { thisChar = ' ' }
                if (thisChar == ':') { thisChar = ' ' }
                if (thisChar == '') { thisChar = ' ' }
                if (thisChar != ' ') { break }
                strLen = strLen - 1
        }
	var newvalue = oldvalue.substring(0,strLen+1)
	if (newvalue == ' ') { newvalue = '' }
	return(newvalue);
}


function rtrim(oldvalue) {
	//
	// Removes all trailing spaces and nulls from a string
	//
	if (oldvalue == '') { return(oldvalue); }
        var newvalue = '';
        try
        {
                var strLen = oldvalue.length;
                for (var i = strLen; i >= 0; i = i - 1)
                {
                        var thisChar = oldvalue.substring(i,i+1)
                        var thisAsci = thisChar.charCodeAt(0);
                        if (thisAsci > 65000) { thisChar = ' ' }
                        if (thisChar == '') { thisChar = ' ' }
                        if (thisChar != ' ') { break }
                        strLen = strLen - 1
                }
                newvalue = oldvalue.substring(0,strLen + 1);
                if (newvalue == ' ') { newvalue = '' }
        }
        catch(err)
        {
                return oldvalue;
        }
	return(newvalue);
}

function unNull(oldvalue) {
	//
        // Converts all nulls to spaces
	//
	if (oldvalue == '') { return(oldvalue); }
        var newvalue = '';
	var strLen = oldvalue.length;
        for (var i = 0; i < strLen; i++) {
                var thisChar = oldvalue.substring(i,i+1)
                var thisAsci = thisChar.charCodeAt(0);
                if (thisAsci < 1) thisAsci = 65535;
                if (thisAsci > 65000) { thisChar = ' ' }
                newvalue = newvalue + thisChar;
        }
	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
//  Changed this on 200804 to be < diff only
//         for (var pads = '', i = 0; i <= diff; i++) {
        for (var pads = '', i = 0; i < diff; i++) {
                pads = pads + ' '
        }
	var newvalue = oldvalue + pads
	newvalue = newvalue.substring(0,newlength)
	return(newvalue)
}

function padzero(oldvalue, newlength) {
	//
        // This adds as zeros to the front as needed to make the oldvalue
        // the newlength, or trims characters if it's too long.
	//
        oldvalue = '' + ltrim(rtrim(oldvalue));
//        dump('\noldvalue='+oldvalue+'!!\n');
        var curlen = oldvalue.length;
//        dump('\npadzero '+oldvalue+' length='+curlen+'\n');
        if (isNaN(curlen)) { curlen = 0; }
	var diff = newlength - curlen
        for (var pads = '', i = 0; i < diff; i++) {
                pads = pads + '0'
        }
        var newvalue = pads + oldvalue;
//        dump('padzero '+newvalue+' length='+newvalue.length);
        newvalue = newvalue.substr(0,newlength)
	return(newvalue)
}

function strrev(str)
{
    return str.split("").reverse().join("");
}

function binaryToInt(thisBinary)
{
        var currnum = 128;
        var num2 = 0;
        for (i = 0; i <= 7; i++)
        {
               num2 = num2 + (thisBinary.charAt(i) * currnum);
               if (i < 7)
               {
                    currnum = currnum / 2;
               }
        }
        return num2;
}

function binaryFromChar(thisChar)
{
        //
        // Returns an eight character binary string from a character.
        //
        var tmp = asc(thisChar);
        return binaryFromInt(tmp);
}

function setBit(thisChar, bitNum)
{
        //
        // Sets a bit to either to true in a character and
        // returns the resulting character.
        //
        var thisBin = strrev(binaryFromChar(thisChar));
        var pre = thisBin.substr(0,bitNum);
        var pst = thisBin.substr(bitNum + 1);
        var newBin = strrev(pre + '1' + pst);
//        window.alert('oldbin='+thisBin+'\nbit='+bitNum+'\nnewbin='+newBin);
        return chr(binaryToInt(newBin));
}

function binaryFromInt(thisInt)
{
        //
        // Returns an eight character binary string from an integer.
        //
        var tempInt = thisInt - 0;
        var tmp = tempInt.toString(2);
        var pad = padzero(tmp,8);
//        window.alert('binaryFromInt=('+tempInt+') return='+pad+' tmp='+tmp);
        return pad;
}

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 getvar(temp, startpos, fieldlength) {
	//
        // This is a global function which gets a field from a variable passed.
        // 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
	//
	startpos = startpos - 1
        var thisfield = temp.substr(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 temp = eval('document.ORIG.'+database+'.value');
	startpos = startpos - 1
        var pretext = temp.substr(0, startpos)
        var posttext = temp.substr(startpos + fieldlength)
        var curlen = newvalue.length;
        var nullCount = 0;
        if (curlen < fieldlength)
        {
                for (var x = curlen; x < fieldlength; x++)
                {
                        newvalue += chr(0);
                        nullCount++;
                }
        }
        newvalue = newvalue.substr(0, fieldlength)
        // dump('PUT curlen='+curlen+' reqlength='+fieldlength+' nullCount='+nullCount +' newlen='+ newvalue.length +' \n');
	var fullrecord = pretext + newvalue + posttext
        // dump(unNull(fullrecord)+'\n');
	return(fullrecord)
}

function putvar(temp, startpos, fieldlength, newvalue) {
	//
        // This is a global function which puts a field into a string. It is
        // used opposite the getvar 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
	//
	startpos = startpos - 1
        var pretext = temp.substr(0, startpos)
        var posttext = temp.substr(startpos + fieldlength)
        var curlen = newvalue.length;
        var nullCount = 0;
        if (curlen < fieldlength)
        {
                for (var x = curlen; x < fieldlength; x++)
                {
                        newvalue += chr(0);
                        nullCount++;
                }
        }
        newvalue = newvalue.substr(0, fieldlength)
        // dump('PUT curlen='+curlen+' reqlength='+fieldlength+' nullCount='+nullCount +' newlen='+ newvalue.length +' \n');
	var fullrecord = pretext + newvalue + posttext
        // dump(unNull(fullrecord)+'\n');
	return(fullrecord)
}



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 }
if (whichCode == 40) { whichCode = 0; }         // Up,
if (whichCode == 39) { whichCode = 0; }         // Right,
if (whichCode == 38) { whichCode = 0; }         // Left and
if (whichCode == 37) { whichCode = 0; }         // Down arrows
// 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
        if (whichCode == undefined)  { whichCode = 0; }

	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';
        var findIt = strCheck.indexOf(whichCode);


	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.
		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 {
                                if (whichCode != undefined) {
                                        // 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 padzero(num,2);
}




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;
}

// window.onerror = function(msg,url,line){
//    var tp = Txt_JavaScriptError + '\n\nUrl: ' + url + '\n\nLine: ' + line + '\n\nError: ' + msg
//   window.alert(tp);
// }  

//
// The following code gets run automatically by each page that includes
// this file (functions.js) in it.  
//
var x = 0
var curDBG = getcookie('DBG');
var curUAP = getcookie('UAP');
var curUID = decodeit(getcookie('UID'));
var curUAI = getcookie('UAI');
var curEXP = getcookie('!!!');
if (curUAP != '') { x++ }
if (curUID != '') { x++ }
if (curUAI != '') { x++ }
// if (curEXP != '') { x++ }
x++
var curSID = getcookie('SID');
var winSID = window.name;
if (winSID != curSID)
{
        if (winSID == '')
        {
                // They opened a new window (or we did), set the SID.
                window.name = curSID;
        }
}

if (curDBG.indexOf('LOGOUT') != -1) { x-- }
if (x != 4) { 
	var curpage = document.URL
	if (curDBG.indexOf('WHYFORCED') != -1) {
		var tp = curpage+'\nEXP='+curEXP+'\nDBG='+curDBG+'\nUAP='+curUAP+'\nUID='+curUID+'\nUAI='+curUAI+'\nx='+x
		window.alert(tp);
	}
//        if (curpage.indexOf('index.html') == -1) {
//                window.top.location.replace('index.html?EXPIRED'); 
//        }
}
// 
// var expdate = new Date();
// var newtime = expdate.getTime() + (1000 * 60 * 20)
// expdate.setTime (newtime);
// expdate = expdate.toGMTString()
// var rc = setcookie('!!!', newtime, expdate, '/', '', '');     
// 
var isReady = true;
var ocreport = '0';

//
// Setup a global variable for when we loaded the page.
//
var pageLoadTime = new Date();
var timeoutUpdates = 0;
var autoLogOutTimer = getcookie('ALT');
var timerTick = 5000;
function isAlive()
{
    pageLoadTime = new Date();
}

function checkLoggedOff()
{
    clearTimeout(timeoutUpdates);
    var tmpUAP = getcookie('UAP');
    if (tmpUAP == '')
    {
        //
        // Our main window has been logged off, so close this window.
        //
        // window.// dump(document.location+': No longer logged in, closing window\n');
        window.close();
    }
    else
    {
        // window.// dump(document.location+': Still logged in, all ok\n');
        timeoutUpdates = setTimeout(checkLoggedOff,timerTick);
    }
}

function checkIdle()
{
    clearTimeout(timeoutUpdates);
    var currentTime = new Date();
    var gapval = currentTime.getTime() - pageLoadTime.getTime();
    gapval = Math.floor(gapval / 1000);
    // gapval contains the number of seconds since we got to this page.
    if (gapval > (autoLogOutTimer))
    {
        // window,// dump('Timer has expired: '+gapval+'\n');
        window.top.document.location = '/SIMSWeb/SIMSWeb.cgi?mode=logout';
    }
    else
    {
        // window.// dump(window.top.location+': '+gapval + '\n');
        timeoutUpdates = setTimeout(checkIdle,timerTick);
    }
}
if (autoLogOutTimer > 0)
{
        window.onmousemove = window.top.isAlive;
        window.onmousedown = window.top.isAlive;
        window.onkeydown = window.top.isAlive;
        
        var thispage = ' ' + document.location;
        var foundmenu = thispage.indexOf('/menu.html');
        if (foundmenu > 1)
        {
                //
                // Only fire our timer if we are the main menu frame.
                //
                timeoutUpdates = setTimeout(checkIdle,timerTick);
        }
                                         
        var subwindow = false;
        thispage = ' ' + window.top.document.location;
        if (thispage.indexOf('/SIMSWeb.cgi') > 0) { subwindow = true; }
        if (subwindow == true)
        {
                //
                // This is a sub-window so start a different timer.
                //
                timeoutUpdates = setTimeout(checkLoggedOff,timerTick);
        }
}        
