/***********************
* Frame resizing logic
************************/

    function resizeFrame(frameID)
    {
        if (!window.opera && !document.mimeType && document.all && document.getElementById)
        {
            parent.document.getElementById(frameID).style.height=this.document.body.offsetHeight+"px";
        }
        else if(document.getElementById)
        {
            parent.document.getElementById(frameID).style.height=this.document.body.scrollHeight+"px";
        }
    }


/***********************
* Popup Focus methods
************************/
var blnPopupFocus;
blnPopupFocus = false

function closePopup(blnParent){

	if (blnPopupFocus == false){
		if (blnParent = true){
			try{
				parent.self.opener.initPage();
			}catch (ex){
				// ignore page is missing.
			}
		}else{
			try{
			self.opener.initPage();
			}catch(ex){
				// ignore page is missing.
			}
		}
	}
}

function setPopupFocus(){
	blnPopupFocus = true;
}

/***********************
* getWindowCoord() 
* Pass in width and height of desired 
*	window size, and screen coordinates
*   are returned for a centered window.
************************/
function getWindowCoord(width,height){

   	var str=",height=" + height + ", " + "width=" + width;

	if (window.screen) 
	{ 
		xc = getScreenXPos(width);
		yc = getScreenYPos(height);

		str += ",left=" + xc + ",screenX=" + xc; 
		str += ",top=" + yc + ",screenY=" + yc; 
	}  

	return (str)
}

/***********************
* moveWindow() 
* Reposition a window.
************************/
function moveWindow(x,y){
	window.moveTo(x,y)
}

/***********************
* getScreenXPos() 
* Return a centered horitonal coord
*	based upon desired window width.
************************/
function getScreenXPos(width){
var aw, xc, horizOffset;

	xc = 0;
	horizOffset = 50;
	aw = screen.availWidth;
	
	if (aw > width){
		xc = (aw - width) / 2 - horizOffset;
	}
	
	return (xc);
}

/***********************
* getScreenYPos() 
* Return a centered vertical coord
*	based upon desired window height.
************************/
function getScreenYPos(height){
var ah, yc;

	yc = 0;
	ah = screen.availHeight; 

	if (ah > height){ 
		yc = (ah - height) / 2; 
	} 

	return (yc);
}


/***********************
* openDialog() 
* Open a new window as a dialog ,
* in the screen.
************************/
function openDialog(objDialogParms, strUrl, intWidth, intHeight, bScroll){
var bScrollbars;

	// define scroll bars property
	if(bScroll == true){bScrollbars = "yes"} else {bScrollbars = "no"};

	// format url, and call dialog;
	strUrl = FormatUrl(strUrl);
	
	window.showModalDialog(strUrl, objDialogParms, "dialogWidth:" + intWidth + "px;dialogHeight:" + intHeight + "px;center:yes;status:no;edge:sunken;scroll:" + bScrollbars);
	
	return (objDialogParms);
}

/***********************
* openForm() 
* Open a new window as a popup centered,
* in the screen.
************************/
function openForm(strUrl){

	setPopupFocus();
	location.href = FormatUrl(strUrl);
}

/***********************
* openPopup() 
* Open a new window as a popup centered,
* in the screen.
************************/
function openPopup(strUrl, strWindowName, intWidth, intHeight, bScroll){
var theWin, bScrollbars, strCoord;

	// don't activate caller.
	setPopupFocus();
	
	// build url	
	strUrl = FormatUrl(strUrl);

	// set window properties and call page.
	if(bScroll == true){bScrollbars = 1} else {bScrollbars = 0};
	strCoord = getWindowCoord(intWidth, intHeight);
	theWin = window.open(strUrl, strWindowName, "resizable=yes,toolbar=no,menubar=no,location=no,status=yes,scrollbars=" + bScrollbars + "," + strCoord);
	theWin.opener = self;
}

