function GetIdArray(sID) {
    var obj1 = document.all.item(sID)
    var obj2 = new Array(0);
    if (obj1 == null) {return}
    if (typeof(obj1.length) != "undefined") {
        return obj1
    }
    else {
        obj2[0] = obj1
        return obj2
    }       
}


function TabClick4Aspx(tabClicked, target)
{
    if (tabClicked == null) {return}
    
    var j = tabClicked.id.indexOf("_");
    var TabStripName = tabClicked.id.substring(0, j);
    var oldTab = null;
    
    if (document.getElementById(TabStripName + "_ActiveCell").value != "")
    {
		oldTab = document.getElementById(document.all(TabStripName + "_ActiveCell").value);
	}
	
    if (oldTab != null)
    {
		oldTab.className = "tab_Left";
    }
    
    tabClicked.className = "tab_Active";
    
    var tabDiv = document.getElementById(TabStripName + '_' + TabStripName);
    var top = parseInt(tabDiv.offsetTop) + tabDiv.offsetHeight + 3;
	
    var divs = document.body.getElementsByTagName("DIV");
    for (var i = 0; i < divs.length; i++)
    {
        if (divs[i].className == "TabBody")
        {
            if (divs[i].id == target)
            {
                divs[i].style.visibility = "visible";
                divs[i].style.top = top;
            }
            else
            {
                // This is to get around an apparent bug.  If we don't have this line,
                // then a ghost frame of the hidden tables shows up on the visible div.
                divs[i].style.top = top;
                divs[i].style.visibility = "inherit";
                divs[i].style.visibility = "hidden"
            }
        }
   }
   
   document.all(TabStripName + "_ActiveCell").value = tabClicked.id; 
}

    
function GetParentByTag(obj, tagName) {
    do {
       if (obj.parentElement == null) {return;}
       if (obj.parentElement.tagName == tagName) {return obj.parentElement}   
       obj = obj.parentElement
    }  
    while (true);   
}

function SyncScroll(DataDiv, HeaderDiv)
{
    HeaderDiv.scrollLeft = DataDiv.scrollLeft
}

function gotChange2(obj) {
    // Keep track of any controls that have changed.
    // If obj has already changed, then return.
    

    obj.isChanged = "true";    
    document.getElementById("BDATACHANGED").value = 1;
    
}

function EnableButton(TheButton) {
	if (TheButton != null && TheButton.type == "button") {
		TheButton.disabled = false;
    }
}

function DisableButton(TheButton) {
	if (TheButton != null && TheButton.type == "button") {
		TheButton.disabled = true;
    }
}

function SaveClick(ClickedButton) {
    // Handles save button click.
    document.body.style.cursor = "wait";
    DisableButton(ClickedButton);
    ProgressbarShow();

    var ChangedControl = document.getElementById("ChangedControlIDCollection");

    if (!ValidateForm()) {document.body.style.cursor = "auto"; EnableButton(ClickedButton); ProgressbarHide(); return false};
    if (DirtyForm()) {document.body.style.cursor = "auto"; EnableButton(ClickedButton); ProgressbarHide(); return false};
    document.all("RequestAction").value = "Save";
    document.all("BSAVE").value = 1;
    
    if (document.getElementById("__EVENTTARGET") != null) { document.getElementById("__EVENTTARGET").value = ""; }
    if (document.getElementById("__EVENTARGUMENT") != null) { document.getElementById("__EVENTARGUMENT").value = ""; }
    document.forms[0].submit();
}

function EditClick() {
    // Handles edit button click.
    document.all("RequestAction").value = "Edit";
    document.all("BSAVE").value = 1;
    
    if (document.getElementById("__EVENTTARGET") != null) { document.getElementById("__EVENTTARGET").value = ""; }
    if (document.getElementById("__EVENTARGUMENT") != null) { document.getElementById("__EVENTARGUMENT").value = ""; }
    document.forms[0].submit();
}

function ValidateForm() {
    // Does all client-side validation.
    if (!FT_FinalTest()) {return false};
    return true;    
}


function WorkFlowValidateForm(clickedLink) {
	/* If user clciked a link on a workflow linked list, compare the current step (index) and the clicked index.
	   Only validate required fields in the user steps forward in the workflow or stays on the same page. */
	
	var re = new RegExp("^([^_]+).+_row(\\d+)$", "i");
	var clickedIndex;
	var currentStep;
	var currentIndex;
	
	try {
		/* clickedLink's parentElement's parentElement should be the row in the table */
		if (re.test(clickedLink.parentElement.parentElement.id)) {
			/* get the workflows name and the clicked rows index */
			clickedIndex = parseInt(RegExp.$2, 10);
			currentStep = document.getElementById(RegExp.$1 + "_CurrentStep");
			currentIndex = parseInt(currentStep.value, 10);
		}
		else { return false; }
		
		/* we only want to proceed with validation of required fields if the user steps forward in the workflow or stays on the same page */
		if (clickedIndex < currentIndex) { return true; }
	}
	catch (any) {
		return false;
	}
	
	return ValidateForm();
}


function DirtyForm() {
    // Checks to see if this form has already been saved 
    // (i.e. user clicked save then click the back button)
    return false;
}

function Lookup2(AssemblyName, ClassName, CodeTarget, DescriptionTarget, MultiSelect) {

    var URL = ""
    var obj = document.all(CodeTarget)
    var s
      
    URL = document.all("WebShareName").value
    URL += "/pages/Lookup.aspx?"    
    URL += "AssemblyName=" + AssemblyName 
    URL += "&ClassName=" + ClassName 
    URL += "&MultiSelect=" + MultiSelect 
    URL += "&CodeTarget=" + CodeTarget
    URL += "&DescriptionTarget=" + DescriptionTarget


    // If any parents are supplied, add them to the URL.  Ignore
    // errors here because there might not be any.
    try {       
        var parentsArray = obj.myParents.split("^")
        var parentTypesArray = obj.myParentTypes.split("^")
        for (var i=0; i < parentsArray.length - 1; i++) {
           // If the parent is a <td>, we need to get the value from .innerText,
           // if it's a <input>, we need .value.
           if (document.all(parentsArray[i]).innerText != "") {s = document.all(parentsArray[i]).innerText}
           else {s = document.all(parentsArray[i]).value}  
           URL += "&" + parentTypesArray[i] + "=" + s
        }
    }
    catch (any) {}    
    
    OpenNewWindow(URL)

}

