var g_bDataChanged = false;	//Set to true when the SetData function of the XML is called
var g_bPostReady = false;	//Set to true when PostReady is called by the page
var g_sSaving = false;		//Set to true when the data is about to be posted
var gs_FirstFocus = null;
var gb_PageBack = false;
var g_sRepostClientKey  = "ClientRePostCheck";
var g_sRepostKey		= "RePostCheck";
var g_sRepostCookieKey  = "RePostCheck_Cookie";
var g_sRePostCheck_History = "RePostCheck_History";
var g_sDisabledMsgId = "DisabledMessage";
var g_sCheckDirtyFlag = true;
var gb_CoverDateExists = false;
var gs_Holder = null;
var g_sDisplayGridRowData = "";
var g_sDisplayGridFieldDataList = "";
var gb_AllowMultipleWindow = false;

function IsFilmAndTape()
{
	var oFlag = document.getElementById( "IsFilmAndTape" );
	
	if( oFlag == null )
		return false;
	else
		return eval(oFlag.value);
}

function BypassChecks()
{
	g_sSaving = true;
}

//oDoc ( optional ) if the document window to be submitted
function FormSubmit(oDoc)
{
	if( oDoc ) 
	{
		setRepostCheck(oDoc);
		oDoc.forms[0].submit();
	}
	else
	{
		setRepostCheck();
		if ( arguments.length > 1 )
			__doPostBack(arguments[1], arguments[2]);
		else
			document.forms[0].submit();
	}
}



function SetPageBack(pageBack)
{
	gb_PageBack = pageBack;
}

function IsPageBack()
{
	return gb_PageBack;
}

function ShowProcessMessage()
{
	ShowFrameMessage(PROCESSING_MESSAGE);
}

function ShowActionMessage(actionType)
{
	if( actionType == 'reset' ) return;
	if(actionType == 'nomessage') return;
	
	/*if( actionType == 'save' )
		ShowFrameMessage(SAVING_MESSAGE);
	else if( actionType == 'reset' )
		ShowFrameMessage(WINDOW_LOADING_MESSAGE);
	else*/
	ShowFrameMessage(PROCESSING_MESSAGE);
}

function RefreshParentWindow(checkFieldID, checkFieldValue)
{
	if( isCachedPage() ) return;
	
	var oForm = null;
	var oDoc = null;
	var oField = null;
	var oFocusCheckField = null;
	
	try
	{
		oDoc = window.opener.document;
		oForm = oDoc.forms[0];
		oFocusCheckField = oDoc.getElementById("FocusOnItemCheck");
		oField = oDoc.getElementById(checkFieldID);
	}
	catch(e)
	{
		return; //exit if the opener window does not exist;
	}
	
	try
	{
		if( oField && oField.value.toLowerCase() == checkFieldValue.toLowerCase() )
		{
			if( oFocusCheckField ) oFocusCheckField.value = "False";
			var oNewHidden = oDoc.createElement("<input type='hidden' name='DoPageRefresh' value='true'>");
			oForm.appendChild(oNewHidden);
			FormSubmit(oDoc);
		}
	}
	catch(e){}
}

function ShowFrameMessage(msg, topPosition)
{
	var oFrame = document.getElementById( "ProcessingFrame" );
	
	if( oFrame )
	{
		var oSpan = oFrame.contentWindow.document.getElementById('message');
		var iCenterPos	  = window.document.body.clientWidth / 2;
		var iFrameWidth   = eval(oFrame.style.width.replace( /px/, ""));
		var iLeftPos	  = iCenterPos - iFrameWidth / 2;
			
		
		if( topPosition )
			oFrame.style.top = topPosition;
		else
			oFrame.style.top = "100";
			
		oFrame.style.left = iLeftPos;
		oFrame.style.display = 'inline';
		oFrame.focus();
		oSpan.innerText = msg;
	}
}
			
//Called every time the page finishes loading
function onPageLoad()
{	
	//Attach to the onsubmit event of the page form
	if( document.forms.length > 0 )
	{
		if( isCachedPage() ) document.forms[0].reset();
		document.forms[0].attachEvent("onsubmit", onFormSubmit);
	}
	
	 SetInputFocus();
}

function GetUniqueURL( url )
{
	var today = new Date();
	
	if( url.indexOf( "?" ) == -1 )
		url = url + "?timestamp=" + today.getTime();
	else
		url = url + "&timestamp=" + today.getTime();

	return url;
}

function CancelAddNew()
{
	var oHidden = document.getElementById( "IsNewRecord" );
	if( oHidden && oHidden.value == 'true' )
	{
		oHidden.value = 'false';
	}
}

function IsNewRecord()
{
	var oHidden = document.getElementById( "IsNewRecord" );
	if( oHidden && oHidden.value == 'true' )
		return true;
	else
		return false;
}

function PendingChanges()
{
	if( IsNewRecord() && !g_bPostReady )
		return true;
	else if (g_bDataChanged && !g_bPostReady)
		return true;
	else
		return false;
}

//Fired automatically prior to the form being submitted
//NOTE: if the submit() function of the form gets called explicitly
//this event will not fire. You SHOULD call CanSubmit() prior to submiting a form
function onFormSubmit()
{
	if( !CanSubmit() ) 
		event.returnValue = false;
}

//Checks to see if data has changed 
//If data has changed, and there is a click button on the page
//Executes the "Save Click" event which results in a page refresh
//
//PARAMETERS: cancelAddNew ( optional, default = true ) clears the new record flag
//			  in general, cancelAddNew will be set to false on "reset" operations

function CanSubmit(cancelAddNew)
{
	// if there is no save button there is no reason to check whether to save so returns a true
	if ( ! HasSaveButton() )
		return true;
	
	//Be Pessimistic
	var bCanSubmit = false;
	var iResponse = -1;
	
	//alert( "DataChanged=" + g_bDataChanged + " pending Changes=" + PendingChanges() + " IsNewRecord=" + IsNewRecord() + " Saving=" + g_sSaving );

	var bCancelAddNew = (cancelAddNew == null) ? true : cancelAddNew;
	
	//If it is safe to link to a new page, exit
	if ( !PendingChanges() || g_sSaving || !g_sCheckDirtyFlag) return true;
		
	//Show Save confirmation dialog
	iResponse = ShowCanSubmitConfirm(OKCANCEL_BUTTONS);
	
	switch( iResponse )
	{
		//OK -- DO NOT Save Changes
		case 0:
			if( bCancelAddNew ) CancelAddNew();
			bCanSubmit = true;
			//g_sSaving = false;
			break;
			
		//ELSE Returns False
	}
	
	return bCanSubmit;
}

// this checks to see if the save button exists.
function HasSaveButton()
{
	var oSave = GetActionButton("save");
	if ( oSave == null )
	{
		return false;
	}
	return true;
}

//Same as CanSubmit() except that it accepts a URL of a page to transfer
//after executing the save operation.
//Also, unlick Can Submit(), the page gets submitted even if the user 
//does not wish to save changes.
//Returns FALSE if the user presses cancel, otherwise it will not return
function SaveAndTransfer(url, newRecord)
{	
	//Be Pessimistic
	var iResponse = -1;
	var sURL = (url == null) ? "" : url;
	var bNewRecord = (url == null ) ? false : newRecord;
	
	//alert( "DataChanged=" + g_bDataChanged + " pendingChanges=" + PendingChanges() + " IsNewRecord=" + IsNewRecord() + " Saving=" + g_sSaving );
	
	//If it is safe to link to a new page, change URL and submit
	if ( !PendingChanges() || g_sSaving || !g_sCheckDirtyFlag) 
	{
		if ( sURL == "CLOSEWINDOW" )
			window.close();
		
		document.forms[0].action = sURL;
		FormSubmit();
		return true;
	}
	
	// if it has a save button do the checks
	if ( HasSaveButton() )
	{
		//Show Save confirmation dialog
		if(newRecord)
		{
			iResponse = ShowSaveConfirm(YESCANCEL_BUTTONS);
			if( iResponse == 1 ) iResponse = -1;
		}
		else
			iResponse = ShowSaveConfirm(YESNOCANCEL_BUTTONS);
	}
	// if not then just transfer without saving.
	else
		iResponse = 1;
	
	switch( iResponse )
	{
		//YES -- Save Changes
		case 0:
			var oSave = GetActionButton("save");
			var oURL = document.getElementById("TransferURL");
			if( oURL != null ) oURL.value = sURL;
		
			//g_sSaving = true;
			oSave.click();
			break;
		
		//NO -- DO NOT Save Changes
		case 1:
			if ( sURL == "CLOSEWINDOW" )
			{
				window.close();
			}
			else
			{
				CancelAddNew();
				document.forms[0].action = sURL;
				FormSubmit();
			}
			break;
	
		//ELSE DO NOTHING
	}
	
	//This function will only return if the user presses "Cancel"
	//Otherwise it will submit the form.
	return false;
}

function ShowSaveConfirm(buttons)
{
	var sButtons = (buttons == null) ? YESNOCANCEL_BUTTONS : buttons;
	return iResponse = OpenMessage(sButtons, SAVE_CHANGES_MESSAGE, "","", 170, 260);
}
function ShowCanSubmitConfirm(buttons)
{
	var sButtons = (buttons == null) ? OKCANCEL_BUTTONS : buttons;
	return iResponse = OpenMessage(sButtons, ALERT, CAN_SUBMIT_MSG,"", 180, 300);
}


function GetActionButton( actionType )
{
	var i;
	var oSave = null;
	var aInput = document.getElementsByTagName( 'input' );
	
	for( i = 0; i < aInput.length; i++ )
	{
		if( aInput[i].ActionType && aInput[i].ActionType == actionType )
		{
			oSave = aInput[i];
			break;
		}
	}
	
	return oSave;
}

function SaveConfirm()
{
	if( GetActionButton("save") != null)
	{
		return OpenMessage(YESNOCANCEL_BUTTONS, SAVE_CHANGES_MESSAGE, "","", 170, 260);
	}
	else
	{
		return ( confirm( CANCEL_MESSAGE ) ) ? 1 : 2;
	}
}

//Checks to see if data has changed (without prompting user)
function GetDataChanged()
{
	return g_bDataChanged;
}

//Sets whether the data has changed or not
function SetDataChanged(dataChangedValue)
{	
	g_bDataChanged = dataChangedValue;
}


//Attach to the onload event
window.attachEvent("onload", onPageLoad);

//***************************************************************************
function trimString(str)
{
	//Match spaces at beginning and end of text and replace
    //with null strings
    return str.replace(/^\s+/,'').replace(/\s+$/,'');
}

function GetSelectValue(name)
{
	var sFormID = document.forms[0].id;
	
	var oSelect = eval( 'document.' + sFormID + '.' + name );
	
	if (oSelect )
	{ return oSelect.options[oSelect.selectedIndex].value;	}
	else
	{ return ''; }	
}

function GetSelectDescription(name)
{
	var sFormID = document.forms[0].id;
	
	var oSelect = eval( 'document.' + sFormID + '.' + name );
	
	if (oSelect )
	{ return oSelect.options[oSelect.selectedIndex].text;	}
	else
	{ return ''; }	
}

// this takes a string of the select name and the string of the extended property and returns the value in the property
function GetSelectExtendedValue(name, extendedProp)
{
	var sFormID = document.forms[0].id;
	
	var oSelect = eval( 'document.' + sFormID + '.' + name );
	
	if (oSelect )
	{ return eval ( 'oSelect.options[oSelect.selectedIndex].x_' + extendedProp );	}
	else
	{ return ''; }	
}

