<!--
// i_utils.js
//
// Misc Functions (date, currency, etc)
//
// Copyright (c) 2001 Citiux Corporation - www.citiux.com
// By Milko Lima, MCP - milkoNOSPAM123@citiux.com
// May be used without express permission from the author and keeping this notice.


var DAY_SUNDAY = 0


function DateAdd( start, interval, number )
{
	// if 10/31 then and number += 1  b/c of weird error just for 10/31/2005
	if( start == "Sun Oct 30 00:00:00 EDT 2005" )
		number += 1
	
    // Create 3 error messages, 1 for each argument. 
    var startMsg = "Sorry the start parameter of the dateAdd function\n" +
			"must be a valid date format.\n\n" +
			"Please try again."
		
    var intervalMsg = "Sorry the dateAdd function only accepts\n" +
			"d, h, m OR s intervals.\n\n" +	// intervals are Days, Hours, Minutes, Seconds
			"Please try again."

    var numberMsg = "Sorry the number parameter of the dateAdd function\n" +
			"must be numeric.\n\n" +
			"Please try again."
		
    // get the milliseconds for this Date object. 
    var buffer = Date.parse( start )
	
    // check that the start parameter is a valid Date. 
    if( isNaN (buffer) )
    {
        alert( startMsg )
        return null
    }
	
    // check that an interval parameter was not numeric. 
    if( interval.charAt == 'undefined' )
    {
        // the user specified an incorrect interval, handle the error. 
        alert( intervalMsg )
        return null
    }

    // check that the number parameter is numeric. 
    if( isNaN ( number ) )
    {
        alert( numberMsg )
        return null
    }

    // what kind of add to do? 
    switch( interval.charAt(0) )
    {
        case 'd': case 'D': 
            number *= 24	// days to hours
            // fall through! 
        case 'h': case 'H':
            number *= 60	// hours to minutes
            // fall through! 
        case 'm': case 'M':
            number *= 60	// minutes to seconds
            // fall through! 
        case 's': case 'S':
            number *= 1000	// seconds to milliseconds
            break
        default:
			// If we get to here then the interval parameter
			// didn't meet the d,h,m,s criteria.  Handle
			// the error. 		
			alert( intervalMsg )
			return null
    }
    
    return new Date( buffer + number )
}


function y2k( year )
{
	return (year < 1000 ? year + 1900 : year)
}


function DateDiff_days( date2, date1 )
{
	var difference =
		Date.UTC(y2k(date1.getYear()),date1.getMonth(),date1.getDate(),0,0,0)
		- Date.UTC(y2k(date2.getYear()),date2.getMonth(),date2.getDate(),0,0,0)
    
    return difference/1000/60/60/24
}


function DateGet()
{
	var dteDate = new Date()
	
	return DateToShort( dteDate )	//(dteDate.getMonth() + 1) + "/" + dteDate.getDate() + "/" + dteDate.getYear()
}


function DateTimeGet()
{
	var dteDate = new Date()
	
	return (dteDate.getMonth() + 1) + "/" + dteDate.getDate() + "/" + dteDate.getYear() + " " + dteDate.getHours() + ":" + dteDate.getMinutes()
}


function DateToShort( dateParam )
{
	var date = new Date( dateParam );
	var d  = date.getDate();
	var day = (d < 10) ? '0' + d : d;
	var m = date.getMonth() + 1;
	var month = (m < 10) ? '0' + m : m;
	var yy = date.getYear();

	return month + "/" + day + "/" + yy
}


function FormatUSCurrency(theNumber)
{
  var isNegative = 0

  if( theNumber != "" || theNumber == 0 )	// Milko: added "0" b/c when =0, theNumber != "" is false !?
  {
    var workingNumber = theNumber + "" // Evaluate to a string

    if (workingNumber.charAt(0) == "-") { 
      isNegative = 1;
      workingNumber = workingNumber.substring(1, workingNumber.length)
    }

    var withoutChars = ""

    for (x=0; x<=((workingNumber.length)-1); x++) {
      thisChar = workingNumber.charAt(x)
      charAsNum = parseFloat(thisChar)

      if ( ((thisChar >= "0") & (thisChar <= "9")) || (thisChar == ".")  ) { 
	withoutChars += workingNumber.charAt(x) 
      }
    }
    workingNumber = withoutChars
    decimalPoint = workingNumber.indexOf(".")

    if (decimalPoint == -1) {
      dollarValue = workingNumber
      centsValue = "00"
      } else if (decimalPoint == 0) {
      dollarValue = "0"
      centsValue = workingNumber.substring(decimalPoint + 1, workingNumber.length)
    } else {
        dollarValue = workingNumber.substring(0, decimalPoint)
        if (decimalPoint == (workingNumber.length - 1)) {
	  centsValue = "00";
        } else {
          centsValue = workingNumber.substring(decimalPoint + 1, workingNumber.length);
          centsValue += "0";
          centsValue = centsValue.charAt(0) + centsValue.charAt(1)
        }
    }

    var theString = dollarValue;
    var totalCommas = Math.floor((theString.length - 1) / 3)
    var dollarAmt = ""
    x=dollarValue.length
    position = 0

    while (x > 0) {
	x = x - 1
        thisChar = dollarValue.charAt(x)
	rounded = Math.round(position/3)

	if ( (position/3 == rounded ) & (position != 0) ) {
           dollarAmt = "," + dollarAmt
	}
        dollarAmt = thisChar +  dollarAmt
	position = position + 1
    }

    if (isNegative)
    {
      //theString = "$" + dollarAmt + "." + centsValue
      theString = "($" + dollarAmt + "." + centsValue + ")"
    } else { 
      theString = "$" + dollarAmt + "." + centsValue
    }
    return (theString);
  }
  else
	return("");
}


