/****************************************************
Checks to see if a bit is present within a bit mask
*/
function IsBitInBitMask(intBit, intBitMask)
{
	if ((intBit & intBitMask) == intBit)
	{
		return true;
	}
	else
	{
		return false;
	}
}

/****************************************************
This function converts a UK format date/time string into a Universal Coordinated Time (UTC).
*/
function setUKUTC(szDate)
{
	var nHours = 0;
	var nMinutes = 0;
    var szSeparator = szDate.substring(2,3);		//find date separator
    var arrayDate = szDate.split(szSeparator);		//split date into day, month, year
	var nDay = parseInt(arrayDate[0], 10);
	var nMonth = parseInt(arrayDate[1], 10) - 1;	// zero based! (why oh why!?!?)
	var nYear = 2000 + parseInt(arrayDate[2], 10);
	// optionally may have [, hours[, minutes]]
	if (szDate.length > 8) {
		var szTime = szDate.substr(9);
		szSeparator = szTime.substring(2,3);		
		var arrayTime = szTime.split(szSeparator);
		nHours = parseInt(arrayTime[0], 10);
		nMinutes = parseInt(arrayTime[1], 10);
	}
	//var dt = new Date(nYear, nMonth, nDay, nHours, nMinutes);
	dt = Date.UTC(nYear, nMonth, nDay, nHours, nMinutes);
	return dt;
}

/****************************************************
Compare dates
The return value of this function indicates the numeric relation of dt1 to dt2.
Value	Relationship of dt1 to dt2 
< 0		dt1 less than dt2 
0		dt1 identical to dt2 
> 0		dt1 greater than dt2 
*/
function datecmp(szDate1, szDate2)
{
	dt1 = setUKUTC(szDate1);
	dt2 = setUKUTC(szDate2);
	if (dt1 < dt2)
		return -1;
	if (dt1 == dt2)
		return 0;
	if (dt1 > dt2)
		return 1;
}

function datediff(szDate1, szDate2)
{
	var d, r, t1, t2, t3;
	var MinMilli = 1000 * 60
	var HrMilli = MinMilli * 60
	var DyMilli = HrMilli * 24
	t1 = setUKUTC(szDate1);
	t2 = setUKUTC(szDate2);
	if (t2 >= t1) 
		t3 = t2 - t1;
	else
		t3 = t1 - t2;
	r = Math.round(t3 / DyMilli);
	return(r);	//absolute difference	
}


/***********************************************************************************************************************************
 CUSTOM DATE FUNCTIONS WRITTEN BY Dest@pobox.com
	FormatDate()-  AUTOINSERTS the /'s IN A DATE
	CheckDate()- Validates Date Entered is a Valid Date

	COPY AND PASTE THE FOLLOWING INTO YOUR INPUT FIELD AND CHANGE TO APPROPRIATE FRAME LOCATION (ie: parent. or self.) :
	onchange="CheckDate(this)" onkeydown="FormatDate(this, window.event.keyCode,'down')" onkeyup="FormatDate(this, window.event.keyCode,'up')"
***********************************************************************************************************************************/
function FormatDate(i, delKey,direction) {
  if (i.value.length < 8) {
  	if (delKey!=9) { //tab
	  	if(delKey!=8 && delKey!=46 && delKey!=16 &&  !(delKey>36 && delKey<41)){ //if the delete, backspace, shift, are not the keys that caused the keyup event.
  			var fieldLen = i.value.length
   			if ((delKey >= 48 && delKey <= 57) || (delKey >= 96 && delKey <=105)) {
   				if (fieldLen == 2 || fieldLen == 5) {
      				i.value = i.value + "/";
		     	}
   			} else {
   				if (direction == "up") {
     				if (i.value.length == 0) {
      					i.value = ""
	     			} else {
		      			i.value = i.value.substring(0,i.value.length-1)
	   				}
    			}
	 		}
  			i.focus()
	  	}
 	} else {
 		if (direction == "down") {
	 		//CheckDate(i);
  		}
  	}
 }
}


function FormatTime(i, delKey,direction) {
  if (i.value.length < 5) {
  	if (delKey!=9) { //tab
	  	if(delKey!=8 && delKey!=46 && delKey!=16 &&  !(delKey>36 && delKey<41)){ //if the delete, backspace, shift, are not the keys that caused the keyup event.
  			var fieldLen = i.value.length
   			if ((delKey >= 48 && delKey <= 57) || (delKey >= 96 && delKey <=105)) {
   				if (fieldLen == 2 || fieldLen == 5) {
      				i.value = i.value + ":";
		     	}
   			} else {
   				if (direction == "up") {
     				if (i.value.length == 0) {
      					i.value = ""
	     			} else {
		      			i.value = i.value.substring(0,i.value.length-1)
	   				}
    			}
	 		}
  			i.focus()
	  	}
 	} else {
 		if (direction == "down") {
	 		//CheckDate(i)
  		}
  	}
 }
}

