/**
 * Script:  jsVBScriptFunctions.js
 * Author:  Todd Lucas,  2003/08/12
 * Desc:    VBScript-Like functions for JavaScript.
 */


/*---------------------------------------------------------------------------------------
    Func: Right(str,n)
    In:   str - the string we are RIGHTing
          n   - the number of characters we want to return

    Out:  n characters from the right side of the string
  ---------------------------------------------------------------------------------------*/
function Right(str, n) {

    if (n <= 0)                                        // Invalid bound, 
        return "";                                     //   return blank string
    else if (n > String(str).length)                   // Invalid bound,
        return str;                                    //   return entire string
    else {                                             // Valid bound, 
        var iLen = String(str).length;                 //  return appropriate substring
        return String(str).substring(iLen, iLen - n);
    }
}



/*---------------------------------------------------------------------------------------
    Func: Left(str,n)
    In:   str - the string we are LEFTing
          n   - the number of characters we want to return

    Out:  n characters from the left side of the string
  ---------------------------------------------------------------------------------------*/
function Left(str, n) {

    if (n <= 0)                                        // Invalid bound, 
        return "";                                     //   return blank string
    else if (n > String(str).length)                   // Invalid bound,
        return str;                                    //   return entire string
    else                                               // Valid bound, 
        return String(str).substring(0,n);             //   return appropriate substring
}



/*---------------------------------------------------------------------------------------
    Func: Mid(str, start, len)
    In:   str   - the string we are MIDing
          start - our string's starting position (1 based!!)
          len   - how many characters from start we want to get

    Out:  The substring from start to start+len
  ---------------------------------------------------------------------------------------*/
function Mid(str, start, len) {

    // Make sure start and len are within proper bounds
    if (start < 0 || len < 0) return "";

    var iEnd, iLen = String(str).length;
    if (start + len > iLen)
        iEnd = iLen;
    else
        iEnd = start + len;

    return String(str).substring(start,iEnd);
}



/*---------------------------------------------------------------------------------------
    Func: Len(str)
    In:   str - the string to return the length of

    Out:  The number of characters in the string
  ---------------------------------------------------------------------------------------*/
function Len(str) {
    return String(str).length;  
}



/*---------------------------------------------------------------------------------------
    Func: InStr(lngStartPos,strSearch,strSearchFor)
    In:   lngStartPos - starting position to search. 
    In:   strSearch - the string to search.
    In:   strSearchFor - the string to find.

    Out:  first location a substring (SearchForStr), or -1 if not found
  ---------------------------------------------------------------------------------------*/
function InStr(lngStartPos, strSearch, strSearchFor) {

    for (j=lngStartPos; j < Len(strSearch); j++) {
        if (strSearchFor == Mid(strSearch, j, Len(strSearchFor))) return j;
	}
	return -1;
}



/*---------------------------------------------------------------------------------------
    Func: LTrim(str)
    In:   str - the string we want to LTrim

    Out:  An LTrimmed string!
  ---------------------------------------------------------------------------------------*/
function LTrim(str) {

    var whitespace = new String(" \t\n\r");
    var s = new String(str);

    if (whitespace.indexOf(s.charAt(0)) != -1) {

        // We have a string with leading blank(s)...
        var j=0, i = s.length;

        // Iterate from the far left of string until we don't have any more whitespace...
        while (j < i && whitespace.indexOf(s.charAt(j)) != -1)
            j++;

        // Get the substring from the first non-whitespace character to the end of the string...
        s = s.substring(j, i);
    }

    return s;
}



/*---------------------------------------------------------------------------------------
    Func: RTrim(str)
    In:   str - the string we want to RTrim

    Out:  An RTrimmed string!
  ---------------------------------------------------------------------------------------*/