function GetSelectedRadio(name)
{
	var i = 0;
	var oRadio = null;
	var sValue = '';
	var sFormID = document.forms[0].id;
	
	do
	{
		oRadio = eval( 'document.' + sFormID + '.' + name + '_' + i );
		if( oRadio && oRadio.checked ) sValue = oRadio.value;
		i++;
	}
	while( oRadio != null );
	
	return sValue;	
}

function SaveData( confirmMessage )
{
	if( confirmMessage != null )
	{
		if ( ! confirm( confirmMessage ) )
		{
			return false;
		}
	}
	
	try
	{
		//Call post ready if there is an xml data island present
		if( document.getElementsByTagName("XML").length > 0 )
		{
			PostReady();
		}
		
		FormSubmit();
	}
	catch(e)
	{
		alert( SUBMIT_ERROR );
		return false;
	}
	return true;
}
//************************************************************************
//							Repost Check
//************************************************************************
function GetCookie(sName)
{
	var aCookie = document.cookie.split('; ');
	for (var i=0; i < aCookie.length; i++)
	{
		var aCrumb = aCookie[i].split('=');
		if (sName == aCrumb[0]) 
		return unescape(aCrumb[1]);
	}

	return null;
}

function isCachedPage()
{
	var oHidden = document.getElementById(g_sRepostClientKey); 
	var sCookie = GetCookie(g_sRepostCookieKey);
	
	var iCookieVal = (sCookie == null ) ? 0 : eval(sCookie);
	var iFormVal = (oHidden && oHidden.defaultValue != '') ? eval(oHidden.defaultValue) : iCookieVal + 1;
	//alert( "cookie:" + iCookieVal + "  Form:" + iFormVal );
	
	if( iCookieVal > iFormVal )
		return true;
	else
		return false;
}

function CheckActionControls()
{
	if( !isCachedPage()) return;
	setDisabledMsg();
	
	var aInputs = document.getElementsByTagName( 'input' );
	var aFormFrames = document.getElementsByTagName( 'div' );
	
	DisableControls(aInputs, false);
	DisableControls(aFormFrames, true);
}

function DisableControls(aControls, recursive)
{
	var i = 0;
	
	for( i = 0; i < aControls.length; i++ )
	{
		if( aControls[i].RePostCheck && aControls[i].RePostCheck == 'true' )
		{
			aControls[i].disabled = true;
			if( recursive ) RecursiveDisable(aControls[i]);
		} 
	}
}

function doNothing()
{
	event.returnValue = false;
}

function RecursiveDisable(oControl)
{
	var i = 0;
	var aInputs				= oControl.getElementsByTagName( 'input' );
	var aMultiLineInputs	= oControl.getElementsByTagName( 'multiLineInput' );
	var aMarcInput			= oControl.getElementsByTagName( 'MarcInput' );
	var aImages				= oControl.getElementsByTagName( 'img' );
	var aLinks				= oControl.getElementsByTagName( 'a' );
	var aLists				= oControl.getElementsByTagName( 'select' );
	var aTextAreas			= oControl.getElementsByTagName( 'textarea' );

	for( i = 0; i < aLists.length; i++ ) 
	{	aLists[i].disabled = true; 	}
		
	for( i = 0; i < aLinks.length; i++ ) 
	{	aLinks[i].disabled = true; aLinks[i].onclick = doNothing;}
		
	for( i = 0; i < aImages.length; i++ )
	{	aImages[i].disabled = true; }
		
	for( i = 0; i < aInputs.length; i++ ) 
	{	aInputs[i].disabled = true; }
	
	for( i = 0; i < aMultiLineInputs.length; i++ ) 
	{	aMultiLineInputs[i].disabled = true; }
		
	for( i = 0; i < aMarcInput.length; i++ ) 
	{	aMarcInput[i].disabled = true; }	
	
	for( i = 0; i < aTextAreas.length; i++ ) 
	{	aTextAreas[i].disabled = true; 
		aTextAreas[i].contentEditable = false;	}
}

//oDoc ( optional ) is the document window that contains the form 
//to be updated
function onPageFromSubmit()
{
	setRepostCheck();
}

function setRepostCheck(oDocumentObject)
{
	var today = new Date();
	var oHidden = null;

	if( oDocumentObject )
		oHidden = oDocumentObject.getElementById(g_sRepostKey); 
	else
		oHidden = document.getElementById(g_sRepostKey); 
			
	if( oHidden != null )
	{
		oHidden.value = today.getTime();
	}
}

function setDisabledMsg()
{
	message = document.getElementById(g_sDisabledMsgId);
	if(message != null) message.style.display = "inline";
}

