//<SCRIPT>
// this file contains common JSCRIPT functions
// String functions
//
String.prototype.trim = String_trim;
function String_trim() {
	//
	// trims spaces from both ends of a string
	if(this.length > 0) {
		var start = 0;
		while(((this.charAt(start)).valueOf() == " ".valueOf()) && (start < this.length)) {
			start++;
		}
		if(start >= this.length) {
			return ""; //string contains spaces only.
		}
		var endstr = this.length - 1;
		while(((this.charAt(endstr)).valueOf() == " ".valueOf()) && (endstr >= 0)) {
			endstr--;
		}
		return this.substring(start,endstr+1);
	}
	else {
	  return "" + this;
	}
}
//
// Currency functions
//
function toCurrency(strSrc) {
	// returns the input string in currency format
	// returns false if not a currency or if it overflows
	// the SQL Server money datatype
	// 10/5/99, perkins
	//
	// Strip commas and dollar signs
	var re = new RegExp('[,$]', 'ig');
	theMoney = ('' + strSrc).replace(re, '').trim();
	// Convert parens format for negative values to - format
	if ((theMoney.charAt(0) == '(') && (theMoney.charAt(theMoney.length - 1) == ')')) {
		theMoney = '-' + theMoney.substring(1, theMoney.length - 1);
	}
	// Exclude the blank string and scientific notation
	if (theMoney == '' || theMoney.toUpperCase().indexOf('E') > -1) {
		return false;
	}
	// 920000000000000 ~ the limit of the currency datatype in SQL server
	if (isNaN(theMoney) || theMoney > 920000000000000) {
		return false;
	}
	// Format the number
	var thePrefix = '$';
	var theSuffix = '';
	if (theMoney.charAt(0) == '-') {
		thePrefix = '(' + thePrefix;
		theSuffix = theSuffix + ')';
		theMoney = theMoney.substring(1, theMoney.length);
	}
	theMoney = '' + (Math.round(100*parseFloat(theMoney))/100)
	var theCents = '0' + (Math.round((parseFloat(theMoney) % 1)*100));
	theCents = '.' + theCents.substring(theCents.length - 2, theCents.length);
	var theDollars = '' + (Math.floor(parseFloat(theMoney)));
	// Add commas
	var theIdx = theDollars.length - 3;
	while (theIdx > 0) {
		theDollars = theDollars.substring(0, theIdx) + ',' + theDollars.substring(theIdx, theDollars.length);
		theIdx += -3;
	}
	// put it all together
	return thePrefix + theDollars + theCents + theSuffix;
}

function fromCurrency(strSrc) {
	// Returns: A Number object which could be the numerical
	// representation of a string in currency format. 
	// OR false if this function doesn't recognize the
	// string as being in a currency format.
	// 6/13/00, jwhite
	//
	// Strip commas and dollar signs
	var re = new RegExp('[,$]', 'ig');
	var strMoney,numMoney;
	strMoney = ('' + strSrc).replace(re, '').trim();
	// Convert parens format for negative values to - format
	if ((strMoney.charAt(0) == '(') && (strMoney.charAt(strMoney.length - 1) == ')')) {
		strMoney = '-' + strMoney.substring(1, strMoney.length - 1);
	}
	// Exclude the blank string and scientific notation
	if (strMoney == '' || strMoney.toUpperCase().indexOf('E') > -1) {
		return false;
	}
	// 920000000000000 ~ the limit of the currency datatype in SQL server
	if (isNaN(strMoney) || strMoney > 920000000000000) {
		return false;
	} 
	numMoney = Number(strMoney);
	return Number(strMoney);
}

function formatAsCurrency(Cur,type) {
	// Format a number to a Dollar format
	// type=0 : Format as TEXT if negitive, ('' == '')
	// type=1 : Format as HTML if negitive, ('' == '')
	// type=2 : Format as HTML if negitive, ('' == '$0.00')
	// type=4 : Format as TEXT if negitive, ('' == '$0.00')

	var myCur=String();
	try{
		myCur=String(Cur)
	}
	catch (e) {}	
    myCur=myCur.trim();
    if(myCur == '') {
		if(type == 2 || type == 4)
			return '$0.00';
		else
			return '';
	}
 	if (type == 0 || type == 4) {
		return(numToDollars(strToFloatMax(myCur,99999999)));
	} else {
		if(strToFloatMax(myCur,99999999) < 0) {
			return('<SPAN STYLE="color:red;">' + numToDollars(strToFloatMax(myCur,99999999)) + '</SPAN>');
		} else {
			return(numToDollars(strToFloatMax(myCur,99999999)));
		}
	}
}

// return true if the value val is found in the array arr
function inArray(arr, val)
{
	for(var i = 0; i < arr.length; i++)
		if(arr[i] == val) return true;
	return false;
}