function RTrim(str) {

    // We don't want to trip JUST spaces, but also tabs,
    // line feeds, etc.  Add anything else you want to
    // "trim" here in Whitespace
    var whitespace = new String(" \t\n\r");
    var s = new String(str);

    if (whitespace.indexOf(s.charAt(s.length-1)) != -1) {

        // We have a string with trailing blank(s)...
        var i = s.length - 1;       // Get length of string

        // Iterate from the far right of string until we
        // don't have any more whitespace...
        while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1)
            i--;

        // Get the substring from the front of the string to
        // where the last non-whitespace character is...
        s = s.substring(0, i+1);
    }

    return s;
}



/*---------------------------------------------------------------------------------------
    Func: Trim(str)
    In:   str - the string we want to Trim

    Out:  A Trimmed string!
  ---------------------------------------------------------------------------------------*/
function Trim(str) {

    return RTrim(LTrim(str));
}



/*---------------------------------------------------------------------------------------
    Func: Replace(inputString, fromString, toString)
    In:   inputString - the string to search and replace
          fromString  - from text
          toString    - to text

    Out:  The Replaced string.
  ---------------------------------------------------------------------------------------*/
function Replace(inputString, fromString, toString) {

   // If nothing to search then we are done:
   var temp = inputString;
   if (fromString == "") return inputString;

    // If string being replaced is not a part of the replacement string (normal situation):
   if (toString.indexOf(fromString) == -1) { 
      while (temp.indexOf(fromString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(fromString));
         var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
         temp = toTheLeft + toString + toTheRight;
      }

   // String being replaced is part of replacement string (like "+" being replaced with "++") - prevent infinite loop:
   } else { 
      var midStrings = new Array("~", "`", "_", "^", "#");
      var midStringLen = 1;
      var midString = "";

      // Find a string that doesn't exist in the inputString to be used as an "inbetween" string:
      while (midString == "") {
         for (var i=0; i < midStrings.length; i++) {
            var tempMidString = "";
            for (var j=0; j < midStringLen; j++) { tempMidString += midStrings[i]; }
            if (fromString.indexOf(tempMidString) == -1) {
               midString = tempMidString;
               i = midStrings.length + 1;
            }
         }
      } // Keep on going until we build an "inbetween" string that doesn't exist

      // Now go through and do two replaces - first, replace the "fromString" with the "inbetween" string
      while (temp.indexOf(fromString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(fromString));
         var toTheRight = temp.substring(temp.indexOf(fromString)+fromString.length, temp.length);
         temp = toTheLeft + midString + toTheRight;
      }

      // Next, replace the "inbetween" string with the "toString"
      while (temp.indexOf(midString) != -1) {
         var toTheLeft = temp.substring(0, temp.indexOf(midString));
         var toTheRight = temp.substring(temp.indexOf(midString)+midString.length, temp.length);
         temp = toTheLeft + toString + toTheRight;
      }
   } // Ends the check to see if the string being replaced is part of the replacement string or not

   // Send the updated string back to the user
   return temp; 
}


/*---------------------------------------------------------------------------------------
    Func: UCase(str)
    In:   str - the string we want to convert to UPPER case

    Out:  UPPER Case string
  ---------------------------------------------------------------------------------------*/
function UCase(str) {

    return str.toUpperCase();
}


/*---------------------------------------------------------------------------------------
    Func: LCase(str)
    In:   str - the string we want to convert to lower case

    Out:  lower Case string
  ---------------------------------------------------------------------------------------*/
function LCase(str) {

    return str.toLowerCase();
}



/*---------------------------------------------------------------------------------------
    IsNumeric - Returns a Boolean value indicating whether an expression can be evaluated 
                as a number (this includes values like $15,656.00).

    Parameters:
    Expression = Variant containing a numeric expression or string expression.

    Returns: Boolean
  ---------------------------------------------------------------------------------------*/
function IsNumeric(Expression) {

   Expression = Expression.toLowerCase();
   RefString = "0123456789.-";

   if (Expression.length < 1) return (false);

   for (var i = 0; i < Expression.length; i++) {
      var ch = Expression.substr(i, 1)
      var a = RefString.indexOf(ch, 0)
      if (a == -1) return (false);
   }

   return(true);
}