//************************************************************************
//							xmlDataIsland
//************************************************************************
function XmlTable( DataIsland, EmptyDataIsland, DataInstance, TableName, PK, StartPKVal, PositionColumn)
{
	this.DataIsland = DataIsland;
	this.EmptyDataIsland = EmptyDataIsland;
	this.DataInstance = DataInstance;
	this.TableName = TableName;
	this.PK = PK;
	this.PositionColumn = PositionColumn;
	this.NextPKVal = StartPKVal;
	
	var DeleteBuffer = "diffgr:before";
	var RootNode = "diffgr:diffgram";
	// These are just to make constants.
	var MoveUp = true;
	var MoveDown = false;
	
	// This adds the row to the delete buffer. This will be fired on 2 occasions, update and delete.
	// no row gets actually removed from the xml.
	function AddToDeleteBuffer(CurrentRow)
	{
		// see if the delete buffer exists and how many rows are available.
		var BufferRows = DataIsland.selectNodes("//" + DeleteBuffer);
		if ( BufferRows )
		{
			var nBufferRows = DataIsland.selectNodes("//" + DeleteBuffer).length;	
		}
		else
		{
			var nBufferRows = 0;
		}
		// if there is not a delete buffer create it.
		if ( nBufferRows == 0 )
		{							
			// if not then add the delete buffer	
			var sNewXml = "<" + DeleteBuffer + " xmlns:diffgr='urn:schemas-microsoft-com:xml-diffgram-v1' xmlns:msdata='urn:schemas-microsoft-com:xml-msdata'></" + DeleteBuffer + ">";				
			var NewRow = new ActiveXObject("Microsoft.XMLDOM");
			
			NewRow.loadXML(sNewXml);	
			
			DataIsland.selectSingleNode("//" + RootNode).appendChild(NewRow.selectSingleNode("//" + DeleteBuffer));
		}
		// then add the deleted row to the buffer
		DataIsland.selectSingleNode("//" + DeleteBuffer).appendChild(CurrentRow.cloneNode(true));
	}
	
	// this removes the row from the table.  This is done for a delete and a remove function.  
	function RemoveFromDataInstance(CurrentRow)
	{
		DataIsland.selectSingleNode("//" + DataInstance).removeChild(CurrentRow);
	}
	
	// This builds the xpath for the primary key value given.
	function BuildXPath(PKVal)
	{
		var sPath = TableName + "[" + PK + " = '" + PKVal + "']";
		return sPath;
	}	
	
	function ShiftPosition( Qualifier, QualValue, Position, bMoveUp)
	{
		var xpath = "//" + DataInstance + "/" + TableName + "[";
		if ( Qualifier )
		{
			xpath +=  Qualifier + " = '" + QualValue + "' and ";
		}
		
		if ( Position == "" )
			Position = 0;
		
		xpath += PositionColumn + " >= " + Position + "]";
		var RowsToChange = DataIsland.selectNodes(xpath);
		for ( var ii=0; ii<RowsToChange.length; ii++ )
		{
			SetAction( RowsToChange(ii) );
			if ( bMoveUp == true )
			{
				RowsToChange(ii).selectSingleNode(PositionColumn).text = parseInt(RowsToChange(ii).selectSingleNode(PositionColumn).text,10) + 1;
			}
			else
			{
				RowsToChange(ii).selectSingleNode(PositionColumn).text = parseInt(RowsToChange(ii).selectSingleNode(PositionColumn).text,10) - 1;
			}
			
		}		
	}
	
	function GetLastPosition(Qualifier, QualValue)
	{
		var xpath = "//" + DataInstance + "/" + TableName ;
		if ( Qualifier )
		{
			xpath +=  "[" + Qualifier + " = '" + QualValue + "'] ";
		}
		
		return DataIsland.selectNodes(xpath).length;
	}
	
	
	
	// this clears the document of the rows that have no data in the comma delimited list passed in.
	// allRequired is to determine if all have to be blank or just one.
	this.CleanDocument = function(requiredColumnList, allRequired)
	{
		var sColumnXpath = "";
		var sColumns = requiredColumnList.split(",");
		for ( var i=0; i<sColumns.length; i++ )
		{
			if ( sColumnXpath != "" )
			{
				if ( allRequired )
					sColumnXpath += " and ";
				else
					sColumnXpath += " or ";				
			}
			sColumnXpath += sColumns[i] + " = ''";
		}
		if ( sColumnXpath != "" )
		{
			sColumnXpath = "[" + sColumnXpath + "]";
		}		
		var sTableXpath = "//" + this.DataInstance + "/" + this.TableName + sColumnXpath;
		var oRemoveNodes = DataIsland.selectNodes(sTableXpath);	
		for ( var j=0; j<oRemoveNodes.length; j++ )
		{
			RemoveFromDataInstance(oRemoveNodes(j));	
		}		
	}
	//Insert new record into DiffGram DataInstance area.
	this.Add = function( Position, Qualifier, QualValue, ZeroBased )
	{
		var nPK = this.NextPKVal;
		
		// Get a blank row.
		var NewRow = this.EmptyDataIsland.selectSingleNode("//" + this.TableName).cloneNode(true);

		// set the has changes attribute.
		NewRow.setAttribute("diffgr:hasChanges", "inserted");
		NewRow.setAttribute("msdata:rowOrder", "1");

		this.SetRowData(NewRow, PK, nPK );
	
		if ( this.PositionColumn != null )
		{	
			if ( Position == null )
			{
				Position = GetLastPosition(Qualifier, QualValue);
			}
			
			if ( ZeroBased == "false" )
				Position = parseInt(Position,10) + 1;
			
			this.SetRowData(NewRow, this.PositionColumn, Position);
			ShiftPosition(Qualifier, QualValue, Position, MoveUp);
		}
		
		// this is the case where the datasource was completely empty and no rows were present.
		if ( this.DataIsland.selectSingleNode("//" + this.DataInstance) == null )
		{
			var oRootNode = this.DataIsland.createElement(this.DataInstance);
			this.DataIsland.selectSingleNode("//" + RootNode).appendChild(oRootNode);			
		}
		
		this.DataIsland.selectSingleNode("//" + this.DataInstance).appendChild(NewRow);		
		
		this.NextPKVal--;
			
		return nPK;		
	}
	
	//Delete Record From DiffGram and put it in the delete buffer.
	this.Delete = function( PKVal, Qualifier, QualValue )
	{
		var Position = null;
		if ( this.PositionColumn != null )
		{
			Position = this.GetData( PKVal, PositionColumn);
		}
		var CurrentRow = this.GetRow(PKVal);
		
			
		// if the current row is not there it just returns.
		if (! CurrentRow )
		{
			alert(XML_ROW_ERROR + PKVal);
			return;
		}
		
		var sAction = CurrentRow.getAttribute("diffgr:hasChanges");
		if ( sAction != "inserted" )
		{
			AddToDeleteBuffer(CurrentRow);
		}
		RemoveFromDataInstance(CurrentRow);
		
		CurrentRow.setAttribute("diffgr:hasChanges", "deleted");
		
		if ( this.PositionColumn != null && this.PositionColumn != "null" && Position != null && Position != "null")
		{
			ShiftPosition(Qualifier, QualValue, Position, MoveDown);
		}
		g_bDataChanged = true;
		
		return CurrentRow;				
	}
	
	//Remove Record From DataInstance section of the DiffGram
	this.Remove = function( PKVal, Position, Qualifier, QualValue )
	{
		var CurrentRow = this.GetRow(PKVal);	
		// if the current row is not there it just returns.
		if (! CurrentRow )
		{
			alert(XML_ROW_ERROR + PKVal);	
			return;
		}
		RemoveFromDataInstance(CurrentRow);		
		CurrentRow.setAttribute("diffgr:hasChanges", "deleted");	
		
		if ( this.PositionColumn != null && Position != null )
		{
			ShiftPosition(Qualifier, QualValue, Position, MoveDown);
		}
			
		return CurrentRow;			
	}	
	
	this.DeleteColumn = function( PKVal, ColumnName )
	{
		var oRow = this.GetRow(PKVal);
		
		if ( ! oRow )
		{
			alert(XML_ROW_ERROR + PKVal);	
			return;
		}
		
		var oDeleteColumn = oRow.selectSingleNode(ColumnName);
		
		if ( oDeleteColumn != null )
		{
			SetAction(oRow);
			this.DataIsland.selectSingleNode("//" + this.DataInstance + "/" + this.TableName + "[" + this.PK + " = '" + PKVal + "']").removeChild(oDeleteColumn);
			g_bDataChanged = true;
		}
		
		return oDeleteColumn;
		
	}
	
	this.CheckEmpty = function ( ColumnName )
	{
		var oEmptyNode = EmptyDataIsland.selectSingleNode("//" + TableName + "/" + ColumnName);
		if ( oEmptyNode )
			return oEmptyNode.cloneNode(true);
		else
			return;
	}
	
	function SetAction( Row )
	{
		var Action = Row.getAttribute("diffgr:hasChanges");
		// if the has changes has not been set, then set it to blank. that means that the row has not been messed with.
		if ( Action == null)
		{
			Action = "";
		}
		
		switch (Action)
		{
			// if it is deleted, you want nothing to happen, they are passing the wrong row.
			case "deleted":
				return;
				break;
			// inserted and modifed are the same, they have already been changed and any further changes won't do anything
			case "inserted":
			case "modified":
				break;
			//no changes have been made yet, so move the original (for the db ) to the delete buffer and set action 
			// to modified.
			default:
				AddToDeleteBuffer(Row);
				Row.setAttribute("diffgr:hasChanges", "modified");
				break;
		}	
	}
	
	// this checks to see if the data in a node is empty
	this.IsEmpty = function ( PKVal, ColumnName )
	{
		var sData = this.GetData(PKVal, ColumnName);
		if ( trimString(sData) == "" )
			return true;
		
		return false;			
	}
	
	this.AllRowsContainData = function ( ColumnName )
	{
		var oRows = this.GetAllRows();
		for ( var i=0; i<oRows.length; i++ )
		{
			var sData = oRows[i].selectSingleNode(ColumnName);	
			if ( sData == null || trimString(sData.text) == "" )
			{
				return false;
			}
		}	
		return true;	
	}
	
	//Sets the value of a column
	this.SetData = function( PKVal, ColumnName, Value )
	{
		var CurrentRow = this.GetRow(PKVal);
		if ( ! CurrentRow )
		{
			alert(XML_ROW_ERROR + PKVal);
			return;	
		}
		this.SetRowData(CurrentRow, ColumnName, Value);		
		return;
	}
	// Sets the value of a column on a specific row
	this.SetRowData = function( Row, ColumnName, Value )
	{
		if (! Row.selectSingleNode(ColumnName) )
		{
			var oNewNode = this.CheckEmpty(ColumnName);
			if ( oNewNode )
			{
				Row.appendChild(oNewNode);					
			}
			else
			{
				alert(XML_COLUMN_ERROR + ColumnName);
				return;
			}
		}
		SetAction(Row);

		// change the value.
		Row.selectSingleNode(ColumnName).text = Value;	
		g_bDataChanged = true;
	}
	
	//Gets the value of a column 
	this.GetData = function( PKVal, ColumnName )
	{
		var oRow = this.GetRow(PKVal);
		
		if ( ! oRow )
		{
			alert(XML_ROW_ERROR + PKVal);	
			return;
		}
		
		return this.GetRowData(oRow, ColumnName);
	}
	
	this.GetDataByIndex = function( rowIndex, columnName )
	{
		var oRow = this.GetRowByIndex(rowIndex);
		
		var oData = "";
		if ( oRow.selectSingleNode(columnName) != null )
			oData = oRow.selectSingleNode(columnName).text;
		return oData;
	}
	
	this.GetRowData = function( oRow, ColumnName )
	{		
		if ( ! oRow.selectSingleNode(ColumnName) )
		{
			if ( this.CheckEmpty(ColumnName) == null )
			{
				alert(XML_COLUMN_ERROR + ColumnName);
				return;
			}
			return "";
		}
		
		return oRow.selectSingleNode(ColumnName).text;
	}
	
	// Gets a specific row
	this.GetRow = function ( PKVal )
	{
		var sXpath = BuildXPath(PKVal);	
		var CurrentRow = this.DataIsland.selectSingleNode("//" + this.DataInstance).selectSingleNode(sXpath);	
		return CurrentRow;
	}
	this.RowCount = function()
	{
		var oRows = this.GetAllRows();
		return oRows.length;
	}
	
	this.GetRowByIndex = function(rowIndex)
	{
		var sTableXpath = "//" + this.DataInstance + "/" + this.TableName;
		if ( rowIndex != null )
		{
			sTableXpath += "[" + rowIndex + "]";
		}
		
		var oRows = DataIsland.selectSingleNode(sTableXpath);
		return oRows;
	}
	this.GetAllRows = function()
	{
		var sTableXpath = "//" + this.DataInstance + "/" + this.TableName;
		var oRows = DataIsland.selectNodes(sTableXpath);
		return oRows;
	}
	
	this.GetRowByStatement = function ( Statement )
	{
		var sXpath = BuildXPathByStatement( Statement );
		var MainRow = this.DataIsland.selectSingleNode("//" + this.DataInstance);
		if ( MainRow )
		{
			var CurrentRow = MainRow.selectSingleNode(sXpath);	
			return CurrentRow;
		}
		else
			return null;
	}
	
	this.GetRowsByStatement = function ( Statement )
	{
		var sXpath = BuildXPathByStatement( Statement );
		var MainRow = this.DataIsland.selectSingleNode("//" + this.DataInstance);
		if ( MainRow )
		{
			var Rows = MainRow.selectNodes(sXpath);	
			return Rows;
		}
		else
			return null;
	}
	
	this.DataExists = function ( Column, Value )
	{
		var oRows = this.GetRowsByColumn( Column, Value );
		if ( oRows != null && oRows.length > 0 )
			return true;
		else
			return false;
	}
	
	this.GetRowsByColumn = function ( Column, Value )
	{
		var sXpath = BuildXPathByData( Column, Value );
		var MainRow = this.DataIsland.selectSingleNode("//" + this.DataInstance);
		if ( MainRow )
		{
			var Rows = MainRow.selectNodes(sXpath);	
			return Rows;
		}
		else
			return null;
	}
	
	this.GetRowByColumn = function ( Column, Value )
	{
		var sXpath = BuildXPathByData( Column, Value );
		var MainRow = this.DataIsland.selectSingleNode("//" + this.DataInstance);
		if  ( MainRow )
		{
			var CurrentRow = MainRow.selectSingleNode(sXpath);
			return CurrentRow;
		}
		else
			return null;		
	}
	function BuildXPathByData( Column, Value )
	{
		var sPath = TableName + "[" + Column + " = '" + Value + "']";
		return sPath;
	}	
	function BuildXPathByStatement( Statement )
	{
		var sPath = TableName + "[" + Statement + "]";
		return sPath;
	}	
}

//****************************************************************
//							Code Selection
//****************************************************************

function GetFormElement( id )
{
	return document.getElementById( id );
}

function GetFormElementByName( name )
{
	return document.getElementsByName( name );
}	

//---------------------------------------------------
// Class Name: CheckboxSelection
// Description: 
//		Holds state for a group of checkboxes
//		and updates the hidden form elements.
//---------------------------------------------------