// associated with an onClick(this) event, do a POST, setting the DisplayAction
//  to the value of the button (DisplayAction needs to be defined as a hidden form
//  variable)
function doButton(objButt)
{
	document.all.DisplayAction.value = objButt.value;
	document.all.thisForm.submit();
}

// BrowserCheck Object
// provides most commonly needed browser checking variables
// 19990326

// Copyright (C) 1999 Dan Steinman
// Distributed under the terms of the GNU Library General Public License
// Available at http://www.dansteinman.com/dynduo/

function BrowserCheck() {
	var b = navigator.appName
	if (b=="Netscape") this.b = "ns"
	else if (b=="Microsoft Internet Explorer") this.b = "ie"
	else this.b = b
	this.v = parseInt(navigator.appVersion,10)
	this.ns = (this.b=="ns" && this.v>=4)
	this.ns4 = (this.b=="ns" && this.v==4)
	this.ns5 = (this.b=="ns" && this.v==5)
	this.ie = (this.b=="ie" && this.v>=4)
	this.ie4 = (navigator.userAgent.indexOf('MSIE 4')>0)
	this.ie5 = (navigator.userAgent.indexOf('MSIE 5')>0)
	if (this.ie5) this.v = 5
	this.min = (this.ns||this.ie)
}

// automatically create the "is" object
is = new BrowserCheck()
if(is.ns) {
	alert("Please use IE4.0 or higher to follow this link");
	history.back();
}


//------------------------------------------------

function isOverflow(n)
{
	return (isNaN(n) || n == Number.POSITIVE_INFINITY || n == Number.NEGATIVE_INFINITY);
}

function strToFloatEx(s)
{
	var n = parseFloat(removeNonNumerics(s));
	if (isNaN(n)) n=0;
	return n;
}

function strToFloat(s)
{
	var n = strToFloatEx(s);
	return n;
}
function strToFloatMax(s, m)
{
	var x=strToFloat(s);
	if (x>m) x=m;
	return x;
}

function strToIntEx(s)
{
	var n=parseInt(removeNonNumerics(s),10)
	if (isNaN(n)) n=0;
	return n;
}

function strToInt(s)
{
	var n=strToIntEx(s);
	if (n<0) n=0;
	return n;
}

function strToIntMax(s, m)
{
	var x=strToIntEx(s);
	if (x>m) x=m;
	return x;
}

function isCharValidNumeric(c)	// check the input character to see if it's a valid numeric
{
	return (c == '.' || c == '-' || c == ',' ||(c >= '0' && c <= '9'))
}

function removeNonNumerics(s)
{
	if (s == null) return null
	s = '' + s;
	var t = '';
	var isLeadingZero = true;
	if (s.charAt(0)=='(' && s.charAt(s.length-1)==')'){
		s='-' + s.substr(1,s.length-2);}
	if (s.charAt(0)=='$')
		s=s.substr(1,s.length-1)
	else {
		if (s.substr(0,2)=='-$')
			s='-'+ s.substr(2,s.length-2)}
	var sLen=s.length;
	for (var i = 0; i < sLen; i++){
		var c = s.charAt(i);
		if (isCharValidNumeric(c))
		{
			if (isLeadingZero && (c == '0')){
				continue;  // remove leading zeros to avoid javascript octal conversion
				t += c;
				}
			else{
				if (c!=','){
					isLeadingZero=false;
					t += c;
					}
				}
		}
		else{
			t=0;
			break;}
	}
	return t;
}


function addCommas(t)
{
	var s='';
	var len = t.length;
	var end = len-1;
	for (var i=0; i < len; i++)
	{
		c = t.charAt(end-i);
		s = c + ((i>2 && i % 3 == 0) ? ',' : '') + s;
	}
	return s;
}

function _numToUnits(n, units_prefix, decimal_places, units_suffix){
	if (isOverflow(n)) return '<i>numeric overflow</i>';
	var isNegative = n < 0;
	var d = decimal_places;
	// get precision value
	var x = Math.abs(Math.round (n * Math.pow(10, decimal_places)));

	var s = '';
	// if zero, return default string
	if (x == 0)
	{
		s = '0';
		if (d > 0)
		{
			s += '.';
			for (var i=0; i < d; i++) s += '0';
		}
		s = units_prefix + s + units_suffix;
		return s;
	}

	// create the number string
	if (d == 0)
	{
		var tmp = '' + x;
		s = addCommas(tmp);
	}
	else
	{
		var leftTmp = '' + x;
		var rightTmp = '' + x;
		var len = leftTmp.length;
		
		for (var i=0; i < d+1-len; i++)
		{
			leftTmp = '0' + leftTmp;
			rightTmp = '0' + rightTmp;
		}

		len=leftTmp.length;
		var decimalSplit=len - d;

		var leftStr=addCommas(leftTmp.substring(0, decimalSplit));
		var rightStr=rightTmp.substring(decimalSplit, len);

		s = leftStr + '.' + rightStr
	}
	s=units_prefix + s + units_suffix;	
	if (isNegative)	
		s = '(' + s + ')';

	return s;
}