/*---------------------------------------------------------------------------------------
    IsDate - Returns a Boolean value indicating whether an expression can be evaluated 
             as a date.

    Parameters:
    Expression = Variant containing a date expression or string expression.

    Returns: Boolean
  ---------------------------------------------------------------------------------------*/
function IsDate(Expression) {

    // Determine if passed value is a date or not.
    var dDate, bResult;
    var dDate = new Date(Expression);
    isNaN(dDate)? bResult=false : bResult=true;
    return bResult;
}



/*---------------------------------------------------------------------------------------
    Chr - Return a String containing the character associated with the specified character 
          code.

    Parameters:
    CharCode = Long that identifies a character.

    Returns: String
  ---------------------------------------------------------------------------------------*/
function Chr(CharCode) {
   return String.fromCharCode(CharCode);
}



/*---------------------------------------------------------------------------------------
    Asc - Returns an Integer representing the character code corresponding to the first 
          letter in a string

    Parameters:
    String = The required string argument is any valid string expression. If the string is 
             not in the range 32-126, the function returns ZERO.

    Returns: Integer
  ---------------------------------------------------------------------------------------*/
function Asc(string) {

   var symbols = " !\"#$%&'()*+'-./0123456789:;<=>?@";
   var loAZ = "abcdefghijklmnopqrstuvwxyz";
   symbols += loAZ.toUpperCase();
   symbols += "[\\]^_`";
   symbols += loAZ;
   symbols += "{|}~";

   var loc;
   loc = symbols.indexOf(string);

   if (loc > -1) { 
      Ascii_Decimal = 32 + loc;
      return (32 + loc);
   }

   return (0);
}



/*---------------------------------------------------------------------------------------
    LBound - Returns a Long containing the smallest available subscript for the indicated 
             dimension of an array.

    Parameters:
    array = Array to verify.

    Returns: Integer (-1 if Array does not contain any subscript).
  ---------------------------------------------------------------------------------------*/
function LBound(array) {

   var i = 0;
   var temp = '';

   if (array.length == 0)
      return (-1);

   for (i = 0; i < array.length; i++) {
      temp = array[i]
      if (temp != null) {
         var temp = i;
         return temp;
      }
   }

   return (-1);
}



/*---------------------------------------------------------------------------------------
    UBound - Returns a Long containing the largest available subscript for the indicated 
             dimension of an array.

    Parameters:
    array = Array to verify.

    Returns: Integer (-1 if Array does not contain any subscript).
  ---------------------------------------------------------------------------------------*/
function UBound(array)
{
   return (array.length - 1);
}



/*---------------------------------------------------------------------------------------
    RepeatString - Returns a String containing a repeating character string of the length 
                   specified.

    Parameters:
    Number = Length of the returned string. If number is less than 1, false is returned.
    Character = Character code specifying the character or string expression whose first 
                Character is used to build the return string. If character contains null, 
                false is returned. 

    Returns: String
  ---------------------------------------------------------------------------------------*/
function RepeatString(Number, Character) {

   var temp = '';

   if (Number < 1) return (false);

   if (Character.length == 0) return (false);

   if (Character.length > 1) Character = Character.charAt(0);

   for (var i = 0; i < Number; i++) {
      temp = temp + Character
   }

   return temp;
}



/*---------------------------------------------------------------------------------------
    Space - Returns a String containing the specified number of spaces.

    Parameters:
    Number = Length of the returned string. If number is less than 1, false is returned.

    Returns: String
  ---------------------------------------------------------------------------------------*/
function Space(Number) {
   return RepeatString(Number, " ");
}