function CheckboxSelection( CodeSelectionID, DisplayMsg, SelectLimitMsg, HitLimitMsg, LimitSelect, LimitHitCount )
{	
	this.ErrMsg			= '';
	this.Text			= DisplayMsg;
	this.MsgSelectLimit = SelectLimitMsg;
	this.MsgHitLimit	= HitLimitMsg;
	this.SelectionLimit = LimitSelect;
	this.HitCountLimit  = LimitHitCount;
	
	this.HitCountInput = GetFormElement( 'CodeSelection_HitCount_' + CodeSelectionID );
	this.CodesInput	   = GetFormElement( 'CodeSelection_Codes_' + CodeSelectionID );
	this.DisplayInput  = GetFormElement( 'CodeSelection_Display_' + CodeSelectionID );

	this.Codes		 = this.CodesInput.value;
	this.NumHits	 = eval(this.HitCountInput.value);
	
	this.NumSelected = function()
	{
		var lCount;
		
		if (  this.Codes != null && this.Codes != '')
			lCount = this.Codes.split('|').length; 
		else
			lCount = 0;
		
		return lCount;
	}
	
	this.SaveState = function()
	{
		this.HitCountInput.value = this.NumHits;
		this.CodesInput.value = this.Codes;
		
		if(this.DisplayInput)
		{
			var pattern = /\{0\}/;
			this.DisplayInput.value = this.Text.replace( pattern, this.NumSelected());
		}
	}
	
	this.SelectCheckbox = function( oCheck )
	{
		this.ErrMsg = '';
		
		if ( oCheck.checked == true )
		{
			this.AddCode( oCheck.value );
			
			if ( this.ErrMsg != '' ) 
			{
				alert( this.ErrMsg );
				oCheck.checked = false;
			}
		}
		else
		{
			//cc_104943 thl 02/04/2004
			var sCode = oCheck.value;
			
			this.DeleteCode( oCheck.value );
			//cc_104943 thl 02/04/2004 - uncheck any checkboxes
			//that have the same value. Duplicate bibcodes
			//can now appear in the title list because of the display
			//all headings sort change
			var oCheckBoxes = GetFormElementByName( "check" );
			for ( i = 0; i < oCheckBoxes.length; i++ )
			{
				if  ( oCheckBoxes[i].value == sCode )
				{
					if  ( oCheckBoxes[i].checked == true )
					{
						oCheckBoxes[i].checked = false;
					}
				}
			}
		}
		this.SaveState();
	}
	
	this.SelectRecord = function( Code, HitCount, CheckBoxName )
	{
	
		var oCheckBoxes = GetFormElementByName( CheckBoxName );
				
		//If oCheckBoxes is not an array
		if( oCheckBoxes && oCheckBoxes.value )
		{
			oCheckBoxes.checked = false;
		}
		else if( oCheckBoxes )
		{		
			for ( i = 0; i < oCheckBoxes.length; i++ )
			{
				if(oCheckBoxes[i].value == Code + '~' + HitCount)
				{
					this.AddCode( oCheckBoxes[i].value );
					oCheckBoxes[i].checked = true;
					break;
				} 
			}
		}
		
		this.SaveState();
	}
	
	this.ClearCheckboxes = function( oCheckAll, CheckBoxName )
	{
	
		var oCheckBoxes = GetFormElementByName( CheckBoxName );
		if( oCheckAll ) oCheckAll.checked = false;
		
		//If oCheckBoxes is not an array
		if( oCheckBoxes && oCheckBoxes.value )
		{
			oCheckBoxes.checked = false;
		}
		else if( oCheckBoxes )
		{		
			for ( i = 0; i < oCheckBoxes.length; i++ )
			{
				oCheckBoxes[i].checked = false;
			}
		}
		
		this.Codes		 = '';
		this.NumHits	 = 0;
		
		this.SaveState();
	}


	//--------------------------------------------------------
	// Name: SelectAll
	// Purpose: Selects / deselects all entrees in a grid
	//--------------------------------------------------------
	this.SelectCheckboxes = function(oCheckAll, CheckBoxName)
	{
		var oCheckBoxes = GetFormElementByName( CheckBoxName );
		
		this.ErrMsg = '';
		
		if ( oCheckAll.checked == false)
			this.UncheckAll(oCheckBoxes);
		else
			this.CheckAll(oCheckBoxes);

		if ( this.ErrMsg != '' ) alert( this.ErrMsg );
		
		this.SaveState();
	}
			
	//------------------- Private Functions ---------------------------
	this.UncheckAll = function(oCheckBoxes)
	{
		var i;
		this.ErrMsg = '';
		
		if ( oCheckBoxes.value ) 
		{	
			if ( oCheckBoxes.checked == true )
			{ 
				this.DeleteCode( oCheckBoxes.value );	
				this.oCheckBoxes.checked = false;
			}
		}
		else
		{
			for ( i = 0; i < oCheckBoxes.length; i++ )
			{
				if ( oCheckBoxes[i].checked == true )
				{
					
					this.DeleteCode( oCheckBoxes[i].value );	
					oCheckBoxes[i].checked = false;
				}
			}
		}
	}

	this.CheckAll = function(oCheckBoxes)
	{
		var i;
		this.ErrMsg = '';
		
		if ( oCheckBoxes.value ) 
		{	
			if ( oCheckBoxes.checked == false )
			{ 
				this.AddCode( oCheckBoxes.value );
				if ( this.ErrMsg == '' )	oCheckBoxes.checked = true;
			}
		}
		else
		{
			for ( i = 0; i < oCheckBoxes.length; i++ )
			{
				if ( oCheckBoxes[i].checked == false )
				{			
					this.AddCode( oCheckBoxes[i].value  );
					
					if ( this.ErrMsg == '' )
						oCheckBoxes[i].checked = true;
					else
						break;
				}
			}
		}
	}
				
	this.CheckLimits = function()
	{
		var sErrMsg;
		
		if ( this.NumSelected() >= this.SelectionLimit ) 
			return this.MsgSelectLimit; 
		else if ( this.NumHits >= this.HitCountLimit ) 
			return this.MsgHitLimit; 
		else
			return '';
	}

	this.AddCode = function( Code )
	{
		var sCodes		= "|" + this.Codes + "|";
		var oCode		= this.GetCodeStruct( Code );
		this.ErrMsg		= '';
		
		//Exit if we reached a limit
		this.ErrMsg = this.CheckLimits()
		if (this.ErrMsg != '' ) return;
				
				
		if ( sCodes != "||" )
		{
			if ( sCodes.indexOf( "|" + oCode.value + "|") == -1 )
			{ sCodes += oCode.value + "|";	} 
		}
		else
		{
			sCodes = "|" + oCode.value + "|";
		}
			
		this.NumHits		 = this.NumHits + oCode.hitCount;
		this.Codes			 = sCodes.substring( 1, sCodes.length - 1 );
	}

	this.DeleteCode = function( Code )
	{
		var oCode	= this.GetCodeStruct( Code );
		var sCodes  = "|" + this.Codes + "|";
		var sCode   = "|" + oCode.value + "|";
		var lPos;
		
		this.ErrMsg = '';
		
		if ( sCodes != "||" )
		{
			lPos = sCodes.indexOf( "|" + oCode.value + "|" );
				
			sCodes = sCodes.substring( 0, lPos + 1 ) +
					sCodes.substring( lPos + sCode.length, sCodes.length );
				
			this.NumHits = this.NumHits - oCode.hitCount;
		}
			
		if ( sCodes == "|" ) 
			this.Codes = "";
		else
			this.Codes = sCodes.substring( 1, sCodes.length - 1 );
	}
	
	//---------------------------------------------------
	// Function: GetCodeStruct
	// Description: 
	//		Returns a structure containing the code and the
	//		corresponding hitcount ( if any )
	//---------------------------------------------------
	this.GetCodeStruct = function(Code)
	{
		var oCode = new Object();

			
		if ( Code.indexOf("~") != -1 )
		{
				
			oCode.hitCount = eval(Code.substring( Code.indexOf("~") + 1, Code.length ));
			oCode.value    = Code.substring( 0, Code.indexOf("~") );	
		}
		else
		{
			oCode.value = Code;
			oCode.hitCount = 0;
		}
			
		return oCode;
	}
}

//************************************************************
//						EditGrid
//************************************************************
function Debug(oRow)
{
	var oDataTable = GetDataTable( oRow );
	var xmlRow = oDataTable.GetRow( oRow.pk );
	alert( xmlRow.xml );
}

function DebugFromElem(elem)
{
	var oDataTable = eval(elem.dataTable);
	var newRow = oDataTable.GetRow( elem.pk );
	alert( newRow.xml );
}


//************************************************************
//						DHTML Picklist
//************************************************************
function GetDHTMLPicklistVal(td, EventToFire)
{
	var sSelectedValue = td.parentElement.cells[0].getElementsByTagName("span")[0].innerText;
	oPopup.hide();
	
	//Upon close, save the value to input control if pressent
	//Else, call a user specified function
	if( oPicklistInput )
	{
		if( sSelectedValue != oPicklistInput.value )
		{
			if ( oPicklistInput.tagName.toLowerCase() == "input" )
			{
				oPicklistInput.value = sSelectedValue;
				oPicklistInput.fireEvent( "onchange" );
			}
			else
			{
				oPicklistInput.innerText = sSelectedValue;
			}
		}
	}
	else if( EventToFire != "" )
	{
		eval(EventToFire + "('" + sSelectedValue + "');");
	}
}

function PopDHTMLPicklist( XMLData, XSLStyle, Elem, ValueObject, Width, Height, Filter, Sort )
{	
	 if( XMLData.readyState != 'complete' )
  	 {
  		alert( LOADING_MESSAGE )
  		return;
  	 }
	 
	 //Save the input object for later use
	 oPicklistInput = ValueObject;
	 
	 //Set Filter and Sort
	 if( Filter != "" ) XSLStyle.documentElement.selectSingleNode("xsl:for-each/@select").text = Filter;
	 if( Sort != "" ) XSLStyle.documentElement.selectSingleNode("xsl:for-each/@order-by").text = Sort;
	
	 //Create The Popup Body and Data
	oPopup.document.body.innerHTML =
		"<div class='DHTMLPicklist' style='height:" + Height + "' >" + 
		XMLData.documentElement.transformNode( XSLStyle ) +
		"</div>" 
	
	//Display the window
	oPopup.show(0, Elem.height, Width, Height, Elem);
}

function SetPageRefreshField()
{
	document.forms[0].HiddenPageBack.value = 'true';
}

function DoPageRefresh()
{
	var oDoc = window.document;
	var oForm = document.forms[0];
	var oNewHidden = oDoc.createElement("<input type='hidden' name='DoPageRefresh' value='true'>");
	oForm.appendChild(oNewHidden);
	FormSubmit();
}

function PopWindowFullScreen(url, width, height, resizable, toolbar, title)
{	
	if (! title )
		var title = "Titles";
		
	if (title == null && window.BrowserWindow != null && !window.BrowserWindow.closed)
	{
		//alert('Window is open.');
		window.BrowserWindow.close();
	}

	var windowOptions = 'width=' + (window.screen.availWidth - 10) + ',height=' + (window.screen.availHeight - 40)
	                    + ',left=0,top=0,screenx=0,screeny=0,dependent=yes,alwaysRaised=yes,directories=no,location=no,scrollbars=yes,menubar=no';
	
	if( resizable && resizable == true ) windowOptions += ',resizable';

	if( toolbar != false ) 
		windowOptions += ',toolbar=yes'; 
	else
		windowOptions += ',toolbar=no';		
	
	var sNewURL = GetUniqueURL(url);
	
	window.BrowserWindow = open(sNewURL, title, windowOptions, false );
	window.BrowserWindow.focus();
	//return BrowserWindow;
}

function PopWindowCustom(url, width, height, resizable, toolbar, title)
{	
	if (! title )
		var title = "Titles";
		
	if (title == null && window.BrowserWindow != null && !window.BrowserWindow.closed)
	{
		//alert('Window is open.');
		window.BrowserWindow.close();
	}

	var windowOptions = 'width=' + width + ',height=' + height
	                    + ',left=10,top=10,screenx=10,screeny=0,dependent=yes,alwaysRaised=yes,directories=no,location=no,scrollbars=yes,menubar=no';
	
	if( resizable && resizable == true ) windowOptions += ',resizable';

	if( toolbar != false ) 
		windowOptions += ',toolbar=yes'; 
	else
		windowOptions += ',toolbar=no';		
	
	//var sNewURL = GetUniqueURL(url);
	
	window.BrowserWindow = open(url, title, windowOptions, false );
	window.BrowserWindow.focus();
	//return BrowserWindow;
}

function PopWindow(url, width, height, resizable, toolbar, title)
{	
	if (! title )
		var title = "Titles";
		
	if (title == null && window.BrowserWindow != null && !window.BrowserWindow.closed)
	{
		//alert('Window is open.');
		window.BrowserWindow.close();
	}
	if ( gb_AllowMultipleWindow )
		title += new Date().getTime();
	var windowOptions = 'width=' + width + ',height=' + height
	                    + ',left=10,top=10,screenx=10,screeny=0,dependent=yes,alwaysRaised=yes,directories=no,location=no,scrollbars=yes,menubar=no';
	
	if( resizable && resizable == true ) windowOptions += ',resizable';

	if( toolbar != false ) 
		windowOptions += ',toolbar=yes'; 
	else
		windowOptions += ',toolbar=no';		
	
	var sNewURL = GetUniqueURL(url);
	
	window.BrowserWindow = open(sNewURL, title, windowOptions, false );
	window.BrowserWindow.focus();
	//return BrowserWindow;
}