function iif( cond, truePart, falsePart )
{
	if( cond )
		return truePart;
	else
		return falsePart;
}


function NullToEmpty( value )
{
	if( value == null || value == "undefined" )
		return ""
	else
		return value
}


function NumberWithCommas(intNumber, intDecimals){ 
	// To convert a numeric value in format with commas and decimals
	// Ex: 1234.56 = 1,234.56 or 1234 = 1,234
	var intTmp = new Number(intNumber);
	var strNewNumber = new String();
	var strFormatNumber = new String();
	var intInd, intCount, strCurCar;

	//Put decimals if necesary
	intTmp = intTmp.toFixed(intDecimals);
	strNewNumber = intTmp;
	
	with( strNewNumber )
	{
		if ( intTmp < 1000 )
			// Commas are not used, number is <= 999
			strFormatNumber = strNewNumber
		else{
			// Commas are required, initialize count for item (if 3, comma is required)
			if ( intDecimals > 0 ) 
				intCount = -1;
			else
				intCount = 0;
					
			for ( intInd = (length - 1); (intInd >= 0 ); --intInd)
			{
				//Get item 
				strCurCar = substr(intInd, 1);
				strFormatNumber = strCurCar + strFormatNumber;

				if ( strCurCar == "." ) 
					//Initialize counter
					intCount = 0
				else {
					if ( intCount != -1 )  // if -1 is decimal part
						intCount++;
						
					if ( intCount == 3 )
					{
						//Put 'comma'
						intCount = 0;
						if (intInd != 0 )
							// Don't insert comma if is the first item
							strFormatNumber = "," + strFormatNumber
					}
				}
			}
		}
	}
	
	return strFormatNumber
}


function NumberClean( number )
{ 
	var strNewNumber = new String( number )
	strNoComma = strNewNumber.replace( ",", "" )
	return parseFloat( strNoComma.replace( "$", "") )
}


function ParseFloatMy( str )
{
	var n
	
	if( !str || str == "" || isNaN(str) )
		n = 0
	else
		n = parseFloat( str )
		
	return n
}


function ParseIntMy( str )
{
	var n
	
	if( !str || str == "" || isNaN(str) )
		n = 0
	else
		n = parseInt( str )
		
	return n
}


/*function round( number, X )
{
	// rounds number to X decimal places, defaults to 2
	X = (!X ? 2 : X)
	return Math.round( number * Math.pow( 10, X) ) / Math.pow( 10, X )
}*/


function round( original_number, decimals )
{
	decimals = (!decimals ? 2 : decimals)
    var result1 = original_number * Math.pow(10, decimals)
    var result2 = Math.round(result1)
    var result3 = result2 / Math.pow(10, decimals)
    return pad_with_zeros( result3, decimals )
}


function pad_with_zeros(rounded_value, decimal_places)
{
    // Convert the number to a string
    var value_string = rounded_value.toString()
    
    // Locate the decimal point
    var decimal_location = value_string.indexOf(".")

    // Is there a decimal point?
    if( decimal_location == -1 )
    {
        // If no, then all decimal places will be padded with 0s
        decimal_part_length = 0
        
        // If decimal_places is greater than zero, tack on a decimal point
        value_string += decimal_places > 0 ? "." : ""
    }
    else
    {
        // If yes, then only the extra decimal places will be padded with 0s
        decimal_part_length = value_string.length - decimal_location - 1
    }
    
    // Calculate the number of decimal places that need to be padded with 0s
    var pad_total = decimal_places - decimal_part_length
    
    if( pad_total > 0 )
    {
        // Pad the string with 0s
        for( var counter = 1; counter <= pad_total; counter++ )
            value_string += "0"
	}
    
    return value_string
}


function Trim( str )
{
	// from: http://blog.stevenlevithan.com/archives/faster-trim-javascript
	return RTrim( LTrim( str) )
}


function LTrim( str )
{
	return str.replace(/^\s\s*/, '');
}


function RTrim( str )
{
	return str.replace(/\s\s*$/, '');
}


function TrimAll( data )
{
	return (data == null) ? false : data.replace(/(\s+)/g,"")
}


function ReplaceSubstring( inputString, fromString, toString )
{
	// From: http://www.breakingpar.com/bkp/home.nsf/Doc?OpenNavigator&45A5696524D222C387256AFB0013D850
   // Goes through the inputString and replaces every occurrence of fromString with toString
   var temp = inputString;
   if (fromString == "") {
      return inputString;
   }
   if (toString.indexOf(fromString) == -1) { // If the string being replaced is not a part of the replacement string (normal situation)
      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;
      }
   } else { // String being replaced is part of replacement string (like "+" being replaced with "++") - prevent an infinite loop
      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
   return temp; // Send the updated string back to the user
} // Ends the "replaceSubstring" function
//-->