/*---------------------------------------------------------------------------------------
    ReverseString - Returns a string in which the character order of a specified string is 
                    reversed.

    Parameters:
    Expression = The expression argument is the string whose characters are to be reversed. 
                 If expression is a zero-length string (""), a zero-length string is returned. 
                 If expression is null, false is returned.

    Returns: String
  ---------------------------------------------------------------------------------------*/
function ReverseString(Expression) {

   if (Expression == null) return (false);

   var dest = '';
   for (var i = (Expression.length - 1); i >= 0; i--)
      dest = dest + Expression.charAt(i);

   return dest;
}



/*---------------------------------------------------------------------------------------
    StrConv - Returns a String converted as specified in the Parameters Section.

    Parameters:
    String = String expression to be converted.
    Conversion = Number specifying the type of conversion to perform.
                 1 = TO UPPER CASE
                 2 = to lower case
                 3 = To Proper Case
                 If Conversion is null or not specified 1 is set as default.

    Returns: String
  ---------------------------------------------------------------------------------------*/
function StrConv(String, Conversion) {

   var index;
   var tmpStr;
   var tmpChar;
   var preString;
   var postString;
   var strlen;

   if (Conversion == null || Conversion.length == 0) Conversion = '1';

   if (Conversion != '1' && Conversion != '2' && Conversion != '3') Conversion = '1';

   if (Conversion == '1') return String.toUpperCase();

   if (Conversion == '2') return String.toLowerCase();

   //Proper Case
   tmpStr = String.toLowerCase();
   strLen = tmpStr.length;

   if (strLen > 0) {

      for (index = 0; index < strLen; index++) {

         if (index == 0) {
            tmpChar = tmpStr.substring(0, 1).toUpperCase();
            postString = tmpStr.substring(1, strLen);
            tmpStr = tmpChar + postString;
         } else {
            tmpChar = tmpStr.substring(index, index + 1);
            if (tmpChar == " " && index < (strLen - 1)) {
               tmpChar = tmpStr.substring(index + 1, index + 2).toUpperCase();
               preString = tmpStr.substring(0, index + 1);
               postString = tmpStr.substring(index + 2,strLen);
               tmpStr = preString + tmpChar + postString;
            }
         }
      }
   }

   return tmpStr;
}



/*---------------------------------------------------------------------------------------
    FormatNumber - Returns an expression formatted as a number.


    Parameters:
    Expression = Expression to be formatted.
    NumDigitsAfterDecimal = Numeric value indicating how many places to the right of the
                            decimal are displayed.

    Returns: String
  ---------------------------------------------------------------------------------------*/
function FormatNumber(Expression, NumDigitsAfterDecimal) {

   var iNumDecimals = NumDigitsAfterDecimal;
   var dbInVal = Expression;
   var bNegative = false;
   var iInVal = 0;
   var strInVal
   var strWhole = "", strDec = "";
   var strTemp = "", strOut = "";
   var iLen = 0;

   if (dbInVal < 0) {
      bNegative = true;
      dbInVal *= -1;
   }

   dbInVal = dbInVal * Math.pow(10, iNumDecimals)
   iInVal = parseInt(dbInVal);
   if ((dbInVal - iInVal) >= .5) {
      iInVal++;
   }

   strInVal = iInVal + "";
   strWhole = strInVal.substring(0, (strInVal.length - iNumDecimals));
   strDec = strInVal.substring((strInVal.length - iNumDecimals), strInVal.length);
   while (strDec.length < iNumDecimals) {
      strDec = "0" + strDec;
   }

   iLen = strWhole.length;
   if (iLen >= 3) {

      while (iLen > 0) {
         strTemp = strWhole.substring(iLen - 3, iLen);
         if (strTemp.length == 3) {
            strOut = "," + strTemp + strOut;
            iLen -= 3;
         } else {
            strOut = strTemp + strOut;
            iLen = 0;
         }
      }

      if (strOut.substring(0, 1) == ",") {
         strWhole = strOut.substring(1, strOut.length);
      } else {
         strWhole = strOut;
      }
   }

   if (bNegative) {
      return "-" + strWhole + "." + strDec;
   } else {
      return strWhole + "." + strDec;
   }
}