function PopWindowNoReturn(url, width, height, resizable, toolbar, title)
{	
	if (! title )
		var title = "Titles";
		
	if (title == null && window.BrowserWindow != null && !window.BrowserWindow.closed)
	{
		//alert('Window is open.');
		window.BrowserWindow.close();
	}

	var windowOptions = 'width=' + width + ',height=' + height
	                    + ',left=10,top=10,screenx=10,screeny=0,dependent=yes,alwaysRaised=yes,directories=no,location=no,scrollbars=yes,menubar=no';
	
	if( resizable && resizable == true ) windowOptions += ',resizable';

	if( toolbar != false ) 
		windowOptions += ',toolbar=yes'; 
	else
		windowOptions += ',toolbar=no';		
	
	window.BrowserWindow = open(GetUniqueURL(url), title, windowOptions, false );
	window.BrowserWindow.focus();
}

function PopViewRecordWindow(sUrl, windowName)
{
	PopWindow(sUrl, 650, 500, true, true, windowName);
}



//**************************************************************
//					    Modal Dialog
//**************************************************************
function ModalDialog(url, title, width, height,resizable)
{
	this.Properties = new Object();
	this.Properties.Values = new Array();
	this.Properties.Keys = new Array();
	this.Properties.URL = GetUniqueURL(GetApplicationPath() + url);
	this.Properties.Title = title;
	this.Properties.Width = width;
	this.Properties.Height = height;
	
	if ( resizable == "undefined" )
	{
		resizable = null;
	}
	if ( resizable == null )
	{
		resizable = true;
	}
	this.Properties.Resizable = resizable;
	
	this.AddHiddenField = function(key, value)
	{
		var nCount = this.Properties.Values.length;
		this.Properties.Values[nCount] = value;
		this.Properties.Keys[nCount] = key;
	}
	
	this.Show = function()
	{	
	
		var sResize = "no";
		if ( this.Properties.Resizable )
			sResize = "yes";
		
		var windowOptions = 'dialogHeight:' + this.Properties.Height + 'px;dialogWidth:' + this.Properties.Width + 'px;center:yes;status:no;help:no;resizable:' + sResize + ';'; 	
		return window.showModalDialog(GetApplicationPath() + "/Common/Htm/ModalDialog.htm", this.Properties , windowOptions );
	}	
}

function GetApplicationPath()
{
	var sPos = window.location.pathname.indexOf( '/', 1 );
	return window.location.pathname.substring(0 , sPos);
}

function FindControl( Controls, ID )
{
	var nLength = Controls.length;

	for( i = 0; i < nLength; i++ )
	{
		if( Controls[i].id.lastIndexOf( ID ) != -1 ) return Controls[i];
	}
}

// parameters have been added for more flexibility
//sDocColor will change the Document class name to [ClassName] + sDocColor
//sBodyClass is the classname that will be used for the Body
//sTextClass is the classname that will be used for the main Message text
//You will need to ensure that classes have been created for these to work.
function OpenMessage( sButtonList, sMessage, sMessageDescription, sMessageDirections, nHeight, nWidth, sDocColor, sBodyClass, sTextClass )
{
	if ( nHeight == null || nHeight == "" )
	{
		nHeight = 300;
	}
	if (nWidth == null || nWidth == "" )
	{
		nWidth = 300; 
	}
	
	var args = new Object();
	
	args.Buttons = sButtonList;
	args.Message = sMessage;
	args.messageBody = sMessageDescription;
	args.MessageDirections = sMessageDirections;
	args.ApplicationPath = GetApplicationPath();
	args.DocColor = sDocColor;
	args.BodyClass = sBodyClass;
	args.TextClass = sTextClass;
	var features = "dialogWidth:" + nWidth  + "px;dialogHeight:" + nHeight + "px;help:no;resizable:no;status:no";
	window.showModalDialog( GetApplicationPath() + "/Common/Htm/Message.htm", args, features);
	return args.ButtonClicked;
}

function OpenErrorPopup( sMessage, sMessageDescription )
{
	var	nHeight = 220;
	var	nWidth = 400; 
	
	var args = new Object();
	
	args.Message = sMessage;
	args.messageBody = sMessageDescription;
	args.ApplicationPath = GetApplicationPath();
	args.SorryMsg = SORRY_MSG;
	args.Details = DETAILS_MSG;
	var features = "dialogWidth:" + nWidth  + "px;dialogHeight:" + nHeight + "px;help:no;resizable:yes;status:no";
	window.showModalDialog( GetApplicationPath() + "/Common/Htm/ErrorPopup.htm", args, features);
	return args.ButtonClicked;
}

function OpenSuccessPopup( sMessage, sMessageDescription, Width, Height )
{
	
	var nHeight = (Height == null) ? 200 : Height;
	var	nWidth = (Width == null) ? 300 : Width; 
	
	var args = new Object();
	
	args.Message = sMessage;
	args.messageBody = sMessageDescription;
	args.ApplicationPath = GetApplicationPath();
	var features = "dialogWidth:" + nWidth  + "px;dialogHeight:" + nHeight + "px;help:no;resizable:no;status:no";
	window.showModalDialog( GetApplicationPath() + "/Common/Htm/SuccessPopup.htm", args, features);
	return args.ButtonClicked;
}

function OpenSuccessPrintPopup( sMessage, sMessageDescription, PrintHTML, Width, Height )
{				
	var nHeight = (Height == null) ? 200 : Height;
	var	nWidth = (Width == null) ? 300 : Width; 
	var args = new Object();
	
	args.Message = sMessage;
	args.messageBody = sMessageDescription;
	
	args.PrintHTML = PrintHTML;
	
	var features = "dialogWidth:" + nWidth  + "px;dialogHeight:" + nHeight + "px;help:no;resizable:no;status:no";

	window.showModalDialog( GetApplicationPath() + "/Common/Htm/SuccessPrintPopup.htm", args, features);
	return;
}	


function OpenRadioButtonPopup( sTitle, sRadioButtonList, nHeight, nWidth )
{
	if ( nHeight == null || nHeight == "" )
	{
		nHeight = 300;
	}
	if (nWidth == null || nWidth == "" )
	{
		nWidth = 300; 
	}
	
	var args = new Object();
	
	args.Title = sTitle;
	args.RadioButtons = sRadioButtonList;
	args.ApplicationPath = GetApplicationPath();
	var features = "dialogWidth:" + nWidth  + "px;dialogHeight:" + nHeight +"px;help:no;resizable:no;status:no";
	window.showModalDialog( GetApplicationPath() + "/Common/Htm/RadioButtonPopup.htm?title=rss", args, features);
	return args.ButtonClicked;
}

function OpenCheckboxPopup( sTitle, sCheckboxList, sCheckedItems, nHeight, nWidth )
{
	if ( nHeight == null || nHeight == "" )
	{
		nHeight = 300;
	}
	if (nWidth == null || nWidth == "" )
	{
		nWidth = 300; 
	}
	
	var args = new Object();
	
	args.Title = sTitle;
	args.CheckboxList = sCheckboxList;
	args.CheckedItems = sCheckedItems;
	args.ApplicationPath = GetApplicationPath();
	var features = "dialogWidth:" + nWidth  + "px;dialogHeight:" + nHeight +"px;help:no;resizable:no;status:no";
	window.showModalDialog( GetApplicationPath() + "/Common/Htm/CheckboxPopup.htm?title=rss", args, features);
	return args.CheckedItems;
}

function GetBibViewURL()
{
	return GetApplicationPath() + "/OPAC/TitleView/CopyInfo.asp";
}
function GetAssignmentViewURL()
{
	return GetApplicationPath() + "/TitleView/FTTitleView.aspx";
}

function GetBibEditURL()
{
	if(g_sDefaultBibEditor == "Marc")
	{
		return GetApplicationPath() + "/Cataloging/Bibliographic/Marc.aspx";
	}
	else
	{
		return GetApplicationPath() + "/Cataloging/Bibliographic/EasyMarc.aspx";	
	}
}

function GetAssignmentEditURL()
{
	return GetApplicationPath() + "/FilmAndTape/Assignments/AssignmentEdit.aspx";
}

function GetAuthEditURL()
{
	//if express, there is no marc for these records.
	if ( g_sDefAuthEditor || g_sDefAuthEditor == "" )
	{
		return GetApplicationPath() + "/Cataloging/Authority/AuthEasyMarc.aspx";
	}
	
	if(g_sDefAuthEditor == "Marc")
	{
		return GetApplicationPath() + "/Cataloging/Authority/AuthMarc.aspx";
	}
	else
	{
		return GetApplicationPath() + "/Cataloging/Authority/AuthEasyMarc.aspx";	
	}
}


function OnAssignmentEditClickBibCodes( bibCodes )
{	
	var sURL= GetAssignmentEditURL() + "?codes=" + bibCodes;
	PopWindowFullScreen(sURL, 1100, 700, true, true, 'BibEdit');
}

function OnAssignmentRecordClickBibCodes( searchCode, bibCodes )
{
	var sURL = GetAssignmentViewURL() + "?RwSearchCode=" + searchCode + "&codes=" + bibCodes;
	if ( arguments.length > 2 )
	{
		sURL += "&DbCode=" + arguments[2];
	}
	if ( arguments.length > 3 )
	{
		sURL += "&CurLanguage=" + arguments[3];
	}
	if ( arguments.length > 4 )
	{
		sURL += "&WordHits=" + arguments[4];
	}
	PopWindowFullScreen(sURL, 1100, 700, true, true, 'BibEdit');
}

function OnEditClickBibCodes( bibCodes )
{	
	var sURL= GetBibEditURL() + "?codes=" + bibCodes;
	PopWindow(sURL, 770, 500, true, true, 'BibEdit');
}

function OnRecordClickBibCodes( searchCode, bibCodes )
{
	var sURL = GetBibViewURL() + "?RwSearchCode=" + searchCode + "&BibCodes=" + bibCodes;
	if ( arguments.length > 2 )
	{
		sURL += "&DbCode=" + arguments[2];
	}
	if ( arguments.length > 3 )
	{
		sURL += "&CurLanguage=" + arguments[3];
	}
	if ( arguments.length > 4 )
	{
		sURL += "&WordHits=" + arguments[4];
	}
	PopWindow(sURL, 770, 500, true, true, 'BibEdit');
}

function AddNewRecord()
{
	var sURL = GetApplicationPath() + "/Cataloging/Bibliographic/NewBibRecord.aspx";
	PopWindow(sURL, 770, 500, true, true, 'BibEdit');
}

function AddNewAssignment()
{
	var sURL = GetApplicationPath() + "/FilmAndTape/Assignments/AssignmentEdit.aspx";
	PopWindowFullScreen(sURL, 1100, 700, true, true, 'AssignmentEdit');
}

//Transferred from PublisherTemplate.ascx
function ChangePage(URL)
{		
	if( CanSubmit() )
	{		
		document.forms[0].action = URL;
		FormSubmit();
	}
}

//////////////////////

function toggleElement(elementName, elementButtonName) {
	var elem = document.getElementById(elementName);
	var elemButton = document.getElementById(elementButtonName);
	
	if ((elem != null) && (elemButton != null)) {
		if (elem.style.display == 'none') {
			elem.style.display = '';
			elemButton.src = GetApplicationPath() + '/Common/Images/arrow_collapse.gif';
		}
		else
		{
			elem.style.display = 'none';
			elemButton.src = GetApplicationPath() + '/Common/Images/arrow_expand.gif';
		}
	}
}


////////////// Pickers ///////////////////////