function MailTo(obj) {
    
    location.href="mailto:" + obj.value
}


/*
The following 6 functions are related to a SingleSelect or MultiSelct
data grid.
*/
var ShiftKeyPressed = false
var RowWithShiftKeyPressed = -1
var RowColors = new Array();
var PreviousSelectedSingleRow;

function CollapseArray(myArray) {
	var s = new String();
	for (var i = 0; i < myArray.length; i++) {
		if (myArray[i] != null && myArray[i] != "") {
			s += myArray[i] + "^";
		}
	}
	
	return s.substr(0, s.length - 1);
}

function AddCodeToCollection(row) {
	if (document.getElementById("SavedSelection_TextBox") == null) { return; }
	
	var SelectedCodes = document.getElementById("SavedSelection_TextBox").value.split("^");
	SelectedCodes.push(row.childNodes[0].innerText);
	document.getElementById("SavedSelection_TextBox").value = CollapseArray(SelectedCodes);
	
	var SelectedDescriptions = document.getElementById("SavedDescription_TextBox").value.split("^");
	SelectedDescriptions.push(row.childNodes[1].innerText);
	document.getElementById("SavedDescription_TextBox").value = CollapseArray(SelectedDescriptions);
	
}

function RemoveCodeFromCollection(row) {
	if (document.getElementById("SavedSelection_TextBox") == null) { return; }
	
	var SelectedCodes = document.getElementById("SavedSelection_TextBox").value.split("^");
	for (var i = 0; i < SelectedCodes.length; i++) {
		if (SelectedCodes[i] == row.childNodes[0].innerText) {
			SelectedCodes[i] = "";
			document.getElementById("SavedSelection_TextBox").value = CollapseArray(SelectedCodes);
			break;
		}
	}
	
	var SelectedDescriptions = document.getElementById("SavedDescription_TextBox").value.split("^");
	for (var i = 0; i < SelectedCodes.length; i++) {
		if (SelectedDescriptions[i] == row.childNodes[1].innerText) {
			SelectedDescriptions[i] = "";
			document.getElementById("SavedDescription_TextBox").value = CollapseArray(SelectedDescriptions);
			break;
		}
	}
}

function SaveRowColor(row) {
	if ( RowColors[row.id] == null) {
		RowColors[row.id] = row.currentStyle.backgroundColor;
	}
}

function GetRowColor(row) {
	return RowColors[row.id];
}

var LIGHT_GREEN = "#bdd2d2"

function SetRowSelected(obj) {
	var DataGridID = ""
	var bSingleSelect = false
	var SingleSelectID = ""
	var bSelectRow = true
	
	DataGridID = obj.parentElement.parentElement.id
	i = DataGridID.indexOf("_")
	DataGridID = DataGridID.substring(0, i)
	SingleSelectID = DataGridID + "_SingleSelect"
	if (typeof(document.forms[0].elements[SingleSelectID]) == "undefined") {bSingleSelect = false}
	else {bSingleSelect = (document.forms[0].elements[SingleSelectID].value == "true")}
	
	bSelectRow = (obj.style.backgroundColor != LIGHT_GREEN )
	
	if (bSingleSelect == true) {
		//reset bSelected.
		if (!bSelectRow) {document.forms[0].elements[DataGridID + "_bSelected"].value = ""}
		else {
			bSomethingSelected = (document.forms[0].elements[DataGridID + "_bSelected"].value == "true")
			// Only allow 1 row selected. If another row is selected, clear that row.
			if (bSomethingSelected) {
				PreviousSelectedSingleRow.style.backgroundColor = GetRowColor(PreviousSelectedSingleRow);
			}  
			
			//Remove any values from SavedSelection_TextBox. 
			document.getElementById("SavedSelection_TextBox").value = "";
			
			// Set bSelected and stach away the row in case the user selects another row and we need to deselect this one.
			document.forms[0].elements[DataGridID + "_bSelected"].value = "true"
			PreviousSelectedSingleRow = obj;
		}
	}
	else {
		if (ShiftKeyPressed == true && RowWithShiftKeyPressed > -1 ) {
			if (document.selection) {document.selection.empty()}
			else if (window.getSelection){window.getSelection().removeAllRanges()}
			if (RowWithShiftKeyPressed > GetRowNumber(obj.rowNum)) {
				for (i = GetRowNumber(obj.rowNum); i <= RowWithShiftKeyPressed; i++) {
					SaveRowColor( obj.parentElement.rows(i) );
					AddCodeToCollection(obj.parentElement.rows(i));
					obj.parentElement.rows(i).style.backgroundColor = LIGHT_GREEN;
				}
			}
			else {
				for (i = RowWithShiftKeyPressed; i <= GetRowNumber(obj.rowNum); i++) {
					SaveRowColor( obj.parentElement.rows(i) );
					AddCodeToCollection(obj.parentElement.rows(i));
					obj.parentElement.rows(i).style.backgroundColor = LIGHT_GREEN 
				}
			}
		}
		else {RowWithShiftKeyPressed = GetRowNumber(obj.rowNum)}        
	}        
	
	if (bSelectRow) {
		SaveRowColor(obj);
		AddCodeToCollection(obj);
		obj.style.backgroundColor = LIGHT_GREEN 
	}
	else {
		obj.style.backgroundColor = GetRowColor(obj);
		RemoveCodeFromCollection(obj);
	}
	
	if (document.selection) {document.selection.empty()}
	else if (window.getSelection){window.getSelection().removeAllRanges()}
}

function GetRowNumber (rowString) {
	return parseInt(rowString.substring(3, rowString.length), 10);
}

function SetShiftKeyPressed() {
    var pressed = (window.event.keyCode)
    if (pressed == 16) {ShiftKeyPressed = true}
}

function ClearShiftKeyPressed() {    
    var pressed = (window.event.keyCode)
    if (pressed == 16) {ShiftKeyPressed = false}
}