/*---------------------------------------------------------------------------------------
    FormatCurrency - Returns an expression formatted as a currency value using the currency 
                     symbol $.

    Parameters:
    Expression = Expression to be formatted.

    Returns: String
  ---------------------------------------------------------------------------------------*/
function FormatCurrency(Expression) {

   var iNumDecimals = 2;
   var dbInVal = Expression;
   var bNegative = false;
   var iInVal = 0;
   var strInVal
   var strWhole = "", strDec = "";
   var strTemp = "", strOut = "";
   var iLen = 0;

   if (dbInVal < 0) {
      bNegative = true;
      dbInVal *= -1;
   }

   dbInVal = dbInVal * Math.pow(10, iNumDecimals)
   iInVal = parseInt(dbInVal);
   if ((dbInVal - iInVal) >= .5) {
      iInVal++;
   }

   strInVal = iInVal + "";
   strWhole = strInVal.substring(0, (strInVal.length - iNumDecimals));
   strDec = strInVal.substring((strInVal.length - iNumDecimals), strInVal.length);
   while (strDec.length < iNumDecimals) {
      strDec = "0" + strDec;
   }

   iLen = strWhole.length;
   if (iLen >= 3) {
      while (iLen > 0) {
         strTemp = strWhole.substring(iLen - 3, iLen);
         if (strTemp.length == 3) {
            strOut = "," + strTemp + strOut;
            iLen -= 3;
         } else {
            strOut = strTemp + strOut;
            iLen = 0;
         }
      }

      if (strOut.substring(0, 1) == ",") {
         strWhole = strOut.substring(1, strOut.length);
      } else {
         strWhole = strOut;
      }
   }

   if (bNegative) {
      return "-$" + strWhole + "." + strDec;
   } else {
      return "$" + strWhole + "." + strDec;
   }
}



/*---------------------------------------------------------------------------------------
    FormatPercent - Returns an expression formatted as a percentage (multipled by 100) with 
                    a trailing % character.

    Parameters:
    Expression = Expression to be formatted.

    Returns: String
  ---------------------------------------------------------------------------------------*/
function FormatPercent(Expression, NumDigitsAfterDecimal) {

   var iNumDecimals = NumDigitsAfterDecimal;
   var dbInVal = Expression * 100;
   var bNegative = false;
   var iInVal = 0;
   var strInVal
   var strWhole = "", strDec = "";
   var strTemp = "", strOut = "";
   var iLen = 0;

   if (dbInVal < 0) {
      bNegative = true;
      dbInVal *= -1;
   }

   dbInVal = dbInVal * Math.pow(10, iNumDecimals)
   iInVal = parseInt(dbInVal);
   if ((dbInVal - iInVal) >= .5) {
      iInVal++;
   }

   strInVal = iInVal + "";
   strWhole = strInVal.substring(0, (strInVal.length - iNumDecimals));
   strDec = strInVal.substring((strInVal.length - iNumDecimals), strInVal.length);
   while (strDec.length < iNumDecimals) {
      strDec = "0" + strDec;
   }

   iLen = strWhole.length;
   if (iLen >= 3) {
      while (iLen > 0) {
         strTemp = strWhole.substring(iLen - 3, iLen);
         if (strTemp.length == 3) {
            strOut = "," + strTemp + strOut;
            iLen -= 3;
         } else {
            strOut = strTemp + strOut;
            iLen = 0;
         }
      }

      if (strOut.substring(0, 1) == ",") {
         strWhole = strOut.substring(1, strOut.length);
      } else {
         strWhole = strOut;
      }
   }

   if (bNegative) {
      return "-" + strWhole + "." + strDec + "%";
   } else {
      return strWhole + "." + strDec + "%";
   }
}