function ShowPatronPicker(InputBoxID, NextButtonID, PatronLinkCodeID, UseCircDeskBrowse) {
	var sURL = "/Circulation/PatronPicker.aspx?UseCircDeskBrowse=" + UseCircDeskBrowse;
	
	var oModal = new ModalDialog(sURL, 'Browse', 600, 500 );

	sVal = oModal.Show();
	
	if (sVal != null) {
		if (sVal.BarCode != null) {
			var inputBox = document.getElementById(InputBoxID);
			var nextButton = document.getElementById(NextButtonID);
			var patronLinkCodeBox = document.getElementById(PatronLinkCodeID);
			
			inputBox.value = sVal.BarCode;
			patronLinkCodeBox.value = sVal.LinkCode;
		
			ShowProcessMessage();
			nextButton.click();
		}
	}
}

function ShowHolderPicker(InputBoxID, NextButtonID, PatronLinkCodeID, UseCircDeskBrowse) {
	var sURL = "/FilmAndTape/Order/HolderPicker.aspx?UseCircDeskBrowse=" + UseCircDeskBrowse;
	
	var oModal = new ModalDialog(sURL, 'Browse', 600, 500 );

	sVal = oModal.Show();
	
	if (sVal != null) {
		if (sVal.BarCode != null) {
			var inputBox = document.getElementById(InputBoxID);
			var nextButton = document.getElementById(NextButtonID);
			var patronLinkCodeBox = document.getElementById(PatronLinkCodeID);
			
			inputBox.value = sVal.BarCode;
			patronLinkCodeBox.value = sVal.LinkCode;
		
			ShowProcessMessage();
			nextButton.click();
		}
	}
}


function ShowItemPicker(InputBoxID, NextButtonID, IsBibCodeID, CircType, ItemLinkCodeID) {
	
	/*var sURL = GetApplicationPath() + '/Circulation/ItemPicker.aspx';
	
	var oPopWindow = new PopWindow(sURL, 'Browse', 600, 500 );
	oPopWindow.AddHiddenField('CircType', CircType);
	if (IsBibCodeID != '')
		oPopWindow.AddHiddenField('TitlePickerDisplay', '');
	else
		oPopWindow.AddHiddenField('TitlePickerDisplay', 'none');
		
	sVal = oPopWindow();*/
	
	var sURL = "/Circulation/ItemPicker.aspx";
	
	var oModal = new ModalDialog(sURL, 'Browse', 600, 500 );
	oModal.AddHiddenField('CircType', CircType);
	if (IsBibCodeID != '')
		oModal.AddHiddenField('TitlePickerDisplay', '');
	else
		oModal.AddHiddenField('TitlePickerDisplay', 'none');
		
	sVal = oModal.Show();
	
	if (sVal != null) {
		if ((sVal.Code != null) && (sVal.IsBibCode != null)) {
			var inputBox = document.getElementById(InputBoxID);
			var nextButton = document.getElementById(NextButtonID);
			var IsBibCodeBox = document.getElementById(IsBibCodeID);
			var ItemLinkCodeIDBox = document.getElementById(ItemLinkCodeID);
			
			if (IsBibCodeBox != null)
				IsBibCodeBox.value = sVal.IsBibCode;
				
			if (ItemLinkCodeIDBox != null)
				ItemLinkCodeIDBox.value = sVal.LinkCode;
			
			inputBox.value = sVal.Code;
			ShowProcessMessage();
			nextButton.click();
		}
	}
}

function ShowTitlePicker(InputBoxID, NextButtonID, IsBibCodeID) {
	var sURL = "/Circulation/TitlePicker.aspx";
	
	var oModal = new ModalDialog(sURL, 'Browse', 600, 500 );
	if (IsBibCodeID != '')
		oModal.AddHiddenField('TitlePickerDisplay', '');
	else
		oModal.AddHiddenField('TitlePickerDisplay', 'none');
	sVal = oModal.Show();
	
	if (sVal != null) {
		if ((sVal.Code != null) && (sVal.IsBibCode != null)) {
			var inputBox = document.getElementById(InputBoxID);
			var nextButton = document.getElementById(NextButtonID);
			var IsBibCodeBox = document.getElementById(IsBibCodeID);
		
			if (IsBibCodeBox != null)
				IsBibCodeBox.value = sVal.IsBibCode;
			
			inputBox.value = sVal.Code;
			ShowProcessMessage();
			nextButton.click();
		}
	}
}

////////////////////////////////////////////////////////////////////

function ConfirmDeleteMessage(message)
{
	var bReturn = false;
	var iReturn = OpenMessage( OKCANCEL_BUTTONS, PLEASE_CONFIRM, message, '', 200, 300 );
	if( iReturn == 0 ) bReturn = true;
	return bReturn;
}
function ConfirmDelete(hitCount)
{
	var bReturn = false;
	if ( hitCount != null )
		hitCount = parseInt(hitCount,10);
	if ( hitCount > 100 )
	{
		alert(HITCOUNT_MAX);
		return false;
	}
	var iReturn = OpenMessage( OKCANCEL_BUTTONS, PLEASE_CONFIRM, DELETE_CONFIRM, '', 200, 300 );
	if( iReturn == 0 ) bReturn = true;
	return bReturn;
}

function CleanCodes( sCodes, retainPosition )
{
	var aCodes = sCodes.split( "|" );
	var sNewCodes = "";
	for ( i = 0; i < aCodes.length; i++ )
	{
		var aSplit = aCodes[i].split( "_" );
		if ( retainPosition < aSplit.length )
			sNewCodes += aSplit[retainPosition] + "|";
	}
	if ( sNewCodes.length != 0 )
		sNewCodes = sNewCodes.substr( 0, sNewCodes.length - 1 );
	else
		sNewCodes = sCodes;
		
	return sNewCodes;
}

function HasLinkedBibs( sCodes, position )
{
	var bHasLinkedBibs = false;
	var aCodes = sCodes.split( "|" );
	for ( i = 0; i < aCodes.length; i++ )
	{
		var aSelected = aCodes[i].split( "_" );
		if ( position < aSelected.length )
		{
			if ( aSelected[position] != "0" )
			{
				bHasLinkedBibs = true;
				i = aCodes.length;
			}
		}
	}
	return bHasLinkedBibs;
}

function AuthorityConfirmDelete(linkedBibs)
{
	var bReturn = false;
	var sMessage = "";
	var iWidth = 300;
	var iHeight = 200;
	if ( linkedBibs )
	{
		sMessage = DELETE_CONFIRM_WITH_LINKS;
		iWidth = 400;
		iHeight = 225;
	}
	else
	{
		sMessage = DELETE_CONFIRM;
	}

	var iReturn = OpenMessage( OKCANCEL_BUTTONS, PLEASE_CONFIRM, sMessage, '', iHeight, iWidth );
	if( iReturn == 0 ) bReturn = true;
	return bReturn;
}


function ConfirmLabelDelete()
{
	var Message = false;
	var Temp = OpenMessage( OKCANCEL_BUTTONS, PLEASE_CONFIRM, DELETE_LABEL_CONFIRM, '', 200, 300 );
	if( Temp == 0 ) 
		Message = true;
	return Message;
}

function RowsFound(IsEmpty)
{
	if ( IsEmpty == null )
		return false;
		
	if ( IsEmpty )
	{
		OpenMessage(OK_BUTTONS, "Alert!", NO_RECORDS_FOUND, "", 180, 300);
		return false;
	}	
	return true;
}

function ConfirmMessage(message, includeCancel, height)
{
	// if height is not given, as it will be most of the time it will be set to 200
	if ( ! height )
		var height = 200;
	
	if ( includeCancel == null )
		includeCancel = false;
		
	var buttons = YESNO_BUTTONS;
	if ( includeCancel )
		buttons = YESNOCANCEL_BUTTONS;
		
	var iAnswer = OpenMessage(buttons,PLEASE_CONFIRM, message, "", height, 350);
	if ( includeCancel )
	
		return iAnswer;
	
	if ( iAnswer != 0 )
		return false;
	
	return true;		
}
function SetTime()
{
	var oInput;
	eval ( "oInput = document.forms[0]." + event.dateInput + ";");
	if ( oInput == null )
	{
		alert(TIME_ERROR);
	}
	oInput.Time = event.serverValue;				
}

function SetInputFocus()
{
	if ( gs_FirstFocus != null )
	{
		var oCtrl;
		var command = "oCtrl = " + gs_FirstFocus;
		eval(command);		
		if ( oCtrl )
		{
			if ((oCtrl.disabled == false) && (oCtrl.style.display != 'none')) {
				oCtrl.focus();
				
				if (oCtrl.createTextRange) {					
					var r = oCtrl.createTextRange();
					r.moveStart('character', oCtrl.value.length);
					r.collapse();
					r.select();
				}
			}
		}
	}	
}

function DisplayOptions(clientID)
{
	var args = new Object();
	var oldValues = eval("document.forms[0]." + clientID + "_DisplayOptions.value");
	var sColumnText = eval("document.forms[0]." + clientID + "_DisplayColumnNames.value");
	var popupHeight = eval("document.forms[0]." + clientID + "_DisplayColumnsHeight.value");
	
	var answer = OpenCheckboxPopup("Display Options", sColumnText, oldValues ,  popupHeight, 320 );
	if ( oldValues != answer )
	{
		eval("document.forms[0]." + clientID + "_DisplayOptions.value = answer");
		eval("document.forms[0]." + clientID + "_DisplayOptionsChanged.value = 'true'");

		FormSubmit();		
	}
}
function ChangeInputLabel(ctrl, text)
{
	if ( ctrl.HasLabel == "true" )
	{
		if ( text.indexOf("<b>") == -1 )
		{
			text = "<b>" + text;
		}
		
		if ( text.indexOf("</b>") == -1 )
		{
			text += "</b>";
		}
		
		var oLabel = ctrl.previousSibling.previousSibling;
		oLabel.innerHTML = text;
	}
}
function DisableInput(ctrl)
{	
	if ( ctrl.HasLabel == "true" )
	{
		var oLabel = ctrl.previousSibling.previousSibling;
		oLabel.className = "DisabledLabel";
	}
	ctrl.disabled = true;
}

function EnableInput(ctrl)
{
	if ( ctrl.HasLabel == "true" )
	{
		var oLabel = ctrl.previousSibling.previousSibling;
		oLabel.className = "EnabledLabel";
	}
	ctrl.disabled = false;
}

function HideInput(ctrl)
{
	if ( ctrl.HasLabel == "true" )
	{
		var oLabel = ctrl.previousSibling.previousSibling;
		oLabel.style.display = "none";
	}
	ctrl.style.display = "none";
}

function ShowInput(ctrl)
{
	if ( ctrl.HasLabel == "true" )
	{
		var oLabel = ctrl.previousSibling.previousSibling;
		oLabel.style.display = "inline";
	}
	ctrl.style.display = "inline";
}

//////////////////

function selectSelectionItemByValue(selectionListClientID, value) {		
		
	var locationListControl = document.getElementById(selectionListClientID);	

	if (locationListControl != null) {
		for(i=0;i<locationListControl.options.length;i++) {
			if (value == locationListControl.options[i].value) {
				locationListControl.selectedIndex = i;
				break;
			}
		}
	}
}

function TieEnterKeyToButton(buttonClientID) {	
	if ((event.which && event.which == 13) || (event.keyCode && event.keyCode == 13))
	{
		eval('document.forms[0].' + buttonClientID + '.click();');
		return false;
	} 
    else
		return true;
}