function ToggleSelectAll(GridID) {
    var Table = document.getElementById(GridID + "_DataTable")
    

    ss = document.activeElement.innerHTML
    if (ss == "Select All") {
        document.activeElement.innerHTML = "Clear All"
        for (i = 0; i <= Table.rows.length - 1; i++) {
        	SaveRowColor(Table.rows(i));
        	AddCodeToCollection(Table.rows(i));
            Table.rows(i).style.backgroundColor = LIGHT_GREEN
        }
    }        
    else {
        document.activeElement.innerHTML = "Select All"
        for (i = 0; i <= Table.rows.length - 1; i++) {
        	Table.rows(i).style.backgroundColor = GetRowColor(Table.rows(i));
        	RemoveCodeFromCollection(Table.rows(i));
        }
    }        
    

}    

function LookupSelectAll(GridID) {

    var Table = document.getElementById(GridID + "_DataTable")
       
    for (i = 0; i <= Table.rows.length - 1; i++) {
       	SaveRowColor(Table.rows(i));
       	AddCodeToCollection(Table.rows(i));
        Table.rows(i).style.backgroundColor = LIGHT_GREEN
    }        
}

function LookupClearAll(GridID) {
    var Table = document.getElementById(GridID + "_DataTable")
    for (i = 0; i <= Table.rows.length - 1; i++) {
       	Table.rows(i).style.backgroundColor = GetRowColor(Table.rows(i));
       	RemoveCodeFromCollection(Table.rows(i));
    }        
}

function GetCell(obj, index) {
    // Given a cell of a row and an index to find (zero relative)
    // will reutrn the given cell index from the same row.
    
    row = GetParentByTag(obj, "TR")		
    return row.cells[index]		
    
}

function GetParam(obj, param) {
    // Given a control in a row (obj), will return
    // a control whose name ends in param that lives in the 
    // same row.  This function assumes that the html table
    // was created by a ysiDataGrid.

    if (obj.tagName == "TR") {Row = obj}
    else {
        Row = GetParentByTag(obj, "TR")				
    }
    ControlID = Row.id + "_" + param
    Control = document.all(ControlID)
    return Control
    
    
}

function MessageHandlerSelect(obj) {
	try {
    	obj.focus();        
      	obj.select();        
	}
	catch (any) { }

}

function ResetSelection() {
	var bSingleSelect = false
	
	if (typeof(document.forms[0].elements["LookupGrid_SingleSelect"]) == "undefined") {bSingleSelect = false}
	else {bSingleSelect = (document.forms[0].elements["LookupGrid_SingleSelect"].value == "true")}
	
	if (document.getElementById("SavedSelection_TextBox").value != "") {
		var SelectedCodes = document.getElementById("SavedSelection_TextBox").value.split("^");
		var DataTable = document.all.LookupGrid_DataTable
		
		for (var i = 0; i < DataTable.rows.length; i++) {
 			for (var j = 0; j < SelectedCodes.length; j++) {
				if (SelectedCodes[j] == DataTable.rows[i].childNodes[0].innerText) {
					SaveRowColor(DataTable.rows[i]);
					DataTable.rows[i].style.backgroundColor = LIGHT_GREEN;
					if (bSingleSelect == true && SelectedCodes.length == 1) {
						document.forms[0].elements["LookupGrid_bSelected"].value = "true";
						PreviousSelectedSingleRow = DataTable.rows[i];
					}
					break;
				}
			}
		}
	}
}

function ShowSelection() {
    var TargetID
    var Target
    var CodeValue = ""
    var DescriptionValue = ""
    var SelectedCount = 0
    
    CodeValue = document.getElementById("SavedSelection_TextBox").value;
    /* Strip out illegal spaces (basically before and after a code) */
    CodeValue = trim(CodeValue.replace(/\s?\^\s?/g, "^"));
    
    DescriptionValue = document.getElementById("SavedDescription_TextBox").value;
    /* Strip out illegal spaces (basically before and after a description) */
    DescriptionValue = trim(DescriptionValue.replace(/\s?\^\s?/g, "^"));
    
    // Don't prompt description if multi-select.
    if (CodeValue.indexOf("^") > 0) {DescriptionValue = ""}
    
	// Set Code and Description values (optionally).
    TargetID = document.all.CodeTarget.value
    if (TargetID != "") {
		Target = opener.document.getElementById(TargetID)		    
		Target.value = CodeValue
		Target.focus()   
		opener.gotChange2(Target)
		Target.fireEvent("onChange")
	}
	
    TargetID = document.all.DescriptionTarget.value
    if (TargetID != "") {
		Target = opener.document.getElementById(TargetID)		    
	    if ((Target != null) && (CodeValue.indexOf("^") < 0)) {Target.innerText = DescriptionValue}
	}
	
	window.close()		
}

function GetTotal(obj) {
// Given a cell from a table that contains an INPUT text box, will return the 
// total for that column.

	table = GetParentByTag(obj, "TABLE")				
	row = GetParentByTag(obj, "TR")
	columnNum = -1
	for (i=0; i < row.cells.length; i++) {
		if (obj.id == row.cells[i].childNodes[0].id) {
			columnNum = i
			break;
		}
	}
	if (columnNum == -1) {return 0}
	
	gridTotal = 0	
	for (i=0; i < table.rows.length; i++) {
		gridTotal += parseNum(table.rows[i].cells[columnNum].childNodes[0])
	}
	return gridTotal


}


		  
function GetLinkParam(name) {
    
    Row = GetParentByTag(document.activeElement, "TR")				
    return GetParam(Row, name)


}


function LeftPad(sToBePadded, sPad, dFinalLength)
{
	var sTemp = "";
	for (i = 0; i < dFinalLength - sToBePadded.length; i++)
	{
		sTemp += sPad.toString();
	}
	
	return sTemp.concat(sToBePadded);
}

function Redirect(URL) {
    document.location.href = URL    
}

function SetInitialFocus(obj) {
	// If the page failed to load, we'll still call this, 
	// so make sure it's not null.
	if (obj == null) {return}
	
	try {
		if (obj.isDisabled) {return;}
		
		obj.focus()
		if (obj.tagName == "SELECT") {return}
		// We do this create range business because in certain conditions (I don't really know why), the
		// text box will have the focus, but the user won't see the cursor.
		var o = obj.createTextRange()
		o.moveEnd("character", -(obj.value.length))
		o.select()
	}
	catch (any) {}
}