/*---------------------------------------------------------------------------------------
    FormatDateTime - Returns an expression formatted as a date or time.  If DateTime is null 
                     then false is returned.

    Parameters:
    DateTime = Date/Time expression to be formatted.
    FormatType = Numeric value that indicates the date/time format used. If omitted, 
                 GeneralDate is used

                 0 = Very Long Date/Time Format (Mon Jul 10, 12:02:30 am EDT 2000)
                 1 = Long Date/Time Format (Monday, July 10, 2000)
                 2 = Short Date (1/10/00)
                 3 = Long Time (4:20 PM)
                 4 = Military Time (14:43)

    Returns: String
  ---------------------------------------------------------------------------------------*/
function FormatDateTime(DateTime, FormatType) {

   if (DateTime == null) return (false);

   if (FormatType < 0) FormatType = 1;

   if (FormatType > 4) FormatType = 1;

   var strDate = new String(DateTime);

   if (strDate.toUpperCase() == "NOW") {
      var myDate = new Date();
      strDate = String(myDate);
   } else {
      var myDate = new Date(DateTime);
      strDate = String(myDate);
   }

   var Day = new String(strDate.substring(0, 3));
   if (Day == "Sun") Day = "Sunday";
   if (Day == "Mon") Day = "Monday";
   if (Day == "Tue") Day = "Tuesday";
   if (Day == "Wed") Day = "Wednesday";
   if (Day == "Thu") Day = "Thursday";
   if (Day == "Fri") Day = "Friday";
   if (Day == "Sat") Day = "Saturday";   

   var Month = new String(strDate.substring(4, 7)), MonthNumber = 0;
   if (Month == "Jan") { Month = "January"; MonthNumber = 1; }
   if (Month == "Feb") { Month = "February"; MonthNumber = 1; }
   if (Month == "Mar") { Month = "March"; MonthNumber = 1; }
   if (Month == "Apr") { Month = "April"; MonthNumber = 1; }
   if (Month == "May") { Month = "May"; MonthNumber = 1; }
   if (Month == "Jun") { Month = "June"; MonthNumber = 1; }
   if (Month == "Jul") { Month = "July"; MonthNumber = 1; }
   if (Month == "Aug") { Month = "August"; MonthNumber = 1; }
   if (Month == "Sep") { Month = "September"; MonthNumber = 1; }
   if (Month == "Oct") { Month = "October"; MonthNumber = 1; }
   if (Month == "Nov") { Month = "November"; MonthNumber = 1; }
   if (Month == "Dec") { Month = "December"; MonthNumber = 1; }

   var curPos = 11;
   var MonthDay = new String(strDate.substring(8, 10));
   if (MonthDay.charAt(1) == " ") {
      MonthDay = "0" + MonthDay.charAt(0);
      curPos--;
   }   

   var MilitaryTime = new String(strDate.substring(curPos, curPos + 5));
   var Year = new String(strDate.substring(strDate.length - 4, strDate.length));

   // Format Type decision time!
   if (FormatType == 1)
      strDate = Day + ", " + Month + " " + MonthDay + ", " + Year;
   else if (FormatType == 2)
      strDate = MonthNumber + "/" + MonthDay + "/" + Year.substring(2,4);
   else if (FormatType == 3)
   {
      var AMPM = MilitaryTime.substring(0,2) >= 12 && MilitaryTime.substring(0,2) != "24" ? " PM" : " AM";
      if (MilitaryTime.substring(0,2) > 12)
         strDate = (MilitaryTime.substring(0,2) - 12) + ":" + MilitaryTime.substring(3,MilitaryTime.length) + AMPM;
      else
      {
         if (MilitaryTime.substring(0,2) < 10)
            strDate = MilitaryTime.substring(1,MilitaryTime.length) + AMPM;
         else
         strDate = MilitaryTime + AMPM;
      }
   }   
   else if (FormatType == 4)
      strDate = MilitaryTime;

   return strDate;
}