///*************************************************************************************************
//										Mask Functions
//*************************************************************************************************/

function isAlphaKeyDown(keyCode)
{
	if ( keyCode >=65 && keyCode <= 90 )
		return true;
	if ( keyCode >= 97 && keyCode <= 122 )
		return true;
		
	return false;
}

function isNumberKeyDown( keyCode )
{
	return ((keyCode >= 0x30 && keyCode <= 0x39)||
		    (keyCode >= 0x60 && keyCode <= 0x69));
}

function isTabKeyDown( keyCode )
{
	return ( keyCode == 0x09 );
}

function isDeleteKeyDown( keyCode )
{
	return ( keyCode == 0x2E || keyCode == 0x08  );
}
function isArrowKeyDown( keyCode )
{
	return ( keyCode == 0x25 || keyCode == 0x26 || keyCode == 0x27 || keyCode == 0x28 );
}

function GetCultureClass(cultureCode)
{
	return eval("new CultureCode_" + cultureCode + "();");
}

function SetCurrencyFormat(sValue, culture,ctrl)
{
	var oCultureObject = GetCultureClass(culture);
	
	sValue = sValue + "";
	
	var originalValue = sValue;
	var sepTest = new RegExp("[\\)\\(-]", "g");
	sValue = sValue.replace(sepTest, "" );
	
	var bNegativeVal = false;
	if ( sValue != originalValue )
		bNegativeVal = true;
	
	//sValue = RoundCurrency(sValue, culture);
	
    sValue = sValue.replace(".",oCultureObject.CurrencyDecimalSeperator);
	
	SetCurrencyGroupSizes( sValue, culture );
	
	// if the value has changed then the number was negative.
	if ( bNegativeVal )
	{
		if  ( ctrl )
			ctrl.style.color = "red";
		return SetToNegativeCurrency(sValue, culture);
	}
	else
	{
		if ( ctrl )
			ctrl.style.color = "black";
		return SetToPositiveCurrency(sValue, culture);
	}
	
}

function SetToPositiveCurrency( sValue, culture )
{
	var oCultureObject = GetCultureClass(culture);
	var currencySymbol = oCultureObject.CurrencySymbol;
	var pattern = oCultureObject.CurrencyPositivePattern;
	
	var sReturnValue = "";
	var sPositiveFormat = pattern;
	switch ( sPositiveFormat )
	{
		case "0":
			sReturnValue = currencySymbol + sValue;
			break;
		case "1":
			sReturnValue = sValue + currencySymbol;
			break;
		case "2":
			sReturnValue = currencySymbol + " " + sValue;
			break;
		case "3":
			sReturnValue = sValue + " " + currencySymbol;
			break;
	}
	return sReturnValue;
}

function SetToNegativeCurrency( sValue, culture )
{
	var oCultureObject = GetCultureClass(culture);
	var currencySymbol = oCultureObject.CurrencySymbol;
	var pattern = oCultureObject.CurrencyPositivePattern;
	
	var sReturnValue = "";
	var sNegativeFormat = pattern;
	switch( sNegativeFormat )
	{
		case "0":
			sReturnValue = "(" + currencySymbol + sValue + ")";
			break;
		case "1":
			sReturnValue = "-" + currencySymbol + sValue;
			break;
		case "2":
			sReturnValue = currencySymbol + "-" + sValue;
			break;
		case "3":
			sReturnValue = currencySymbol + sValue + "-";
			break;
		case "4":
			sReturnValue = "("  + sValue + currencySymbol + ")";
			break;
		case "5":
			sReturnValue = "-"  + sValue + currencySymbol;
			break;
		case "6":
			sReturnValue = sValue + "-" + currencySymbol;
			break;
		case "7":
			sReturnValue = sValue + currencySymbol + "-";
			break;
		case "8":
			sReturnValue = "-" + sValue + " " + currencySymbol;
			break;
		case "9":
			sReturnValue = "-" + currencySymbol + " " + sValue;
			break;
		case "10":
			sReturnValue = sValue + " " + currencySymbol +  "-";
			break;
		case "11":
			sReturnValue = currencySymbol + " " +  sValue + "-";
			break;
		case "12":
			sReturnValue = currencySymbol + " -" +  sValue;
			break;
		case "13":
			sReturnValue = sValue + "- " + currencySymbol;
			break;
		case "14":
			sReturnValue = "(" + currencySymbol + " " + sValue + ")";
			break;
		case "15":
			sReturnValue = "(" +  sValue + " " + currencySymbol + ")";
			break;
	}
	return sReturnValue;
}



function SetCurrencyGroupSizes( sValue, culture )
{
	var oCultureObject = GetCultureClass(culture);
	var groupSizes = oCultureObject.CurrencyGroupSizes;
	var groupSeperator = oCultureObject.CurrencyGroupSeperator;
	// this makes sure this is a string value;
	sValue += "";
	// group sizes are passed to the control as a pipe delimited list of values that represent the 
	// distance between commas ( may be different for different cultures).  The format is either
	// one number which represents the fixed amount such as 3 being 123,456,000.00 or there could be 1 to many
	// numbers. such as 1|2|3 which would mean 123,45,6.000. also if the last number is 0, then the 
	// number before must be used again and again, for example 1,2,0 would be 12,34,56,0.00.
	// Note: you must always count forward from the decimal point. 
	var sizes = groupSizes.split("|");
	if ( sizes.length == 1 )
	{
		// if it is one number then you just do it as many times as needed, just divide the length by
		// the number.
		
		// This is the number of commas you need			
		var numSep = parseInt(sValue.indexOf(".") / parseInt(sizes[0],10),10);
		for ( var kk=0; kk<numSep; kk++ )
		{
			// then you start to count back
			var currentPosition = sValue.indexOf(".") - ((kk+1)*sizes[0] + (kk) );
			// if you reach the start of the value, then stop
			if ( currentPosition == 0 )
			{
				continue;
			}			
			sValue = sValue.substring( 0, currentPosition  ) + groupSeperator 
				+ sValue.substring( currentPosition, sValue.length );
		}
	}
	else
	{
		// this is the real tricky one. you have to figure out what group you are on, then you 
		// figure out where to set the group marker.		
		var increment = 0;
		for ( var ii=0; ii<sizes.length; ii++ )
		{
			// if it is equal to zero you have to take the last group size
			if ( sizes[ii] == 0 )
			{
				// get the last group size
				var size = parseInt(sizes[ii-1],10);		
				// so now you find out how many more chars are left in the value 
				// you do that by taking the length to the decimal minus how far you have 
				// already marked in the value		
				var numLeftToCheck = parseInt((sValue.indexOf(".") - increment),10);
				// then you get the number of seperators you have to place
				var numSep = parseInt( (numLeftToCheck  / size),10 );
				for (  var jj=0; jj<numSep; jj++ )
				{
					// them you get the place to put the seperator
					var currentPosition = numLeftToCheck -  ( (jj+1)*size);
					if ( currentPosition == 0 )
					{
						continue;
					}	
					sValue = sValue.substring( 0, currentPosition  ) + groupSeperator 
						+ sValue.substring( currentPosition, sValue.length );
				}		
			}
			else
			{
				// else you just do it like the first case, but you have a different 
				// group size every time.
				var currentPosition = (sValue.indexOf(".") - increment) - sizes[ii];
				if ( currentPosition == 0 )
				{
					continue;
				}				
				sValue = sValue.substring( 0, currentPosition  ) + groupSeperator 
					+ sValue.substring( currentPosition, sValue.length );
				increment += parseInt(sizes[ii],10)  + parseInt(groupSeperator.length);				
			}			
		}
	}
	return sValue;
}
function RoundCurrency(sValue, culture)
{
	var oCultureObject = GetCultureClass(culture);
	var iPlaceOfDecimal = sValue.indexOf(".");
	//  Fill in zeros (if necessary) to show two digits to the right 
    //  of the decimal
    if ( iPlaceOfDecimal == -1)
    {
		var endDecimals = ".";
		for ( var ii=0; ii<parseInt(oCultureObject.CurrencyDecimalPlaces,10); ii++ )
		{
			endDecimals += "0";			
		}
        sValue = sValue + endDecimals;
    }
    else
    {
		if ( iPlaceOfDecimal > (sValue.length - (parseInt(oCultureObject.CurrencyDecimalPlaces,10)+1)) )
		{
			var sAddZeros = "";
			var iNeedZeros = oCultureObject.CurrencyDecimalPlaces - ( sValue.length - (iPlaceOfDecimal + 1) );
			for ( var i=0; i<iNeedZeros; i++ )
			{
				sAddZeros += "0";
			}
			sValue += sAddZeros;
		}
		else
		{
			try 
			{
				sValue = vbFnRound(sValue, oCultureObject.CurrencyDecimalPlaces);
			}
			catch(e)
			{
				sValue = sValue.substr(0, iPlaceOfDecimal + 1 + parseInt(oCultureObject.CurrencyDecimalPlaces,10));
			}
		}
    }
    return sValue;
}

function UpdateParameterRadioButton(ctrl)
{
	var sCommand = "document.forms[0].param_" + ctrl.name + ";";
	var sEvent = "document.forms[0].RadioButtonFired;";
	var oHidden = eval(sCommand);
	var oEvent = eval(sEvent);

	oHidden.value = ctrl.value;
	
	if ( ctrl.RefreshOnChange != null && ctrl.RefreshOnChange == "true" )
	{
		if ( oEvent != null )
		{
			oEvent.value = "true";
			FormSubmit();
		}
	}
}

function UpdateParameterCheckBox(ctrl)
{
	var oHidden = eval("document.forms[0].param_" + ctrl.id);
	
	if ( ctrl.checked == true )
		oHidden.value = "1";
	else
		oHidden.value = "0";
}

function DisableDateTime(id) 
{
	var oDate = eval("document.forms[0]." + id + "_Date");
	var oTime = eval("document.forms[0]." + id + "_Time");
	oDate.Disable();
	oTime.Disable();
}
function EnableDateTime(id) 
{
	var oDate = eval("document.forms[0]." + id + "_Date");
	var oTime = eval("document.forms[0]." + id + "_Time");
	oDate.Enable();
	oTime.Enable();
}
function HideDateTime(id) 
{
	var oDate = eval("document.forms[0]." + id + "_Date");
	var oTime = eval("document.forms[0]." + id + "_Time");
	oDate.Disable();
	HideInput(oDate);
	HideInput(oTime);
}
function ShowDateTime(id) 
{
	var oDate = eval("document.forms[0]." + id + "_Date");
	var oTime = eval("document.forms[0]." + id + "_Time");
	oDate.Enable();
	ShowInput(oDate);
	ShowInput(oTime);
}

function GetControlTime(id)
{
	var oTime = eval("document.forms[0]." + id + "_Time");
	return oTime.Time;
}

function IsTimeSet(id)
{
	var sTime = GetControlTime(id);
	if ( trimString(sTime) == "" )
		return false;
	else
		return true;
}

function IsDateTimeSet(id) 
{
	var oDate = eval("document.forms[0]." + id + "_Date");
	return oDate.value != '';	
}


///*************************************************************************************************
//										Display Grid Functions
//*************************************************************************************************/

var ActionMenuPopup = window.createPopup();