/***********************
* openSecured() 
* Open a modal popup centered,
* in the screen.
************************/
function openSecured(strUrl, strClassName, strWindowName, intWidth, intHeight, bScroll, bPopup, sRelativePath){
var sSecuredURL;

	// build URL
	strUrl = encodeURIComponent(strUrl);
	sSecuredURL = sRelativePath + "/Dialog/FunctionSecurity.aspx?FormName=" + strClassName + "&URL=" + strUrl + "&Width=" + intWidth + "&Height=" + intHeight + "&WinName=" + strWindowName + "&Scroll=" + bScroll + "&Popup=" + bPopup

	// open page.
	theWin = openPopup(sSecuredURL, strWindowName, 360, 240, bScroll);
}

/***********************
* openDatePopup() 
* Open a date popup centered,
* in the screen.
************************/
function openDatePopup(objDateField, sRelativePath){
var intWidth, intHeight, strWindowName, strCoord, sURL;
	
	// set globally defined js var in page.
	setPopupFocus();
	objActiveField = objDateField;
	
	// define window properties.
	intWidth=240;
	intHeight=220;
	strWindowName="DateDialog";
	strCoord = getWindowCoord(intWidth, intHeight);

	// build url
	sURL = FormatUrl(sRelativePath + "/Dialog/DateDialog.aspx?txtDate=" + objDateField.value)
	
	// call page
	theWin = window.open(sURL, strWindowName, "resizable=no,titlebar=0,toolbar=no,menubar=no,location=no,status=no,scrollbars=no," + strCoord);

	//code below does not seem to be needed.
	//---------------------------------------
	//theWin.opener = self;
	//return (theWin);
}

/***********************
* FormatUrl() 
* Build a URL with required query-string
*	name-value pairs
************************/
function FormatUrl(sUrl){
var objFacility, objUser, lFacilityId, lUserId;

	// get facilityId, userId if defined.
	try{
		objFacility = document.forms[0].txtActiveFacilityId;
		objUser = document.forms[0].txtActiveUserId;
		lFacilityId = objFacility.value;
		lUserId = objUser.value;
	}catch(ex){
		lFacilityId = 0;
		lUserId = 0	;
	}

	sUrl = appendUrl(sUrl, "txtActiveFacilityId", lFacilityId);
	sUrl = appendUrl(sUrl, "txtActiveUserId", lUserId);

	return (sUrl);
}


/***********************
* appendUrl() 
* Add querystring elements to a url.
************************/
function appendUrl(sUrl, sName, sValue){
var sDelimiter;

	if (sUrl.indexOf("?") > -1){
		sDelimiter = "&"
	} else {
		sDelimiter = "?"
	}

	sUrl = sUrl + sDelimiter + sName + "=" + sValue;
	
	return (sUrl);
}

/***********************
* preInit() 
* Perform page pre-initialization logic.
************************/
function preInit(){
	if (document.forms[0].txtValidateUser == "ValidateUser")
		{
			document.forms[0].txtValidateUser = "";
			
		}

}

/***********************
* postInit() 
* Perform page post-initialization logic.
************************/
function postInit(){
}

/***********************
* stripFormAction() 
* Remove any query-string defs from the 
*	the form's action tag.
************************/
function stripFormAction(){
var sAction,lQryStringPos;

	sAction = document.forms[0].action;
	lQryStringPos = sAction.indexOf("?");
	
	if (lQryStringPos > -1){
		document.forms[0].action = sAction.substring(0,lQryStringPos)
	}
}

/***********************
* isValidNumber() 
* Is the value held in objArgs equal to a valid 
*	number?  Function has been built to be called
*	from customValidator control.
************************/
function isValidNumber(objSource, objArgs){
var blnValid = true;
var intNumber = objArgs.Value;

 
intNumber = intNumber.replace("$","");
  
   if (isNaN(parseInt(intNumber))) {
      blnValid = false
   } else {
   blnValid = true  }
 	
 objArgs.IsValid = blnValid;
 
 return (blnValid);
}

/***********************
* isNumber() 
* Is the parameter equal to a valid number
************************/
function isNumber(intNumber){
var blnValid = true;

 if (isNaN(parseInt(intNumber))) {
    blnValid = false
 } else {
	blnValid = true  }
 
 return (blnValid);
}