function OpenNewWindow(URL) {
   if (URL.indexOf("FramesNav.aspx") >= 0) {
        var re = new RegExp("&","g");
        URL = URL.replace(re, "%26")
	}
	
	var regExp = new RegExp("^/([^/]+)/");
	var webShare = (regExp.test(location.pathname)) ? "/" + RegExp.$1 + "/" : "";
	
    var topFrame = (this.top != null) ? this.top : this;
    
    var win = window.open(GetBlankPage(), "_blank", "toolbar=no,resizable=yes,location=no,scrollbars=yes,height=100,width=100,top=" + topFrame.screenTop + ",left=" + (topFrame.screenLeft + 10))
    win.document.open()
    win.document.writeln("<body><img id='imgComputerWorking' src='" + webShare + "images/computer_working.gif'></body>")
    win.document.close()
    
    win.document.location.href = URL
    
}

function GridOnLoad(GridName) {

    DataDiv = document.getElementById(GridName + "_DataDiv")
    HeaderDiv = document.getElementById(GridName + "_HeaderDiv")
    DataTable = document.getElementById(GridName + "_DataTable")
    HeaderTable = document.getElementById(GridName + "_HeaderTable")
    ContainerDiv = document.getElementById(GridName + "_DataGridContainer")     
    TabDiv = ContainerDiv.parentNode
    
    //TabDiv.style.zIndex = -1
    

    if (DataDiv.clientWidth != DataDiv.offsetWidth && DataDiv.parentNode.align == "center") {
        DataDiv.style.width = DataTable.clientWidth + 16 + 3
        HeaderDiv.style.width = DataTable.clientWidth + 2
        HeaderDiv.style.left = -8
    }
    // We set the borderColor to white on the server so you don't see a ghost frame of the table.
    // Set it to LightGrey here.
    
    // HeaderTable and DataTable might be NULL if there's no data.
    //if (DataTable != null) {DataTable.borderColor="LightGrey"}    
    //if (HeaderTable != null) {HeaderTable.borderColor="LightGrey"}
    
}

function ToggleVisibility(obj) {

    try {
        if (obj.style.visibility == "hidden") {obj.style.visibility = "visible"}
	    else {obj.style.visibility = "hidden"}
	}
	catch (any) {}
}

function show_clock(Dest) {
	newWindow=window.open(GetBlankPage(),'Clock','width=420,height=140,status=no,resizable=no,top=225,left=175'); 
	newWindow.location='../time.asp?Dest='+Dest;
	if( typeof newWindow != 'unknown'){
  		newWindow.focus();
  	}
}



function DisplayMenu(sender) {
   whichDiv=event.srcElement;
   sender.style.leftPos+=10;
   sender.style.visibility="visible";   
   sender.setCapture();
}

function SwitchMenu() {   

   srcElement=event.srcElement;
   if (srcElement.className=="MenuItem") {
      srcElement.className="HighlightItem";
      document.forms[0].style.cursor = "hand";
   } else if (srcElement.className=="HighlightItem") {
      srcElement.className="MenuItem";
      document.forms[0].style.cursor = "auto";
   }
}
function ClickMenu(sender) {


  sender.releaseCapture();
  sender.style.visibility="hidden";
  eval(event.srcElement.eventArgs)


}

function DefaultCursor(obj) {

    obj.style.cursor = "auto";
}

function ExecTabClick(tabClicked, PageID, ElemID, sQuery) {

    var tabs;
    var i;
    var parent;
   
    if (tabClicked == null) {return}
    parent = tabClicked.parentElement
    tabs = parent.childNodes

    for (i = 0; i < tabs.length; i++) {               
        if (tabs[i].id == tabClicked.id) {tabs[i].className = "tab_Active"}
        else if (tabs[i].className == "tab_Active") {tabs[i].className = "tab_Left"}
    }
    document.frames("frame_" + ElemID).location.href = "Execform.aspx?ID=" + PageID + sQuery;
}

function ConfirmAndRedirect(message, sURL) {
	bConfirm = (confirm(message));
	if (!bConfirm) return false;
	else{
		Redirect(sURL);
	}
}	

//[22]
// Get the specified cookie
function GetSubCookie(sCookie, sSubKey) {

  // get an array of cookies.
  var cookies = document.cookie.split(";");
  for (var i=0; i < cookies.length; i++)  {
    // if this is the cookie we're looking for.
    if (trim(cookies[i]).indexOf(sCookie) == 0) {
        // now get an array of sub cookies.  At this point, the 
        // cookie will look like: "MyCookie=SubCookieA=1&SubCookieB=2"
        var subCookies = cookies[i].replace(sCookie + "=", "").split("&");
        for (var j=0; j < cookies.length; j++) {
            if (trim(subCookies[j].split("=")[0]) == trim(sSubKey)) {
                return subCookies[j].split("=")[1]
            }
        }
    }
 }   
    
  return null;
}


function checkLength(textArea, maxLength)
{
	/* Checks the max allowed length of a text area. If too long, truncates the value in the text area */
	if (textArea.value.length > maxLength)
	{
		textArea.value = textArea.value.substring(0, maxLength);
	}
}



//============================================= Start Progress Bar =========================================================

function createBar() {
  doCreateBar(200,15,1,85,7,3,'',500, 300) 
}

function doCreateBar(width,height,borderWidth,speed,blocks,count,action){

var N=-1;
var top = "expression(parentNode.offsetHeight/2);"
var t = '<div id=progressBarDiv align=center style="width:100%;height:100%;">'
t += '<span style="font-size:8pt;font-family:Verdana;top;position:relative;top:'+top+'">Please wait.....</span>'
t += '<DIV class="progressBar" '
t += 'id="_xpbar'+(++N)+'" '
t += 'STYLE="visibility:visible; overflow:hidden; width:'+width+'px; height:'+height+'px; '
t += 'border-width:' + borderWidth +'px; '
t += 'border-style:solid; '
t += 'font-size:1px;'
t += 'POSITION:relative; '
t += 'top:' + top + '">'
	
	


t +='<span id="blocks'+N+'" style="left:-' + (height*2+1) + 'px; position:absolute; font-size:1px">';

for(i=0;i<blocks;i++) {
    t+='<span class="progressBar" style="left:-'+((height*i)+i)+'px; font-size:1px; position:absolute; width:'+height+'px; height:'+height+'px; '
    t+='filter:alpha(opacity='+(100-i*(100/blocks))+')'
    t+='"></span>';
}
t+='</span></div></div>';
document.write(t);
var bA=document.all['blocks'+N]
bA.bar=document.all['_xpbar'+N]
bA.blocks=blocks;
bA.N=N;
bA.width=width;
bA.height=height;
bA.speed=speed;
bA.ctr=0;
bA.count=count;
bA.action=action;
bA.togglePause=togglePause;
bA.showBar=function(){
this.bar.style.visibility="visible";
}
bA.hideBar=function(){
this.bar.style.visibility="hidden";
}
bA.tid=setInterval('startBar('+N+')',speed);
return bA;
}