function CheckDate(THISDATE) {

	if (!validateDate(THISDATE.value) && THISDATE.value != "") {
		// alert user
		alert("Date is invalid.");
		THISDATE.select();
		THISDATE.focus();
		return false;		
	}
	
}

function CheckTime(THISDATE) {

	if (!validateTime(THISDATE.value) && THISDATE.value != "") {
		// alert user
		alert("Time is invalid.");
		THISDATE.select();
		THISDATE.focus();
		return false;		
	}
	
}

function CheckDateNotBeforeToday(objDate)
{
//Note: Assumes that date has already been validated via CheckDate or other method!
	var dtCheckDate = new Date(UKtoUSDate(c2DigitYearTo4DigitYear(objDate.value)));
	var dtToday = new Date(); //Today's date
	dtToday.setHours(0, 0, 0, 0);

	//Make sure date entered is not before todays date
	if (dtCheckDate < dtToday)
	{
		alert("Date is In the past.");
		objDate.select();
		objDate.focus();
		return false;
	}
}

function FormatDateForComparison(strDate)
{
	var myArray = strDate.split('/');
	var strDateD	= myArray[0];
	var strDateM = myArray[1];
	var strDateY = myArray[2];
	var dtmDateTime = strDateM + '/' + strDateD + '/20' + strDateY;
	var dtmDateTime = new Date(dtmDateTime);
	return dtmDateTime;
}

function CheckStartDate(objDateStart, objEndDate)
{
/*
Performs the following functions:
	1) Checks Start Date is valid
	2) Checks Start Date is after today's date
	3) Ensures Start Date is before End Date
*/
	var blnGoodDate = CheckDate(objDateStart);
	
	//Do standard date check first, only doing other checks if favorable result
	if (blnGoodDate != false)
	{
		//Make sure date entered is not before todays date
		blnGoodDate = CheckDateNotBeforeToday(objDateStart)
	}
	
	//If no problems then copy Start Date into End Date if Start Date > End Date
	if (blnGoodDate != false)
	{
		//Check End Date is present
		if (validateDate(objEndDate.value) && objEndDate.value != "")
		{
			//Compare dates
			var dtStartDate = new Date(UKtoUSDate(c2DigitYearTo4DigitYear(objDateStart.value)));
			var dtEndDate = new Date(UKtoUSDate(c2DigitYearTo4DigitYear(objEndDate.value)));
			if (dtStartDate > dtEndDate)
			{
				//Replace end date
				objEndDate.value = objDateStart.value;
			}
		}
	}
	return blnGoodDate
}

function CheckEndDate(objEndDate)
{
/*
Performs the following functions:
	1) Checks End Date is valid
	2) Checks End Date is after today's date
*/
	var blnGoodDate = CheckDate(objEndDate);
	
	//Do standard date check first, only doing other checks if favorable result
	if (blnGoodDate != false)
	{
		//Make sure date entered is not before todays date
		blnGoodDate = CheckDateNotBeforeToday(objEndDate)
	}
}


function InStrCount(strSearch, charSearchFor)
{
	var intCount = 0;

	for (i=0; i < Len(strSearch); i++)
	{
	    if (charSearchFor == Mid(strSearch, i, 1))
	    {
			intCount++;
	    }
	}
	
	return intCount;
}


function Mid(str, start, len)
/***
        IN: str - the string we are LEFTing
            start - our string's starting position (0 based!!)
            len - how many characters from start we want to get

        RETVAL: The substring from start to 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);
}

function Len(str)
/***
        IN: str - the string whose length we are interested in

        RETVAL: The number of characters in the string
***/
{  return String(str).length;  }



function InStr(strSearch, charSearchFor)
/*
InStr(strSearch, charSearchFor) : Returns the first location a substring (SearchForStr)
                           was found in the string str.  (If the character is not
                           found, -1 is returned.)
                           
Requires use of:
	Mid function
	Len function
*/
{
	for (i=0; i < Len(strSearch); i++)
	{
	    if (charSearchFor == Mid(strSearch, i, 1))
	    {
			return i;
	    }
	}
	return -1;
}


function Right(str, n)
/***
        IN: str - the string we are RIGHTing
            n - the number of characters we want to return

        RETVAL: n characters from the right side of the string
***/
{
        if (n <= 0)     // Invalid bound, return blank string
           return "";
        else if (n > String(str).length)   // Invalid bound, return
           return str;                     // entire string
        else { // Valid bound, return appropriate substring
           var iLen = String(str).length;
           return String(str).substring(iLen, iLen - n);
        }
}