/***********************
* listRightToLeft() 
* Move selected items from list on right to 
*	the list on the left.
************************/
function listRightToLeft(leftList, rightList)
{
	var len = leftList.length;
	var len2 = rightList.length;
	

	//Adding the selected items from right list into left list
	for(var i = 0; i < len2; i++) 
	{
		if ((rightList.options[i] != null) && (rightList.options[i].selected)) 
		{
			leftList.options[len] = new Option(rightList.options[i].text);
			leftList.options[len].value = rightList.options[i].value;
			isUpdated = true;
			len++;
		}
	}
	//delete items from right list that were added to left list
	for(var i = (len2-1); i >= 0; i--) 
	{
		if ((rightList.options[i] != null) && (rightList.options[i].selected == true)) 
		{
			rightList.options[i] = null;
		}
	}
}

/***********************
* listLeftToRight() 
* Move selected items from list on left to 
*	the list on the right.
************************/
function listLeftToRight(leftList, rightList)
{
	var len = rightList.length;
	var len2 = leftList.length;
	var selLen = 0;
		
	//Count how many items are selected
	for(var i = 0; i < len2; i++)
	{
		if ((leftList.options[i] != null) && (leftList.options[i].selected)) 
		{
			selLen++;
		}
	}
		
	//Adding the selected items from left list into right list
	for(var i = 0; i < len2; i++)
	{
		if ((leftList.options[i] != null) && (leftList.options[i].selected)) 
		{
			rightList.options[len] = new Option(leftList.options[i].text);
			rightList.options[len].value = leftList.options[i].value;
			len++;
			isUpdated = true;
		}
	}

	//delete items from left list that were added to right list
	for(var i = (len2-1); i >= 0; i--) 
	{
		if ((leftList.options[i] != null) && (leftList.options[i].selected == true)) 
		{
			leftList.options[i] = null;
		}
	}
}		

/***********************
* updateButtons() 
* When a page contains 2 listboxes, with 
*	left/right assignment buttons, activate
*	or deactivate the buttons based upon their
*	contents.
************************/
function updateButtons(leftList, rightList, toleft, toright )
{
		
	var leftLen = leftList.length;
	var rightLen = rightList.length;
		
	if (leftLen <= 0){
		toright.disabled = true; 
	}
	else{
		toright.disabled = false; 
	}
		
	if (rightLen <= 0){
		toleft.disabled = true; 
	}
	else{
		toleft.disabled = false; 
	}
}

/***********************
* updateIdList() 
* For a managed list of Id's in list box.
*	update the hidden field to reflect the 
*	assigned values after a change.
************************/
function updateIdList(leftList, idList){
var len2 = leftList.length;
var recIDs="";
	
	for(var i = 0; i < len2; i++){
		if ((leftList.options[i] != null)){
			recIDs = recIDs + leftList.options[i].value + ",";
		}
	}
	idList.value=recIDs.substring(0,recIDs.length-1)
}


/***********************
* y2k() 
* Is the year equal to a century
************************/
function y2k(number){ 
	return (number < 1000) ? number + 1900 : number; 
}


/***********************
* isDate() 
* checks if date passed is in valid mm/dd/yyyy format
************************/
function isDate(datein){
 var indate=datein,blnValid;

	if (indate.indexOf("-")!=-1){
		var sdate = indate.split("-")
	}
	else {
		var sdate = indate.split("/")
	}

	var chkDate=new Date(Date.parse(indate))

	var cmpDate=(chkDate.getMonth()+1)+"/"+(chkDate.getDate())+"/"+(chkDate.getYear())
	var indate2=(Math.abs(sdate[0]))+"/"+(Math.abs(sdate[1]))+"/"+(Math.abs(sdate[2]))
 
	if (indate2!=cmpDate){
			blnValid = false;
	}
	else {
		if (cmpDate=="NaN/NaN/NaN"){
			blnValid = false;
		}
		else {
			blnValid = true;
		}
	}

	return(blnValid);

}