function startBar(bn){
var t=document.all['blocks'+bn]
if(parseInt(t.style.left)+t.height+1-(t.blocks*t.height+t.blocks)>t.width){
t.style.left=-(t.height*2+1)+'px';
t.ctr++;
if(t.ctr>=t.count){
eval(t.action);
t.ctr=0;
}}else t.style.left=(parseInt(t.style.left)+t.height+1)+'px';
}

function togglePause(){
if(this.tid==0){
this.tid=setInterval('startBar('+this.N+')',this.speed);
}else{
clearInterval(this.tid);
this.tid=0;
}}

function togglePause(){
if(this.tid==0){
this.tid=setInterval('startBar('+this.N+')',this.speed);
}else{
clearInterval(this.tid);
this.tid=0;
}}

//============================================= End Progress Bar =========================================================


//============================================= Start "The YSI.NET" Progress Bar ===========================================
function ProgressbarShow(myBarId) {
	var timerElement = document.getElementById("progressbarTimerId");
	if (timerElement == null) {
		timerElement = document.createElement("input");
		timerElement.type = "hidden";
		timerElement.id = "progressbarTimerId";
		timerElement.value = 0;
		document.appendChild(timerElement);
	}
	
	if (timerElement.value != 0) { /* There's already a progress bar about to show. just exit */ return; }
	
	/* Set the progressbar to show after 6 seconds */
	timerElement.value = setTimeout("ProgressbarShowDiv()", 6000);
}


function ProgressbarShowDiv(myBarId) {
	if (myBarId == null || myBarId == "") {
		myBarId = "DefaultProgressbar";
	}
	
	var myBar = ProgressbarGetDiv(myBarId);
	var myImage = ProgressbarGetImageElement(myBarId);
	if (myBar == null) return;
	
	var timerElement = document.getElementById("progressbarTimerId");
	if (timerElement != null) { timerElement.value = 0; }
	
	myBar.style.visibility = "visible";
	
	myBar.style.top  = ( Math.round( (document.body.offsetHeight - myBar.clientHeight) / 2) ) + "px";
	myBar.style.left = ( Math.round( (document.body.offsetWidth - myBar.clientWidth) / 2) ) + "px";
	
	/* Hack to prevent <select> elements (DropDowns) show through the <div> element */
	var blankHtm = GetBlankPage();
	myBar.insertAdjacentHTML("beforeBegin", '<iframe style="position:absolute;z-index:99998;filter:alpha(opacity=0);" src="' + blankHtm + '" frameBorder="0" scrolling="no" id="' + myBarId + '_hvrShm" />');
	var iframeShim = ProgressbarGetIFrame(myBarId);
	iframeShim.style.top = myBar.style.top;
	iframeShim.style.left = myBar.style.left
	iframeShim.style.width = myBar.offsetWidth;
	iframeShim.style.height = myBar.offsetHeight;
	
	/* Hack to get the animated gif going again. For some reason it wouldn't run when making the progress bar div visible after being hidden */
	var imageSrc = myImage.src;
	myImage.src = "";
	myImage.src = imageSrc;
}

function ProgressbarHide(myBarId) {
	var timerElement = document.getElementById("progressbarTimerId");
	if (timerElement != null) {
		clearTimeout(timerElement.value);
		timerElement.value = 0;
	}
	
	if (myBarId == null || myBarId == "") {
		myBarId = "DefaultProgressbar";
	}
	
	var myBar = ProgressbarGetDiv(myBarId);
	if (myBar == null) return;
	myBar.style.visibility = "hidden";
	
	var myIFrame = ProgressbarGetIFrame(myBarId);
	if (myIFrame != null) {
		/* If the progress bar was never shown (ex. the delayed showing of the progress bar was cancelled before ProgressbarShowDiv() was invoked),
		   then myIFrame will be null as ProgressbarShowDiv() adds it to the document */
		myIFrame.style.visibility = "hidden";
	}
}

function ProgressbarMoveTo(myBarId, x, y) {
	var myBar = ProgressbarGetDiv(myBarId);
	if (myBar == null) return;
	
	myBar.style.top = y + "px";
	myBar.style.left = x + "px";
}

function ProgressbarGetDiv(myBarId) {
	return document.getElementById(myBarId);
}

function ProgressbarGetIFrame(myBarId) {
	return document.getElementById(myBarId + "_hvrShm");
}

function ProgressbarGetImageElement(myBarId) {
	return document.getElementById(myBarId + "_Image");
}

//============================================= End "The YSI.NET" Progress Bar =============================================



function ysiDoPostBack(eventTarget, eventArgument)
{
	/* this function acts as a replacement for .NET's __doPostBack function.
	 * Rumor has it that __doPostBack can be overridden in .NET 2.x. If true, this should be replaced when we move to .NET 2.0 */

	var RequestActionControl = document.getElementById("RequestAction");
	if (RequestActionControl != null) {
		RequestActionControl.value = "AutoPostBack";
	}
	
	var bSave = document.getElementById("BSAVE");
	if (bSave != null)
	{
		bSave.value = 1;
	}
	
    ProgressbarShow();
	
	return __oldDoPostBack (eventTarget, eventArgument);
}