function numToUnits(n, units) {	return _numToUnits(n, '', 0, ' ' + units); }
function numToPercent(n) { return _numToUnits(n, '', 3, ' %'); }
function numToDollars(n) { return _numToUnits(n, '$', 2, ''); }
function intToDollarStr(n) { return numToDollars(n); } 
//--------------------------------------------

function getCur(item,type){
	var myCur=''+item.value;
	myCur=myCur.trim();
	if (myCur == '')
		return;
	if (type == 0)
		item.value=numToDollars(strToFloatMax(myCur,99999999));
	else
		item.value=numToUnits(strToIntMax(myCur,999999),'');
	return true
}

function getDate(item,type) {
// checks if date passed is in valid mm/dd/yyyy or m/dd/yyyy or m/d/yyyy or mm/d/yyyy format
    var myDate=''+ item.value;
	myDate=myDate.trim();
	if (myDate!=""){
		var monthpos=(myDate.indexOf("/",1));
		if (type==0){
			if (monthpos>0) {
           		var month  = ''+ myDate.substring(0,monthpos);
				month=month.trim();
				var datepos=myDate.indexOf("/",monthpos+1);
				if (datepos>0){
					var date = '' + myDate.substring(monthpos+1,datepos);
					date=date.trim();
					var year  = '' + myDate.substring(datepos+1,myDate.length);
					year=year.trim();
					var test = new Date(year,month-1,date);
					if (year.length!=4){
						if (year.length!=2){
							alert('Invalid Date!!!');
							item.value="";
							return false;
							}
						}
					if ((month-1 == test.getMonth()) && (date == test.getDate())) {
						q=0;
						}
					else {                
						alert('Invalid Date!!!');
						item.value="";
						return false;            
						}
					}
				else{
					alert('Invalid Date!!!');
					item.value="";
					return false;
					}
				}
			else {       
				alert('Invalid Date!!!');
				item.value="";
				return false;   
				}
			}
		else{
			if (type==1){
				if (monthpos>0) {
           			var month  = myDate.substring(0,monthpos);
					var datepos=myDate.indexOf("/",monthpos+1);
					if (datepos>0){
						var date = myDate.substring(monthpos+1,datepos);
						date=date.trim();
						var year  = myDate.substring(datepos+1,myDate.length);
						year=year.trim();
						var test = new Date(year,month-1,date);
						if (year.length!=4){
							alert('Invalid Date!!!');
							item.value="";
							return false;
							}
						if ((month-1 == test.getMonth()) && (date == test.getDate())) {
							q=0;
							}
						else {                
							alert('Invalid Date!!!');
							item.value="";
							return false;            
							}
						}
					else{
						alert('Invalid Date!!!');
						item.value="";
						return false;
						}
					}
				else {       
					alert('Invalid Date!!!');
					item.value="";
					return false;   
				}
			}
		}
	item.value=month + '/' + date +'/' + year;
	}
	return true
}
// construct an object describing an item in a favorite list
function FavListItem(label,isPartOfItemLabel, isEditable)
{
	this.label = label;
	this.isPartOfItemLabel = isPartOfItemLabel;
	this.isEditable = isEditable;
}

function printWindow()
{
	window.print();
	window.close();
}

function showPrintAlert()
{
	alert("Please print this window or close it.");
}

//this function sets the selected property of an option item 
//selection object by checking value of the option with optValue; 
function selectOption(selectObj,optValue)
{
 var selectObjLen=selectObj.length;
 for(i=0;i<selectObjLen;i++) //country
  if(selectObj.options[i].value == (new String(optValue)).valueOf())
  {
    //selectObj.options[i].selected = true; //works in explores
    selectObj.selectedIndex = i; //for netscape.
    break;
    }                 
}

//this function sets the selected property of an option item 
//selection object by checking text of the option with optText; 
function selectOptionByText(selectObj,optText)
{
 var selectObjLen=selectObj.length;
 for(i=0;i<selectObjLen;i++) //country
  if(selectObj.options[i].text == optText)
  {
    selectObj.selectedIndex = i; //for netscape.
    break;
    }                 
                    
}

//this function logout the user because of an error in the javaScript
function errorLogout(errorAt, e)
{
	alert('Your session may have timed out, please re-login and try again.\n\nIf the problem persists, please contact technical support.\n\nLocation: ' + errorAt +'\nError: ' + e.description);
	parent.location.replace(location.href.slice(0, location.href.indexOf('/', location.href.indexOf('/', 7) + 1) + 1) + 'logout.asp');
}
//</SCRIPT>