/***********************
* isValidDate() 
* checks if date passed is in valid mm/dd/yyyy format
************************/
function isValidDate (objSource, objArgs) {
var sep, blnValid, sValue, dValue;
	
	sep = "/";
	blnValid = true;
	sValue = objArgs.Value;
	dValue = new Date(sValue);
	
	if (isNaN(dValue)){
		blnValid = false
	}
	
	objArgs.IsValid = blnValid;
}

/***********************
* isValidPhone(sVal) 
* if value is not 7 or 10 digits 
* and not all numeric then the 
* number is not valid.
************************/
function isValidPhone(objSource, objArgs){
var sPhone,sValue,blnValid;

	sValue = objArgs.Value;
	sPhone = getNumeric(sValue)
	
	if ((sPhone.length == 7) || (sPhone.length == 10) || sPhone.length == 0) {
		blnValid = true
	}else{
		blnValid = false
	}
	
	objArgs.IsValid = blnValid
}

/***********************
* isPhone(sVal) 
* if value is not 7 or 10 digits 
* and not all numeric then the 
* number is not valid.
************************/
function isPhone(sValue){
var sPhone;

	sPhone = getNumeric(sValue)
	
	if ((sPhone.length == 7) || (sPhone.length == 10) || (sPhone.length == 0)) {
		return(true)
	}else{
		return(false)
	}
}

/***********************
* trim(sVal) 
* Return a trimmed value.
************************/
function trimValue(sVal) {
var tValue;

    var m = sVal.match(/^\s*(\S+(\s+\S+)*)\s*$/);
    tValue = (m == null) ? "" : m[1];
    return tValue;
}

/***********************
* isRegExpressionValid(sRegExp, sVal) 
* Compare a value to a regular expression, and
*	true if value is a match.
************************/
function regExpressionIsValid(sRegExp, sVal) {

    if (trimValue(sVal).length == 0)
        return true;        
    var rx = new RegExp(sRegExp);
    var matches = rx.exec(sVal);
    return (matches != null && sVal == matches[0]);
}


var blnReformatting = false;

/***********************
* reFormatNumber()
* Format a numeric entry that was 
*	modified by the user.
************************/
function reFormatNumber(objTextField,Decimals,Currency){

	if (blnReformatting == false){
		Number = objTextField.value;
		blnReformatting = true;
		Number = FormatNumber(Number, Decimals, ".", Currency);
		objTextField.value = Number;
		blnReformatting = false;
	}
}

/***********************
* reFormatTime()
* Format a time entry that was 
*	modified by the user.
************************/
function reFormatTime(objTextField){

	if (blnReformatting == false){
		sTime = objTextField.value;
		blnReformatting = true;
		sTime = formatTime(sTime);
		objTextField.value = sTime;
		blnReformatting = false;
	}
}


/***********************
* reFormatDate()
* Format a date entry that was 
*	modified by the user.
************************/
function reFormatDate(objTextField){

	if (blnReformatting == false){
		sDate = objTextField.value;
		blnReformatting = true;
		sDate = formatDate(sDate);
		objTextField.value = sDate;
		blnReformatting = false;
	}
}

/***********************
* stripPhoneFormat()
* Format a phone entry that was 
*	modified by the user.
************************/
function stripPhoneFormat(objTextField){

	if (blnReformatting == false){
		sPhone = objTextField.value;
		blnReformatting = true;
		sPhone = getNumeric(sPhone);
		if (isPhone(sPhone)){
			objTextField.value = sPhone;
		}
		blnReformatting = false;
		objTextField.select();
	}
}

/***********************
* reFormatPhone()
* Format a phone entry that was 
*	modified by the user.
************************/
function reFormatPhone(objTextField, sMsg){

	if (blnReformatting == false){
		sPhone = objTextField.value;
		if (isPhone(sPhone)){
			blnReformatting = true;
			sPhone = FormatPhone(sPhone);
			objTextField.value = sPhone;
			blnReformatting = false;
		}
	}
}