function ExitForm4ASPX()
{
	/* version of ysilib.ExitForm for ASPX pages */
	
	/* this routine will prompt if user has changed data without saving
	 * Caller should set BSAVE = 1 if he wants to bypass this routine */

	if ( document.getElementById("BDATACHANGED") == null ) {return}
	if ( document.getElementById("BSAVE") != null && document.getElementById("BSAVE").value == "1")
	{
		document.getElementById("BSAVE").value = "0";
		return;
	}
	
	try
	{
		/* put this in try-catch because page might not have finished loading in which case querying document.activeElement result in an 'htmlfile: Unspecified error' */
		if (typeof(document.activeElement.href) != "undefined")
		{
			if (document.activeElement.href.indexOf("Lookup2") > 0)              {return}
			if (document.activeElement.href.indexOf("show_calendar") > 0)        {return}
			if (document.activeElement.href.indexOf("OpenNewWindow") > 0)        {return}
			if (document.activeElement.href.indexOf("MessageHandlerSelect") > 0) {return}
		}
	}
    catch (any)
    {
    	return;
    }
	
	/* trigger an onBlur, which will trigger the BDATACHANGED, in case they made a change without leaving the control */
	if ( typeof(document.activeElement) != "undefined" && typeof(document.activeElement.name) != "undefined" )
	{
		document.activeElement.blur();
	}
	
	if ( document.getElementById("BDATACHANGED").value == "1" )
	{
		event.returnValue="Your data has NOT been saved!";
	}
}

function DoCancel(obj) {

  
    var bDevMode = (document.all("bDevMode").value == "true")
    // If it's not the main window, always close it.
    // If it's developer mode, then don't close it 
    
    /* Check if data changed and is unsaved */
    var bDataChanged = document.getElementById("BDATACHANGED");
    bDataChanged = (bDataChanged == null) ? 0 : bDataChanged.value;
   
    //if (typeof(parent.document.frames["filter"]) == "undefined" || (bDevMode && opener != null)) {
    if (opener != null) {
        
        // opener shouldn't be nothing here, but just in case...
            if (opener != null) {
        	if (opener.document.all('RequestAction') != null) {
            	opener.document.all('RequestAction').value = "Refresh";
            }
            opener.document.forms[0].submit(); 
        }
        window.close()
        return;
    }
  
  
    if (obj.innerText == "Close" && !bDevMode) {
        // They're not in edit mode, so just go home.
        parent.Home()
    }
    else {
        // Just submit the form.  This will throw away the changes and go back to readonly mode.
        if (opener != null) {
           if (opener.document.all("RequestAction") != null) {
             document.all("RequestAction").value = "Cancel"; 
           }
        }
        document.forms[0].submit()
    }  
}

function MonthDiff (dtStart, dtEnd){
	// Receives Dates (NOT objects) and returns the difference in integer. Based on PromptTerm in ysilib.js
	//Only looks at whole months, not part of

  iStartM = dtStart.getMonth() + 1
  iEndM = dtEnd.getMonth() + 1  

  iStartY = dtStart.getFullYear();
  iEndY = dtEnd.getFullYear();

  iDiff = ((iEndY - iStartY) * 12) + (iEndM - iStartM);

  if (iDiff < 0) {iDiff = -1;}  
  
  return iDiff;
}

function FilterHelp4Aspx(parm,link)
{
	if (link != "true") {
	  newWindow = window.open('../fltrhelp.asp?sfile=' + parm + '&link=' + link,'newWin','toolbar=yes,resizable=yes,location=yes,scrollbars=yes,width=450,height=550,name=FltrHelp')

	  if( typeof newWindow != 'unknown'){newWindow.focus();}
	}
	else {
	  location.href = "../fltrhelp.asp?sfile=" + parm + "&link=" + link
	}
 return newWindow;
}

function CloseMeAndRefreshOpener() {
	if (opener == null) return;
	if (typeof(opener.document.all['RequestAction']) != 'undefined') {
		opener.document.all('RequestAction').value = 'Refresh';
		opener.document.forms[0].submit();
	}
	window.close();
}

function CloseMeAndGoHome() {
	var regExp = new RegExp("^/([^/]+)/");
	var webShare = (regExp.test(location.pathname)) ? RegExp.$1 : "";
	
	if (opener == null) {
		parent.location.href = location.protocol + "//" + location.hostname + "/" + webShare + "/pages/menu.aspx";
		return;
	}
	
	opener.parent.location.href = location.protocol + "//" + location.hostname + "/" + webShare + "/pages/menu.aspx";
	window.close();
}

function ProrateCalc() {
  AspWindow = window.open('../functions/Proration_Calc.asp','AspWindow','toolbar=no,resizable=no,location=no,scrollbars=no,top=10,left=10,height=100,width=400,alwaysraised=yes');
}

// called from menuscript.js TR#68468
function OpenNewWindowVista(URL) {
   if (URL.indexOf("FramesNav.aspx") >= 0) {
        var re = new RegExp("&","g");
        URL = URL.replace(re, "%26")
	}
	
	var regExp = new RegExp("^/([^/]+)/");
	var webShare = (regExp.test(location.pathname)) ? "/" + RegExp.$1 + "/" : "";
	
    var topFrame = (this.top != null) ? this.top : this;
    
    //var win = window.open("about:blank", "_blank", "toolbar=no,resizable=yes,location=no,scrollbars=yes,height=100,width=100,top=" + topFrame.screenTop + ",left=" + (topFrame.screenLeft + 10))
    var win = window.open(GetBlankPage(), "_blank", "toolbar=no,resizable=yes,location=no,scrollbars=yes,height=600,width=1015,top=50,left=5");
    win.document.open()
    win.document.writeln("<body><img id='imgComputerWorking' src='" + webShare + "images/computer_working.gif'></body>")
    win.document.close()
    win.document.location.href = URL
    
}