function Left(str, n)
/***
        IN: str - the string we are LEFTing
            n - the number of characters we want to return

        RETVAL: n characters from the left side of the string
***/
{
        if (n <= 0)     // Invalid bound, return blank string
                return "";
        else if (n > String(str).length)   // Invalid bound, return
                return str;                // entire string
        else // Valid bound, return appropriate substring
                return String(str).substring(0,n);
}

function LTrim(str) {
	//Match spaces at beginning of text and replace with a null string
	return str.replace(/^\s+/,'');
}

function RTrim(str) {
	//Match spaces at end of text and replace with a null string
	return str.replace(/\s+$/,'');
}

function Trim(str) {
	//Match spaces at beginning and end of text and replace
	//with null strings
	return str.replace(/^\s+/,'').replace(/\s+$/,'');
}


function FormatDateTime(datetime, FormatType)
/*
	 FomatType takes the following values
		1 - General Date = Friday, October 30, 1998
		2 - Typical Date = 10/30/98
		3 - Standard Time = 6:31 PM
		4 - Military Time = 18:31
*/
{
	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);
	}


	// Get the date variable parts
	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 = 2; }
	if (Month == "Mar") { Month = "March"; MonthNumber = 3; }
	if (Month == "Apr") { Month = "April"; MonthNumber = 4; }
	if (Month == "May") { Month = "May"; MonthNumber = 5; }
	if (Month == "Jun") { Month = "June"; MonthNumber = 6; }
	if (Month == "Jul") { Month = "July"; MonthNumber = 7; }
	if (Month == "Aug") { Month = "August"; MonthNumber = 8; }
	if (Month == "Sep") { Month = "September"; MonthNumber = 9; }
	if (Month == "Oct") { Month = "October"; MonthNumber = 10; }
	if (Month == "Nov") { Month = "November"; MonthNumber = 11; }
	if (Month == "Dec") { Month = "December"; MonthNumber = 12; }
	
	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));	
	
	document.write(strDate + "");	

	// 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;
}


function FormatNumber(num,decimalNum,bolLeadingZero,bolParens,bolCommas)
/**********************************************************************
	IN:
		NUM - the number to format
		decimalNum - the number of decimal places to format the number to
		bolLeadingZero - true / false - display a leading zero for
										numbers between -1 and 1
		bolParens - true / false - use parenthesis around negative numbers
		bolCommas - put commas as number separators.
 
	RETVAL:
		The formatted number!
 **********************************************************************/
{ 
        if (isNaN(parseInt(num))) return "NaN";

	var tmpNum = num;
	var iSign = num < 0 ? -1 : 1;		// Get sign of number
	
	// Adjust number so only the specified number of numbers after
	// the decimal point are shown.
	tmpNum *= Math.pow(10,decimalNum);
	tmpNum = Math.round(Math.abs(tmpNum))
	tmpNum /= Math.pow(10,decimalNum);
	tmpNum *= iSign;					// Readjust for sign
	
	
	// Create a string object to do our formatting on
	var tmpNumStr = new String(tmpNum);

	// See if we need to strip out the leading zero or not.
	if (!bolLeadingZero && num < 1 && num > -1 && num != 0)
		if (num > 0)
			tmpNumStr = tmpNumStr.substring(1,tmpNumStr.length);
		else
			tmpNumStr = "-" + tmpNumStr.substring(2,tmpNumStr.length);
		
	// See if we need to put in the commas
	if (bolCommas && (num >= 1000 || num <= -1000)) {
		var iStart = tmpNumStr.indexOf(".");
		if (iStart < 0)
			iStart = tmpNumStr.length;

		iStart -= 3;
		while (iStart >= 1) {
			tmpNumStr = tmpNumStr.substring(0,iStart) + "," + tmpNumStr.substring(iStart,tmpNumStr.length)
			iStart -= 3;
		}		
	}

	// See if we need to use parenthesis
	if (bolParens && num < 0)
		tmpNumStr = "(" + tmpNumStr.substring(1,tmpNumStr.length) + ")";

	return tmpNumStr;		// Return our formatted string!
}




function FormatPercent(num,decimalNum,bolLeadingZero,bolParens,bolCommas)
/**********************************************************************
	IN:
		NUM - the number to format
		decimalNum - the number of decimal places to format the number to
		bolLeadingZero - true / false - display a leading zero for
										numbers between -1 and 1
		bolParens - true / false - use parenthesis around negative numbers
		bolCommas - put commas as number separators.										
 
	RETVAL:
		The formatted number!		
 **********************************************************************/
{
	var tmpStr = new String(FormatNumber(num*100,decimalNum,bolLeadingZero,bolParens,bolCommas));

	if (tmpStr.indexOf(")") != -1) {
		// We know we have a negative number, so place '%' inside of ')'
		tmpStr = tmpStr.substring(0,tmpStr.length - 1) + "%)";
		return tmpStr;
	}
	else
		return tmpStr + "%";			// Return formatted string!
}