/***********************
* FormatPhone()
* Format a phone number 
************************/
function FormatPhone(sValue){
var iLen, sAreaCode, sPrefix, sNumber, sPhone;

	iLen = sValue.length;
	sPhone = sValue;
	if (iLen == 10) {
		sAreaCode = sValue.substring(0,3);
		sPrefix = sValue.substring(3,6);
		sNumber = sValue.substring(6,10);
		sPhone = "(" + sAreaCode + ") " + sPrefix + "-" + sNumber;
	}else{
		if (iLen == 7){
			sPrefix = sValue.substring(0,3);
			sNumber = sValue.substring(3,7);	
			sPhone = sPrefix + "-" + sNumber;
		}else{
			return(sValue);
		}
	}
	
	return(sPhone);
}


/***********************
* FormatNumber()
* Format a number 
************************/
function FormatNumber(Number,Decimals,Separator, Currency)
{
 // **********************************************************
 // This function accepts a number to format and number
 // specifying the number of decimal places to format to. May
 // optionally use a separator other than '.' if specified.
 //
 // If no decimals are specified, the function defaults to
 // two decimal places. If no number is passed, the function
 // defaults to 0. Decimal separator defaults to '.' .
 //
 // If the number passed is too large to format as a decimal
 // number (e.g.: 1.23e+25), or if the conversion process
 // results in such a number, the original number is returned
 // unchanged.
 // **********************************************************
 var bDollar = false;
 
 Number += ""          // Force argument to string.
 Decimals += ""        // Force argument to string.
 Separator += ""       // Force argument to string.
 if((Separator == "") || (Separator.length > 1))
  Separator = "."
 if(Number.length == 0)
  Number = "0"

 // temporarily remove currency sign  
 if (Number.indexOf(Currency) > -1){
	bCurrency = true;
	Number = Number.replace(Currency,"");
 }
 
 // remove commas
 Number = Number.replace(",","");
 
 var OriginalNumber = Number  // Save for number too large.
 var Sign = 1
 var Pad = ""
 var Count = 0
 
 // If no number passed, force number to 0.
 if(parseFloat(Number)){
  Number = parseFloat(Number)} else {
  Number = 0}
  
 // If no decimals passed, default decimals to 2.
 if((parseInt(Decimals,10)) || (parseInt(Decimals,10) == 0)){
  Decimals = parseInt(Decimals,10)} else {
  Decimals = 2}
 if(Number < 0)
 {
  Sign = -1         // Remember sign of Number.
  Number *= Sign    // Force absolute value of Number.
 }
 if(Decimals < 0)
  Decimals *= -1    // Force absolute value of Decimals.
 
 // Next, convert number to rounded integer and force to string value.
 // (Number contains 1 extra digit used to force rounding)
 Number = "" + Math.floor(Number * Math.pow(10,Decimals + 1) + 5)
 if((Number.substring(1,2) == '.')||((Number + '')=='NaN'))
  return(OriginalNumber) // Number too large to format as specified.
 // If length of Number is less than number of decimals requested +1,
 // pad with zeros to requested length.
 if(Number.length < Decimals +1) // Construct pad string.
 {
  for(Count = Number.length; Count <= Decimals; Count++)
   Pad += "0"
 }
 Number = Pad + Number // Pad number as needed.
 if(Decimals == 0){
  // Drop extra digit -- Decimal portion is formatted.
  Number = Number.substring(0, Number.length -1)} else {
  // Or, format number with decimal point and drop extra decimal digit.
 Number = Number.substring(0,Number.length - Decimals -1) +
          Separator +
          Number.substring(Number.length - Decimals -1,
          Number.length -1)}
          
  // add commas back to whole number portion
  iDecPosition = Number.indexOf(Separator)
  sWholeNum = Number.substring(0,iDecPosition);
  iLen = sWholeNum.length;
  iDigitCount = 0;
  sWholeComma = ""
  for (i=iLen;i >= 0;i--){
		sChar = sWholeNum.charAt(i);
		if (isNumber(sChar) == true) {
			sWholeComma = sChar + sWholeComma;
			iDigitCount += 1;
			
			if ((iDigitCount == 3) && (i != 0)){
				iDigitCount = 0;
				sWholeComma = "," + sWholeComma;
			}
		}
  }	
 
 // concat whole number with commas to decimal.
 sDecimal = Number.substring(iDecPosition,Number.length)
 Number = sWholeComma + sDecimal;
  
 // set sign and currency
 if((Number == "") || (parseFloat(Number) < 1))
  Number="0"+Number // Force leading 0 for |Number| less than 1.
 if(Sign == -1)
  Number = "-" + Number  // Set sign of number.
 
 Number = Currency + Number;
  
 return(Number)
}