function ActionClicked(control,type)
{	
	var sArgs = ''
	if ( arguments.length == 2  )
	{
		sArgs = g_sDisplayGridRowData;
	}
	else
	{		
		if( arguments.length > 2 )
		{
			for ( var i=0;i<arguments[2].length;i++)
			{
				sArgs += '|' + arguments[2][i];
			}
			if ( sArgs != "" )
				sArgs = sArgs.substr(1);
		}
	}
	sArgs = type + '~' + sArgs;
	
	g_sDisplayGridRowData = "";
	FormSubmit(null, control, sArgs);		
}

function GetArguments()
{
	return g_sDisplayGridRowData.split('|');
}

// This is for toggling the area in the Display Grid
function ToggleRowArea(ctrl, img)
{	
	if ( ctrl.style.display == "none" )
	{
		ctrl.style.display = "inline";
		img.src = GetApplicationPath() + '/Common/Images/icon_minus.gif';
	}
	else
	{
		ctrl.style.display = "none";
		img.src = GetApplicationPath() + '/Common/Images/icon_plus.gif';
	}
}


// this makes a hashtable like array
function MakeDataArray(data)
{
	var dataArray = new Array();
	if ( data.length > 0 )
	{
		//gets the array of field names.
		var aKeyList = g_sDisplayGridFieldDataList.split(',');
		for ( var i=0; i<aKeyList.length; i++ )
		{
			dataArray[aKeyList[i]] = data[i];
		}
	}
	return dataArray;
}

function OpenChoiceMenu(imgCtrl, menuDiv, iconCount,disabledMenus, left,top, hideTab, width)
{
	if ( width == null )
	{
		width = 200;
		left -= 50;
	}
		
	if ( hideTab == null )
		hideTab = false;
	var iIconCount = iconCount;
	
	// create and open the popup.
	ActionMenuPopup = window.createPopup();
	ActionMenuPopup.document.body.innerHTML = menuDiv.innerHTML;
	
	var oStyle = document.styleSheets[0].href;
	ActionMenuPopup.document.createStyleSheet(oStyle);
	
	if ( disabledMenus )
	{
		var aMenus = disabledMenus.split(',');
		for ( var j=0; j<aMenus.length; j++ )
		{
			var oMenu = ActionMenuPopup.document.getElementsByTagName("tr");
			for ( var k=0; k< oMenu.length; k++ )
			{
				if ( oMenu[k].ItemName == aMenus[j] )
				{
					oMenu[k].style.display = "none";
					iIconCount --;
				}
			}
		}
	}
	
	var iHeight = (21 * parseInt(iIconCount,10)) + 29;
	if ( hideTab )
		iHeight -= 21;
	ActionMenuPopup.show(left, top, width, iHeight,imgCtrl );
}

function OpenRowChoiceMenu(imgCtrl, menuDiv, iconCount, disabledMenus)
{
	var iIconCount = iconCount;
	// so it gets any arguments after the forth argument, this will be kept in the arguments
	// array native to javascript. it then builds a pipe delimited list of the variables to be 
	// saved for that row, they are saved in a global variable on the client.
	var sArgumentString = "";
	for ( var i=4;i<arguments.length;i++)
	{
		sArgumentString += "|" + arguments[i] ;
	}
	if ( sArgumentString != "" )
		sArgumentString = sArgumentString.substr(1);
	
	g_sDisplayGridRowData = sArgumentString;
	
	// create and open the popup.
	ActionMenuPopup = window.createPopup();
	ActionMenuPopup.document.body.innerHTML = menuDiv.innerHTML;
	
	var oStyle = document.styleSheets[0].href;
	ActionMenuPopup.document.createStyleSheet(oStyle);
	
	if ( disabledMenus )
	{
		var aMenus = disabledMenus.split(',');
		for ( var j=0; j<aMenus.length; j++ )
		{
			var oMenu = ActionMenuPopup.document.getElementsByTagName("tr");
			for ( var k=0; k< oMenu.length; k++ )
			{
				if ( oMenu[k].ItemName == aMenus[j] )
				{
					oMenu[k].style.display = "none";
					iIconCount --;
				}
			}
		}
	}
	
	var iHeight = (19 * parseInt(iIconCount,10)) + 10;
	ActionMenuPopup.show(15,-3, 200, iHeight,imgCtrl );
}

function OpenDisplayOptions(displayID,showSortDirection)
{
	var sURL= "/Common/UserControls/SetDisplayOptions.aspx?DisplayID=" + displayID;
	if ( showSortDirection == "true")
		sURL += "&DisplaySortDirection=true";
				
	var oDisplayPop = new ModalDialog(sURL, '',725, 500);
	var sVal = oDisplayPop.Show();
	
	if (sVal != null) 
	{		
		ShowProcessMessage();
		return true;
	} 
	return false;
}

function ViewPatronTransactions(){
	var sUrl = "PatronTransactions.aspx";
	SaveAndTransfer(sUrl);
}

function ViewHolderTransactions(){
	var sUrl = "HolderTransactions.aspx";
	SaveAndTransfer(sUrl);
}


///*************************************************************************************************
//										Title List Functions
//*************************************************************************************************/

function TitleListDeleteClicked(recordsSelected)
{
	if (RowsFound(recordsSelected))
	{
		var answer = ConfirmDelete();
		if(answer) ShowProcessMessage();
		return answer;
	}
	else
		return false;
}

///*************************************************************************************************
//										User Setup Functions
//*************************************************************************************************/

// This function is called by the user setup authorization pages. 
// When the user clicks on 'CheckAll' it goes thru all the checkboxes on the page 
// and checks/unchecks it so that the user does not have to do it manually
function CheckAll(oControl, table)
{
	var aTags = document.getElementsByTagName("input");
	for(var i=0;i<aTags.length;i++)
	{
		if (aTags[i].type == "checkbox")
		{
			aTags[i].checked = oControl.checked;
			if ( aTags[i].id != oControl.id )
				table.SetData(aTags[i].pk,'checked', (oControl.checked?1:0));	
		}	
	}
}			

// This decides if the CheckAll checkbox needs to be checked or not
function CheckAllUncheckAll(oControl)
{
	var aTags = document.getElementsByTagName("input");
	var bFlag = false;
	for(var i=0;i<aTags.length;i++)
	{
		if (aTags[i].type == "checkbox")
		{
			if ( aTags[i].id != oControl.id )
			{
				if ( aTags[i].checked )
					bFlag = true;
				else
				{
					bFlag = false;
					break;
				}
			}
		}	
	}
	oControl.checked = bFlag;
}



///*************************************************************************************************
//										AJAX Functions
//*************************************************************************************************/
function AJAXObject(ajaxPage, keys, values)
{
	this.ajaxPage = ajaxPage;
	this.keys = keys;
	this.values = values.replace('&', '%26');
	
	var _Response = QueryAJAX(this.ajaxPage, this.keys, this.values);

	this.GetXML = function()
	{
		oXML = new ActiveXObject("Microsoft.XMLDOM");
		oXML.loadXML(_Response);
		return oXML;
	}
	this.GetResponse = function()
	{
		return _Response;
	}
	function InitializeAJAX()
	{
		try
		{
			var oRequest = new ActiveXObject("Microsoft.XMLHTTP");
		}
		catch(e)
		{
			oRequest = null;
			alert("can't find xmlhttp");
		}
		return oRequest;
	}
	function QueryAJAX(ajaxPage, keys, values)
	{
		var sRequestString = "";
		if ( keys.split(',').length != values.split('~').length )
		{
			alert("error");
			return;
		}
		
		for ( var i=0; i< keys.split(',').length; i++ )
		{
			sRequestString += "&" + keys.split(',')[i] + "=" + values.split('~')[i];
		}
		
		if ( sRequestString.length > 0 ) 
			sRequestString = sRequestString.substring( 1, sRequestString.length  );
		
		var oRequest = InitializeAJAX(); 
		if ( ! oRequest )
			return;

		//var AJAXURL = "//localhost/eosweb/Common/AJAX/" + ajaxPage + ".aspx?" + sRequestString;
		
		var AJAXURL = ajaxPage + "?" + sRequestString;

		if(oRequest != null)
		{
			try
			{
				oRequest.open("GET", AJAXURL, false);
				oRequest.send();
				
				return oRequest.responseText;
			}
			catch (e)
			{
				alert("error with request to ajax");
			}
		}
		return "";
	}
}

function AddNewPicklistItem( ctrl, category )
{
	var nHeight = 200;
	var nWidth = 300; 
	
	var args = new Object();
	args.Category = category;	
	
	var features = "dialogWidth:" + nWidth  + "px;dialogHeight:" + nHeight + "px;help:no;resizable:no;status:no";
	
	window.showModalDialog( GetApplicationPath() + "/Common/UserControls/AddNewItem.aspx", args, features);
	
	if ( args.NewCode )
	{
		var sCatObject = "document.forms[0].Category_" + category + "_Cleared";
		
		var oClearPicklist = eval(sCatObject);
		if ( oClearPicklist )
			oClearPicklist.value = "true";
			
		var iOption = ctrl.length;
		
		ctrl.options[iOption] = new Option(args.NewDescription, args.NewCode);

		ctrl.options[iOption].selected = true;
		ctrl.onchange();
	}
}


function KeyCapture(Key)
{
	if( Key == 13)
	{
		event.returnValue = false;
		return;
	}
}

function EncodeHtml( desc )
{
	var encodedHtml = escape(desc);
	encodedHtml = encodedHtml.replace(/%26quot%3B/g,"%22");
	encodedHtml = encodedHtml.replace(/\//g,"%2F");
	encodedHtml = encodedHtml.replace(/\?/g,"%3F");
	encodedHtml = encodedHtml.replace(/=/g,"%3D");
	encodedHtml = encodedHtml.replace(/&/g,"%26");
	encodedHtml = encodedHtml.replace(/@/g,"%40");
	var sRetValue = unescape(encodedHtml);
	return sRetValue;
}

function GetHiddenField( name )
{
	var val = eval ("document.forms[0]." + name );
	return val;
}

function SetToElectronicResource()
{	
	//Get references to the HTML Table and XML data island
	var oHtmlTable = document.getElementById("tblControlFields");
	
	if ( oHtmlTable.type != "Bibliographic" )
		return;

	var oDataTable = eval(oHtmlTable.dataTable);
	var oLdrRow = oDataTable.GetRowByColumn( 'tag', '000' );
	var o008Row = oDataTable.GetRowByColumn( 'tag', '008' );

	if ( ( oLdrRow ) && ( o008Row ) )
	{
		var sLdrData = oDataTable.GetRowData( oLdrRow, 'data' );
		var s008Data = oDataTable.GetRowData( o008Row, 'data' );
		if ( ( sLdrData ) && ( s008Data ) )
		{
			if ( ( sLdrData.length > 7 ) && ( s008Data.length > 29 ) )
			{
				if ( sLdrData.substr( 6, 1 ) != 'm' )
				{
					var pos = 23;
					if ( 'efgkor'.indexOf( sLdrData.substr( 6, 1 ) ) != -1 )
						pos = 29;

					s008Data = s008Data.substr( 0, pos ) + 's' + s008Data.substr( pos + 1 );
					
					oDataTable.SetRowData( o008Row, 'data', s008Data );

					var oDiv = document.getElementById( "Template_ElectResource" );
					if (oDiv) oDiv.style.display = 'none';
					
					var oDisp = document.getElementById( "Template_ElectDisplay" );
					if (oDisp) oDisp.style.display = 'block';
				}
			}
		}
	}
}