function UpdateGridTotals(obj, validator, numericPrecision) {
	var newValue;
	var orgValue = obj.orgValue;
	
	/* Get the new value as a number (integer or double) */
	switch (validator) {
		case 4:		/* Currency */
			newValue = IsValidCurrency(obj.value);
			if (newValue == null || isNaN(newValue)) { newValue = 0 }
			break;
		case 5:		/* Integer */
			newValue = parseInteger(obj);
			if (newValue == false) { newValue = 0 }
			break;
		case 6:		/* Double */
			newValue = parseNum(obj, numericPrecision)
			if (newValue == false) { newValue = 0 }
			break;
	}
	
	/* Get our data column name */
	var reDataColName = new RegExp("^(.+)_DataTable_row\\d+_([a-zA-Z\\d]+)$");
	
	if ( ! reDataColName.test(obj.id) ) {
		return;
	}
	
	var gridName = RegExp.$1;
	var dataColName = RegExp.$2;
	
	/* Get Totals span tag */
	var totalsSpanName = gridName + "_DataTable_row_Totals_" + dataColName;
	var totalSpan = document.getElementById(totalsSpanName);
	
	if (totalSpan != null) {
		var total;
		
		switch (validator) {
			case 4:		/* Currency */
				total = IsValidCurrency(totalSpan.innerHTML);
				total = total - orgValue + newValue;
				totalSpan.innerHTML = FormatCurrency(total);
				break;
			case 5:		/* Integer */
				var objTotal = document.createElement('input');
				objTotal.value = totalSpan.innerHTML;
				total = parseInteger(objTotal);
				objTotal.value = total - orgValue + newValue;
				formatInteger(objTotal);
				totalSpan.innerHTML = objTotal.value;
				break;
			case 6:		/* Double */
				var objTotal = document.createElement('input');
				objTotal.value = totalSpan.innerHTML;
				total = parseNum(objTotal, numericPrecision)
				total = total - orgValue + newValue;
				totalSpan.innerHTML = FormatCurrency(total);
				break;
		}
	}
	
	obj.orgValue = newValue;
}


var tabLeftMargin = 10;
function TabClick4Aspx2(tabClicked, target) {
	if (tabClicked == null) {return}
	
	var rowClicked = tabClicked.parentElement;
	if (rowClicked == null) {return}
	
	var tabStrip = rowClicked.parentElement;
	if (tabStrip == null) {return}
	
	var tabStripName = tabStrip.id;
	var oldTab = null;
	
	if (document.getElementById(tabStripName + "_ActiveCell").value != "") {
		oldTab = document.getElementById(document.all(tabStripName + "_ActiveCell").value);
	}
	
	if (oldTab != null) {
		oldTab.className = "TabStripCell";
	}
	
	tabClicked.className = "TabStripActiveCell";
	
	var rowCount = tabStrip.children.length;
	if (rowCount > 1) {
		formatMultiLineTabstrip(tabStrip, rowClicked);
	} else {
		formatSingleLineTabstrip(tabStrip);
	}
	
	/* hide old tab and make new tab visible */
	var top = parseInt(tabStrip.offsetTop) + tabStrip.offsetHeight + 3;
	
	var divs = document.body.getElementsByTagName("DIV");
	for (var i = 0; i < divs.length; i++) {
		if (divs[i].className == "TabBody") {
			if (divs[i].id == target) {
				divs[i].style.visibility = "visible";
				divs[i].style.display = "block"
				setActiveTabTop(divs[i], tabStrip);
				document.all(tabStripName + "_ActiveCell").ActiveTabId = divs[i].id
			} 
			// Only manipluate the top and visiblity properties if this tab is connected
			// to this tab strip.  This allows for multiple tab strips on one page.
			else if (tabStrip.tabIds == null || tabStrip.tabIds.indexOf(divs[i].id + "^") >= 0) {
				divs[i].style.top = top;
				// This is to get around an apparent bug.  If we don't have this line,
				// then a ghost frame of the hidden tables shows up on the visible div.
				divs[i].style.visibility = "inherit";
				divs[i].style.visibility = "hidden"
				divs[i].style.display = "none"
			}
		}
	}
	
	document.all(tabStripName + "_ActiveCell").value = tabClicked.id; 
}


function formatMultiLineTabstrip(tabStrip, rowClicked) {
	/* rearrange rows to make row containing the current tab the bottom most and set width for each cell */
	var tabStripName = tabStrip.id;
	var rowCount = tabStrip.children.length;
	var rowIndex = 0;
	
	while (rowIndex < rowCount) {
		var row = tabStrip.children[rowIndex];
		if (row.className == "TabStripRow") {
			if (row == rowClicked) {
				/* if the row clicked is not the bottom (foremost), we need to move it */
				tabStrip.removeChild(row);
				tabStrip.appendChild(row);
				
				row.id = tabStripName + "_row_" + (rowCount - 1);
				row.style.top = ((rowCount - 1) * row.firstChild.clientHeight) + "px";
				
				tabStrip.children[rowIndex].id = tabStripName + "_row_" + (rowIndex - 1);
				tabStrip.children[rowIndex].style.top = ((rowIndex - 1) * row.firstChild.clientHeight) + "px";
				++rowIndex;
			} else {
				row.id = tabStripName + "_row_" + (rowIndex - 1);
				row.style.top = ((rowIndex - 1) * row.firstChild.clientHeight) + "px";
				++rowIndex;
			}
		}
	}
	
	/* Format tabs. Set widths */
	var cellWidth = new Array(rowCount);
	var rowWidth = new Array(rowCount);
	var maxRowWidth = 0;
	for (var i = 0; i < rowCount; i++) {
		var row = tabStrip.children[i];
		if (row.className == "TabStripRow") {
			var cellCount = row.children.length;
			
			cellWidth[i] = new Array(cellCount);
			var runningRowWidth = 0;
			
			for (var j = 0; j < cellCount; j++) {
				cellWidth[i][j] = (row.children[j].tabWidth > -1) ? parseInt(row.children[j].tabWidth, 10) : row.children[j].offsetWidth + 20;
				runningRowWidth += cellWidth[i][j];
			}
			
			rowWidth[i] = runningRowWidth;
			if (runningRowWidth > maxRowWidth) { maxRowWidth = runningRowWidth; }
		}
	}
	
	/* Set cell widths */
	for (var i = 0; i < rowCount; i++) {
		var row = tabStrip.children[i];
		if (row.className == "TabStripRow") {
			var cellCount = row.children.length;
			
			var remainingRowWidth = maxRowWidth;
			var sortedCellIndexByWidth = sortCellIndexByWidth(cellWidth[i]);
			
			for (var j = 0; j < cellCount; j++) {
				var avgCellWidth = Math.round(remainingRowWidth / (cellCount - j));
				var cell = row.children[ sortedCellIndexByWidth[j] ];
				
				if (cell.tabWidth > -1) {
					cell.style.width = (cell.tabWidth) + "px";
				}else if (cell.offsetWidth > avgCellWidth) {
					remainingRowWidth -= cell.offsetWidth;
					cell.tabWidth = cell.offsetWidth;
				} else {
					cell.style.width = (avgCellWidth) + "px";
					cell.tabWidth = avgCellWidth;
					remainingRowWidth -= avgCellWidth;
				}
			}
		}
	}
	
	var maxTabsPerRow = tabStrip.maxTabsPerRow;
	/* Set cell lefts and top */
	for (var i = 0; i < rowCount; i++) {
		var row = tabStrip.children[i];
		if (row.className == "TabStripRow") {
			row.firstChild.style.width = (row.firstChild.tabWidth + (i)*2) + "px";
			row.firstChild.style.marginLeft = (tabLeftMargin + 2 * (rowCount - i)) + "px";
			row.lastChild.style.width = (row.lastChild.tabWidth+ (i)*2) + "px";
			setTabCellPositions(row, maxTabsPerRow, false);
			row.style.height = (row.firstChild.clientHeight + 2) + "px";
			row.style.borderBottom = "";
		}
	}
	
	if (tabStrip.lastChild != null) {
		tabStrip.lastChild.style.borderBottom = "solid black 1px";
		var tabHeight = parseInt(tabStrip.lastChild.offsetHeight, 10) + parseInt(tabStrip.lastChild.offsetTop, 10) + 5;
		tabStrip.style.height = tabHeight + "px";
	}
}