function FormatCurrency(num,decimalNum,bolLeadingZero,bolParens,bolCommas)
/**********************************************************************
	IN:
		NUM - the number to format
		decimalNum - the number of decimal places to format the number to
		bolLeadingZero - true / false - display a leading zero for
										numbers between -1 and 1
		bolParens - true / false - use parenthesis around negative numbers
		bolCommas - put commas as number separators.										
 
	RETVAL:
		The formatted number!		
 **********************************************************************/
{
	var tmpStr = new String(FormatNumber(num,decimalNum,bolLeadingZero,bolParens,bolCommas));

	if (tmpStr.indexOf("(") != -1 || tmpStr.indexOf("-") != -1) {
		// We know we have a negative number, so place '$' inside of '(' / after '-'
		if (tmpStr.charAt(0) == "(")
			tmpStr = "($"  + tmpStr.substring(1,tmpStr.length);
		else if (tmpStr.charAt(0) == "-")
			tmpStr = "-$" + tmpStr.substring(1,tmpStr.length);
			
		return tmpStr;
	}
	else
		return "$" + tmpStr;		// Return formatted string!
}


// sList - a string to which the item is going to be added to
// sItem - a string which holds the item to be added
// returned - a string with the item appended at the end
// Note: In the list all items are enclosed with square brackets eg (455)(444)
function AddItemStringList(sList, sItem)
{
	sList += "(" + sItem + ")";
	return sList;
}

// sList - a string to which the item is going to be removed from.
// sItem - a string which holds the item to be removed.
// returned - a string with the item removed.
// Note: In the list all items are enclosed with square brackets eg (455)(444)
function RemoveItemStringList(sList, sItem)
{	
	var reg = new RegExp("\\(" + sItem + "\\)");
	sList = sList.replace(reg, "")
	return sList;
}

// sList - a string to which the item is going to be searched in.
// sItem - a string which holds the item to be searched for.
// returned - True or false depending if item was successfully found.
// Note: In the list all items are enclosed with square brackets eg (455)(444)
function FindItemStringList(sList, sItem)
{	
	var reg = new RegExp("\\(" + sItem + "\\)");
	var index = sList.search(reg);
	var bReturnVal = true;
	
	if (index == -1)
		bReturnVal = false;
		
	return bReturnVal;
}

function FormatDateMMYY(i, delKey,direction) {
  if (i.value.length < 5) {
  	if (delKey!=9) { //tab
	  	if(delKey!=8 && delKey!=46 && delKey!=16 &&  !(delKey>36 && delKey<41)){ //if the delete, backspace, shift, are not the keys that caused the keyup event.
  			var fieldLen = i.value.length
   			if ((delKey >= 48 && delKey <= 57) || (delKey >= 96 && delKey <=105)) {
   				if (fieldLen == 2) {
      				i.value = i.value + "/";
		     	}
   			} else {
   				if (direction == "up") {
     				if (i.value.length == 0) {
      					i.value = ""
	     			} else {
		      			i.value = i.value.substring(0,i.value.length-1)
	   				}
    			}
	 		}
  			i.focus()
	  	}
 	} else {
 		if (direction == "down") {
	 		//CheckDate(i);
  		}
  	}
 }
}

function FormatNumberEntry(i, delKey,direction) {

  	if (delKey!=9) { //tab
	  	if(delKey!=8 && delKey!=16 &&  !(delKey>36 && delKey<41)){ //if the delete, backspace, shift, are not the keys that caused the keyup event.
  			var fieldLen = i.value.length
   			if ((delKey >= 48 && delKey <= 57) || (delKey == 190) || (delKey >= 96 && delKey <= 105)) {
   			
   			} else {
   				if (direction == "up") {
     				if (i.value.length == 0) {
      					i.value = ""
	     			} else {
		      			i.value = i.value.substring(0,i.value.length-1)
	   				}
    			}
	 		}
  			i.focus()
	  	}
 	} else {
 		if (direction == "down") {
	 		//CheckDate(i)
  		}
  	}
}


function replace(string,text,by) {
// Replaces text with by in string
    var strLength = string.length, txtLength = text.length;
    if ((strLength == 0) || (txtLength == 0)) return string;

    var i = string.indexOf(text);
    if ((!i) && (text != string.substring(0,txtLength))) return string;
    if (i == -1) return string;

    var newstr = string.substring(0,i) + by;

    if (i+txtLength < strLength)
        newstr += replace(string.substring(i+txtLength,strLength),text,by);

    return newstr;
}