/***********************
* getCurrencyValue()
* Return a value with only numeric values,
*	and all non-numerics removed, leave decimals.
************************/
function getCurrencyValue(objTextField, Currency){
var Number;

 Number = objTextField.value;

 // Force argument to string.
 Number += ""      
 
 // remove currency sign  
 if (Number.indexOf(Currency) > -1){
	bCurrency = true;
	Number = Number.replace(Currency,"");
 }
 
 // remove commas
 Number = Number.replace(",","");
 
 return(Number);
}


/***********************
* getNumeric()
* Return a value with only numeric values,
*	and all non-numerics removed.
************************/
function getNumeric(sValue){
var i, iLen, sChar, s;

	s = "";
	iLen = sValue.length;
	
	// parse string for numerics
	for (i=0;i < iLen;i++){
	
		sChar = sValue.charAt(i);
		if (isNumber(sChar) == true) {
			s += sChar;
		}
	}	

	return(s);
}


/***********************
* formatTime()
* Format a time entry.  
************************/
function formatTime(sValue){
var sTime, sChar, i, iLen, iDigitCount, sHourVal, sMinVal;
var bColonRead, bHourRead, bMinRead, bFirstNo;
	
	s = "";
	bColonRead = false;
	bHourRead = false;
	bFirstNo = false;
	bMinRead = false;
	iDigitCount = 0;
	sHourVal = "0";
	sMinVal = "00";
	sQual = " AM";
	
	iLen = sValue.length;
	
	// parse string for main time elements
	for (i=0;i < iLen;i++){
	
		sChar = sValue.charAt(i);
		if (isNumber(sChar) == true) {
			iDigitCount++;
			s += sChar;
			
			if (bFirstNo == false){
				bFirstNo = true;
				sHourVal = "";
			}
			
		    if (bHourRead == true){
				if (bMinRead == false){ 
					sMinVal = "";
				}
				sMinVal += sChar;
				bMinRead = true;
		    }else{
				sHourVal += sChar;
		    }
		}else {
			if (sChar == ":") {
				bColonRead=true;
				s += sChar;
					
				if ((iDigitCount > 0) && (iDigitCount < 3)){
					bHourRead = true;
					iDigitCount = 0;
				}
			} else {
			  
				if ((sChar == "a") || (sChar == "A")){
					s += " AM";
					sQual = " AM";
					break;
			
				} else {
					if ((sChar == "p") || (sChar == "P")){
						s += " PM";
						sQual = " PM";
						break;
					}
				}	  
			}
		}
	}

	// final time validation
	iHour =  parseInt(sHourVal)
	iMin = parseInt(sMinVal)
	if ((iHour > 12) || (iMin > 59) || (iHour == 0) || (sHourVal.length > 2) || (sMinVal.length > 2)){
		sTime = "";
	}else{
		sTime = sHourVal + ":" + sMinVal + sQual;
	}

	// return formatted time.
	return(sTime);
}

/***********************
* formatDate()
* Format a date entry.  Expects
*	a date value.
************************/
function formatDate(sValue){
var s;

	dValue = new Date(sValue);
	
	if (isNaN(dValue)){
		s = "";
	}else{
		s = (dValue.getMonth() + 1) + "/";
		s += dValue.getDate() + "/";
		s += dValue.getYear();
	}
	
	return(s);
}