function formatSingleLineTabstrip(tabStrip) {
	var maxTabsPerRow = tabStrip.maxTabsPerRow;
    /* Set cell lefts and top */
	var row = tabStrip.children[0];
	if (row.className == "TabStripRow") {
		for (var i = 0; i < row.children.length; i++) {
			if (row.children[i].tabWidth < 0) {
				row.children[i].tabWidth = row.children[i].offsetWidth + 10;
			}
			if (row.children[i].tabWidth.toString().indexOf("%") > 0) {row.children[i].style.width = row.children[i].tabWidth}
			else {row.children[i].style.width = row.children[i].tabWidth + "px";}
		}
		
		row.firstChild.style.marginLeft = tabLeftMargin + "px";
		setTabCellPositions(row, maxTabsPerRow, true);
		row.style.height = (row.firstChild.clientHeight + 2) + "px";
		row.style.borderBottom = "";
	}
    
    if (tabStrip.lastChild != null) {
    	tabStrip.lastChild.style.borderBottom = "solid black 1px";
		var tabHeight = parseInt(tabStrip.lastChild.offsetHeight, 10) + parseInt(tabStrip.lastChild.offsetTop, 10) + 5;
		tabStrip.style.height = tabHeight + "px";
	}
}


function sortCellIndexByWidth(myArray) {
	var sortedArray = new Array(myArray.length);
	for (var i = 0; i < sortedArray.length; i++) {
		sortedArray[i] = myArray[i];
	}
	sortedArray = sortedArray.sort(descSortNumber);
	var sortedIndex = new Array(sortedArray.length);
	
	for (var i = 0; i < sortedArray.length; i++) {
		for (var j = 0; j < sortedArray.length; j++) {
			if (myArray[i] == sortedArray[j]) {
				if (sortedIndex[j] == null) {
					sortedIndex[j] = i;
					break;
				}
			}
		}
	}
	return sortedIndex;
}


function descSortNumber(a, b) {
	return b - a;
}


function setTabCellPositions(tabRow, maxTabs, isSingleRowTab) {
	/* loop over the "cells" in the row */
	for (var i = 1; i < tabRow.children.length; i++) {
		var cell = tabRow.children[i];
		var borderLeftWidth = 0
		if (parseInt(tabRow.children[i - 1].currentStyle.borderLeftWidth, 10).value != undefined) {borderLeftWidth = parseInt(tabRow.children[i - 1].currentStyle.borderLeftWidth, 10)}
		var positionInPixel = tabRow.children[i - 1].offsetLeft + tabRow.children[i - 1].offsetWidth - borderLeftWidth;
		
		/* hack for last row that might have less than maxTab tabs */
		if (( ! isSingleRowTab ) && (i == (tabRow.children.length - 1)) && (i < maxTabs - 1)) {
			positionInPixel -= (maxTabs - tabRow.children.length);
		}
		
		if (isSingleRowTab) {
			positionInPixel += 2;
		}
		
		cell.style.left = positionInPixel + "px" ;
	}
}


function setActiveTabTop(tab, tabStrip) {
	if (tab.style.position == "relative") {tab.style.top = "0px"}	
	else (tab.style.top = (tabStrip.offsetTop + tabStrip.offsetHeight + 3) + "px");
}


function TabDblClick4Aspx2(tabClicked, target) {
	if (tabClicked == null) {return}
	
	var rowClicked = tabClicked.parentElement;
	if (rowClicked == null) {return}
	
	var tabStrip = rowClicked.parentElement;
	if (tabStrip == null) {return}
	
	if (tabStrip.originalTop == null) {
		/* Grid not prepared for min max. Just exit */
		return;
	}
	
	var tabStripOriginalTop = parseInt(tabStrip.originalTop, 10);
	
	var tabStripHeaderPanelName = tabStrip.headerPanel;
	var tabStripHeaderPanel = document.getElementById(tabStripHeaderPanelName);
	if (tabStripHeaderPanel == null) {return}
	
	var titleElement = document.getElementById("TitleBar_PageTitleBar");
	
	var tabStripNewTop;
	var offset;
	if (tabStrip.offsetTop == tabStripOriginalTop) {
		/* we're going to maximize the tab */
		tabStripNewTop = titleElement.offsetTop + titleElement.offsetHeight + 25;
		offset = tabStrip.offsetTop - tabStripNewTop;
		tabStripHeaderPanel.style.visibility = "hidden";
		
	} else {
		/* we're going to restore the tab position */
		tabStripNewTop = tabStripOriginalTop;
		offset = tabStrip.offsetTop - tabStripNewTop;
		tabStripHeaderPanel.style.visibility = "visible";
	}
	
	/* increase tab heights */
	var activeTab;
	var divs = document.body.getElementsByTagName("DIV");
	for (var i = 0; i < divs.length; i++) {
		if (divs[i].className == "TabBody") {
			if (divs[i].style.visibility == "visible") {
				activeTab = divs[i];
			}
			divs[i].style.height = (divs[i].offsetHeight + offset) + "px";
		}
	}
	
	tabStrip.style.top = (tabStrip.offsetTop - offset) + "px";
	setActiveTabTop(activeTab, tabStrip);
	
	if (document.selection) {document.selection.empty()}
}

