
var lRecordsCount,lCurrRecordsCount;
var EVENT_REFRESH = 1;
var m_iGridTimer = 0;
var m_sNextCaption='Next Page';
var m_sPrevCaption='Previous Page';

//var m_sMatchCaseCaption = 'Match Case';
//var m_sMatchWholeCaption = 'Match whole column only';
//var m_sApplySearchCaption = 'Apply';
//var m_sCancelSearchCaption = 'Cancel';
//var m_sSearchCaption = 'Search';

var m_oHeaderTimer;
var m_bIsSiteAdmin=false;
//var m_bIsSearchChange=false;
//var m_bIsSearchRunning=false;
//var m_lPageWidth=0;
//var m_lPageHeight=0;
//var m_oTimer;
//var m_bTimerIsActivate=false;
//var m_bSearchBarStatus=false;
//var m_sViewHTML='';
//var m_oViewCombo;
var m_bIgnoreResize=false;
var m_lShrinkSize=0;
var m_lBackupOverideHeight=0;
var m_bNoResize =false;
//var m_oSetTimer;
//var m_oViewsCombo=null;
var m_bNavigatorNotFound=false;

var m_bGridNoRefreshOrExport = false;

//var m_bFromResizeHandler=false;

// tomer
var m_arGrids = new Array();


var btnHoverHandlerJS = ' onmouseover="hoverGridBarButton(1);" onmouseout="hoverGridBarButton(0);" ';


// Types ///////////////////////////////////
function ColumnsComboValue(ColumnID,ColumnName)
{
	this.ColumnID = ColumnID;
	this.ColumnName = ColumnName;
}

function handleImageError()
{
	getDomElement('LABEL_TABLE').className='Shown';
	getDomElement('QUICK_VIEW_IMG').className='Hidden';
}

function GridPages(PageID, NavigatorHTML)
{
	this.PageID=PageID;
	this.NavigatorHTML=NavigatorHTML;
}

function Argument(Name, Value)
{
	this.Name = Name;
	this.Value = Value;
}

function WhereClause(ID, Arguments)
{
	this.ID = ID;
	this.Arguments = Arguments;
}

function SortOrderType(ColumnID,Position,Order)
{
	this.ColumnID = ColumnID;
	this.Position = Position;
	this.Order = Order;
}

/////////////////////////////


// Grid Constractor ////////////////////////////////////////////////////
function Grid()
{	        
	this.ID = null;		
	this.ViewID = null;
	this.OverideHeight = null;
	this.ShowView = null;
	this.NoScroll = null;
	this.SortOrder = null;
	this.WhereClause = null;
	this.PageSize = null;
	this.PageNumber = null;
	this.RecordsCount = null;
	this.ClassID= null;
	this.TopOffset= null;
	this.HasCheckBox = null;
	this.ColumnsCombo = null;
	this.SearchString = null;
	this.SearchColumnID = null;
	this.HasSummaryPage = 0;
	this.NoNavigate = null;
	this.NoSorting = null;
	this.NoSearching = null;
	this.IsCaseSensitive = false;
	this.IsMatchWhole = false;
	this.ShowSearch = null;
	this.HiddenColumns = null;
	this.CollectIDs=null;
	this.IDs = null;
	this.FromRecord = null;
	this.ToRecord = null;
	this.MaxRows = null;
	this.NavigateToPage = false;
	
	this.HasSelectColumn = null;
	this.HasMenuColumn = null;
	
    this.RowClass = null;
    this.LinkClass = null; 
    this.CellClass = null;
    this.NoHeader = null;
    this.LastID = 0;	
    
    this.MenuIconColumnName = null;
    this.MenuIcon = '';
    
    this.ExecType = 0;  //0 - Normal, 1 - No SQL, 2- No HTML
    this.IsFirstLoad = false;  //true = load last view from db
    this.IsUsingSavedState = false; //true = loaded last view from db
	
	this.AsyncRefresh = false; //also makes build async
	this.AsyncCallback = null; //function to call after an async build/refresh
	
	
	this.GotoPage = GotoPage;
	this.GetSelection = GetSelection;
	this.GetItem = GetItem;
	this.ItemExists = ItemExists;
	this.applyView = applyView;
	this.Sort = Sort;
	this.Filter = Filter;
	this.ApplyMultyFilters = ApplyMultyFilters;
	this.MultyFilters = null;
	this.IgnoreView = null;
	this.Search = Search;
	this.MarkSelection = MarkSelection;
	this.MarkAll = MarkAll;
	this.Refresh = RefreshGrid;
	this.RefreshCallback = RefreshGridCallback;
	this.Build = BuildGrid;
	this.BuildCallback = BuildGridCallback;
	//this.HandleScript = HandleGridScript;
	this.getRecordsCount = getRecordsCount;
	this.getClassID = getClassID;
	this.getGridCollection = getGridCollection;
	this.hideGridScroll = hideGridScroll;
	this.NoPaging = null;
	this.ForcingSortColumnID=null;
	this.isScrollAble = isScrollAble;
	this.GetHeight = GetHeight;
	this.GetMoreData = GetMoreData;
	this.SetNavigator = SetNavigator;
	this.setHeader = setHeader;
	this.setTitles = setTitles;
	this.attachEvent = GridAttachEvent;
	this.dettachEvent = dettachEvent;
	this.SetHasCheckBox= SetHasCheckBox;
	
	this.GotoNextPage= GotoNextPage;
	this.GotoPrevPage= GotoPrevPage;
	this.GotoFirstPage = GotoFirstPage;
	this.GotoLastPage = GotoLastPage;
	this.GotoPage = GotoPage;
			
	this.isFilter=false;
	this.Listeners = new Array();
	this.RaiseEvent = RaiseEvent;
	
	this.OpenSearch = OpenSearch;
	this.ApplySearch = ApplySearch;
	this.CancelSearch = CancelSearch;
	this.HandleSearch = HandleSearch;

	this.ReloadSearchCombo = ReloadSearchCombo;
	//this.shrinkGrid = shrinkGrid; //tomer
	//this.ResetShrinkGrid = ResetShrinkGrid; //tomer
	this.PrintGrid = PrintGrid;
	this.export2Excel     = export2Excel;
	this.getNavigatorGrid = getNavigatorGrid;
	this.editView =editView;
	this.setGridViews=setGridViews;
	this.setGridTitle=setGridTitle;
	this.setGridHeight = setGridHeight;
	//this.onResizeHandler = onResizeHandler; //tomer
	this.handleSelectedRow = handleSelectedRow;
	this.GetGridIds = GetGridIds;
	this.GetGridSQLIDs = GetGridSQLIDs;
	this.GetGridXML = GetGridXML;
	this.getExcelXML = getExcelXML;
	this.markRow = markRow;
	this.StoreNavigatorHTML = StoreNavigatorHTML;
	this.FirstLoad = true;
	this.SaveState = true;

	// tomer 6/22
	this.KillSearch = KillSearch;
	this.resizeHandler = resizeHandler;
	this.ShowPage = ShowPage
	this.HidePages = HidePages

	this.setFormHTMLtoRow = setFormHTMLtoRow;
	this.cleanFormHTMLtoRow = cleanFormHTMLtoRow;

	this.BackupOverideHeight = null;
	this.IsSearchChange=false;
	this.IsSearchRunning=false;
	this.SearchIsActive=false;

	this.SetGridHeightError = 0;
	//this.RetryCounter = 0;

	this.GridPages = new Array();

	this.throwRow = throwGridRow;
	this.LastSelectedID = -1;

	this.initGrid = initGrid;
	
    
    this.ClearLastView = ClearLastView;
    
    this.SanitizeImagePaths = SanitizeImagePaths;
    
    
    this.aManuallySelectedArray = new Array();

	if ((frameElement != null) && (frameElement.ResizeFrame == 'true'))
		this.NoScroll=1;
	
}


function initGrid()
{    
    //this.setGridViews();
	this.setGridTitle();
	this.SetNavigator();
	this.setTitles(this.ID, this.PageNumber);
	
	this.setGridViews();
	this.setHeader();
	
	
	this.GridBody = getDomElement('GRID_PAGE_' + this.ID) == null ? null : getDomElement('GRID_PAGE_' + this.ID).parentNode;
	
	try
	{
	    this.setGridHeight();
	} catch (e) {}		
    
    
    if (this.ShowSearch)
        window.setTimeout("getGridByID('" + this.ID + "').OpenSearch(true);", 100);
}


function GetGridIds()
{
    var IDs = this.IDs;
	if (IDs == null)
	    IDs = "";
	return (IDs);
}

function GetGridSQLIDs()
{
	var Request, Response , Arguments, Argument, Index;
	var oParameters = new Array();
	var sSql;

	sXML = this.GetGridXML();
	var oBroker = getBroker();
	var oRequest = oBroker.createRequest(window);
	oRequest.setPage(m_PageID,
				 	 m_ObjectID,
					 m_ClassID,
					 m_ParentObjectID,
					 m_ParentClassID,
					 m_SubType,
					 m_TaskID,
					 m_VirtualParentObjectID,
					 m_VirtualParentClassID);

	Response = oRequest.Execute('2000000', 'ids', sXML);
    	    
	return Response;
}

function markRow(ObjectID,status)
{
	var oItem = getDomElement('CHK_' + this.ID + '_' + ObjectID);
	var sCSS='';
	status = (status==null) ? false : status;

	if (oItem==null)
		return;

	while (oItem.tagName!='TR')
		oItem = oItem.parentNode;

	if(status)
	{
		if(oItem.ORG_CLASS=='BoldRow')
			sCSS= 'BoldSelectedRow';
		else
			sCSS= 'GridSelectedRow';
	}
	else
		sCSS = oItem.ORG_CLASS;
	oItem.className = sCSS;
}
	
function handleSelectedRow(CheckBoxObj)
{
    var iIndex=0;
	var oItem=CheckBoxObj;
	var sCSS=''
	var oObjectID = oItem.getAttribute('OBJECT_ID');
	var iRemoveIndex = -1;


	
	while (oItem.tagName.toUpperCase() != 'TR')
	    oItem=oItem.parentNode;		

	gridObj = (this.aManuallySelectedArray) ? this : getGridByID(getParentGridID(oObjectID));	
	
	
	try 
	{
	    gridObj.onCboxClick(CheckBoxObj);
	}
	catch (e) {}
	
	
	if (CheckBoxObj.checked)
	{
		oItem.className = 'GridSelectedRow';			
		if (grid_FindInArray(gridObj.aManuallySelectedArray, oObjectID) == -1) 
		        gridObj.aManuallySelectedArray.push(oObjectID);
	}
	else
	{
		oItem.className = oItem.ORG_CLASS;

		iRemoveIndex = grid_FindInArray(gridObj.aManuallySelectedArray, oObjectID);			    
		if (iRemoveIndex>-1) 
		    gridObj.aManuallySelectedArray.splice(iRemoveIndex, 1);
	
	}
}


function grid_FindInArray(arr, toFind)
{
    for (var i = 0; i < arr.length; i++)
        if (arr[i] == toFind)
            return i;
    return -1;        
}



function getParentGridID(objectID)
{
    for (var iGridID in  m_arGrids)
    {			       
        var oGrid = m_arGrids[iGridID];
        var sGridIDS = oGrid.GetGridIds();
        
        var aGridIDS = sGridIDS.split(", ");

        for (var iIndex2 = 0; iIndex2 < aGridIDS.length; iIndex2++)
            if(objectID == aGridIDS[iIndex2]) 
                return iGridID;
    }
    return -1;
}


function setGridTitle()
{
	var sHTML='<LABEL Class="Label">&#160;' + m_sClassName +  '&#160;&#160;</LABEL>';
	var oTD = getDomElement('GridName');
	if (oTD != null)
	{
		oTD.innerHTML = sHTML;
		oTD.className="Shown";
	}
	oTD=null;
}

////////////////////////////////////////////////


function initGrids()
{
	for (var iGridID in  m_arGrids)
        m_arGrids[iGridID].setGridHeight();
}

function resizeHandler()
{
	var oDiv = getDomElement('GRID_DIV_' + this.ID);
	if (oDiv != null)
	    oDiv.style.width = '100%';
}

function setHeader(Object)
{
	return;
	var oGridTRHeader;
	var oGridHeader;
	var sHTML='';
	var sHeaderHTML='';
	oGridTRHeader = getDomElement('GRID_TR_HEADER_' + this.ID);
	oGridHeader = getDomElement('GRID_INSERTED_HEADER_' + this.ID);

//		if (oGridHeader == null)
//		{
	var aCells=oGridTRHeader.cells;

	for (iIndex = 0; iIndex<aCells.length; iIndex++)
		sHeaderHTML+='<TD class = "' + aCells(iIndex).className + '" style="width:' + aCells(iIndex).style.width +  '">' + aCells(iIndex).innerHTML + '</TD>'

	sHeaderHTML='<TABLE STYLE="table-layout:fixed"  cellpadding="1" cellspacing="1"  BORDER="0"><TR class="GridHeader">' + sHeaderHTML + '</TR></TABLE>';

	sHTML='<DIV  STYLE="position:absolute;left:0;top:30;width:' + oGridTRHeader.style.width + '" ID = "GRID_INSERTED_HEADER_' + this.ID + '">';//<TABLE STYLE="table-layout:fixed"  cellpadding="1" cellspacing="1"  BORDER="0"><TR class="GridHeader">';
	sHTML+=	sHeaderHTML+'<TD style="width:11">&#160;</TD>';
	sHTML+='</DIV>';//</TR></TABLE>

	document.body.insertAdjacentHTML("afterBegin",sHTML);
}

function checkKey (GridID)
{
	if(event.keyCode==13)
		getGridByID(GridID).ApplySearch();
}

function KillSearch(DontRefreshGrid)
{
	DontRefreshGrid = DontRefreshGrid ? true : false;
	this.CancelSearch(DontRefreshGrid);

	var oSearchTABLE = getDomElement('SEARCH_TABLE_' + this.ID);
	if (oSearchTABLE)
	{
		var oParent = oSearchTABLE.parentNode;
		oParent.removeChild(oSearchTABLE);
		oParent=null;
	}

}

function StoreNavigatorHTML()
{
	var oNavigatorWindow = self;
	var iIndex = -1;
	var sNavigatorHTML = '';
	var oNavigator = null;

	if (parent != self)
		if (parent.name == 'SPLIT')
			oNavigatorWindow = parent.parent;

	oNavigator = oNavigatorWindow.document.getElementsByName('GridNavigator' + this.ID);

	iIndex = this.PageNumber-1;

	if (oNavigator.length>0)
		oNavigator=oNavigator[iIndex];

	if (oNavigator == null) return;


	if (this.GridPages[iIndex] != null && this.GridPages[iIndex].NavigatorHTML == null)
		iIndex = 0;

	sNavigatorHTML = oNavigator.innerHTML
	if (this.GridPages[iIndex] != null)
	    this.GridPages[iIndex].NavigatorHTML = sNavigatorHTML ;
	//oNavigator.innerHTML = sNavigatorHTML;

}

function HandleSearch()
{			
	if (this.IsSearchRunning)
		this.CancelSearch();			
	else
		this.OpenSearch();
	
	var oImg = getDomElement('IMG_SEARCH_' + this.ID);
	oImg.src = this.IsSearchRunning ? createGeminiImage('images/icons/gif_grey/magnifier_cancel.gif') : createGeminiImage('images/icons/gif_grey/magnifier.gif');
	oImg.alt = this.IsSearchRunning ? "Cancel Search" : "Search";
}

function OpenSearch(dontClearText)
{
	var iIndex=0
	var sHTML='';
	var sOptions='';
	
	if (dontClearText == null)
	    dontClearText = false;

	// search Bar is Open
	//if (this.IsSearchRunning)
	//{
		// Cancel the Filter The Refresh the Grid back to normal
	//	this.CancelSearch();
	//}
	//else
	//{
		// Search bar is closed
		// init the Active Search status
		this.SearchIsActive = false;
		this.IsSearchRunning = true;
		// Open the Search Bar


		var oSearchTABLE = getDomElement('SEARCH_TABLE_' + this.ID);
		if  (oSearchTABLE !=null)
		{
		    if (!dontClearText)
			    getDomElement('TXT_SEARCH_FOR_' + this.ID).value='';
			oSearchTABLE.className = 'BackgroundSearch';				
		}

		if (!dontClearText)
		{
		    try 
		    {
		        getDomElement('TXT_SEARCH_FOR_' + this.ID).focus();
		    } catch (e) {}
		}
	//}
	
	this.setGridHeight();
	this.StoreNavigatorHTML();
}

function CancelSearch(DontRefreshGrid)
{
	var oSearchFor = getDomElement('TXT_SEARCH_FOR_' + this.ID);

	if (oSearchFor != null)
	{
		if (this.IsSearchChange || oSearchFor.value!='')
		{
			if (DontRefreshGrid)
			{
				this.SearchColumnID=null;
				this.SearchString=null;
			}
			else
				this.Search(0,null);
		}

		var oTable = getDomElement('SEARCH_TABLE_' + this.ID);
		if (oTable.className!='Hidden') oTable.className='Hidden';
		this.setGridHeight();
	}



	this.IsSearchRunning=false;
	this.SearchIsActive=false;
	this.StoreNavigatorHTML();		
}

function vs_valid_date(item)
{
	var strErrorMsg = display_name(item);
	if (isNaN(Date.parse(item.value)))
	{
		item.focus();
		alert(strErrorMsg + " must be a valid Date");
		return false;
	}

	var dtItem = new Date(Date.parse(item.value));
	item.value = dtItem.toSimpleForm();
	return true;
}


function ApplySearch()
{	
	var sStr='';
	var oTxtField=getDomElement('TXT_SEARCH_FOR_' + this.ID);
	var oCboField=getDomElement('CBO_SEARCH_' + this.ID);
			
	for (var i=0;i<oCboField.options.length;i++)
		if (oCboField.options[i].selected)
		{
			sStr+=oCboField.options[i].value;
			break;
		}
	
	var sValue = oTxtField.value;
	var oDate = new Date(sValue)
	
	if (oDate==null || isNaN(oDate))
		sValue = wellFormXML(sValue);
	else
		sValue = ConvertToServerFormat(sValue);

	this.Search(sStr,sValue,getDomElement('CHK_MATCH_WHOLE_' + this.ID).status, getDomElement('CHK_MATCH_CASE_' + this.ID).status);
}


function SetHasCheckBox(Value)
{
	this.HasCheckBox= Value;
}
	
function GotoPage(pageNbr)
{
    if (pageNbr < 1)
        return;
    if (this.PageNumber < (this.RecordsCount/this.PageSize))
        this.PageNumber++;
        
    this.NavigateToPage = true;
	this.PageNumber = pageNbr;
	this.Refresh(false);
	this.NavigateToPage = false;
	
	if(typeof(pagingGridOnload)=="function") 
	    pagingGridOnload();
    
	window.document.body.focus();
}

function GotoNextPage()
{
	if (this.ToRecord < this.RecordsCount) 
	    this.GotoPage(this.PageNumber + 1);
}

function GotoPrevPage()
{
	if (this.PageNumber > 1) 
	    this.GotoPage(this.PageNumber - 1);
}	

function GotoFirstPage()
{
    if (this.PageNumber > 1) 
        this.GotoPage(1);
}

function GotoLastPage()
{
    if (this.ToRecord < this.RecordsCount) 
        this.GotoPage(Math.ceil(this.RecordsCount / this.PageSize));
}


function PrintGrid()
{
	printGridToReport();
}

function export2Excel()
{
    var sURL = "?do=SendFile&download=0&ClassID=2000000";
    sURL += "&ObjectID=" + this.ID;	    	    
    sURL += "&ParentObjectID=" + m_ParentObjectID;
    sURL += "&ParentClassID=" + m_ParentClassID;
    sURL += "&FileArguments=" + escape(this.getExcelXML());

    open(sURL);			    	    
}

function SetNavigator()
{		
	this.GridPages[this.PageNumber-1] = new GridPages(this.PageNumber, sStr);
		
//		alert(this.NoNavigate);
	if (this.NoNavigate) return;
	var sStr;
	//var iFromRecord, iToRecord, iTotRows;
	//var sPluse;
	var oGrid;

   
   
   
	sStr = '<SPAN>';
	sStr += '<TABLE nowrap="1" cellpadding="0" cellspacing="0" border="0" Class="GridNavigator" ID="GRID_NAVIGATOR_' + this.ID + '">';
	sStr += '<TR nowrap="1">';

    sStr += '<TD width="16">';
    sStr += '<IMG SRC="skins/common/images/indicator.gif" style="display:none;" ID="GRID_INDICATOR_' + this.ID + '" />';
    sStr += '</TD>';
    
    if (m_bGridNoRefreshOrExport == null || !m_bGridNoRefreshOrExport)
    {				
	    if (m_bIsSiteAdmin)
	    {
		    //sStr += '<TD nowrap="1">' + m_sViewHTML + '</TD>'
		    sStr += '<TD>';
		    sStr += '<IMG ' + btnHoverHandlerJS + ' NAME=IMG_EDIT_VIEW ID=IMG_EDIT_VIEW alt="Edit View" Class="GridBarButton16" src="';
		    sStr += createGeminiImage('images/hd_captions.gif') + '" onclick=\'getGridByID("' + this.ID + '").editView('
		    sStr += this.ViewID + ',true,"' + this.ID + '");\'/>';
		    sStr += '</TD>';
	    }
		
	    sStr += '<TD Width="3%">'
	    sStr +=     '<IMG ' + btnHoverHandlerJS + ' NAME="IMG_REFRESH" ID="IMG_REFRESH" alt="Refresh" Class="GridBarButton16" src = "' + createGeminiImage('images/icons/gif_grey/arrow_refresh.gif') + '" onclick=\'getGridByID("' + this.ID + '").Refresh();\'></IMG>';
	    sStr += '</TD>';
	    //sStr += '<TD Width="3%"><IMG NAME = "IMG_PRINT" ID = "IMG_PRINT" alt ="Print" Class="GridBarButton" src = "' + createGeminiImage('images/gb_print.gif') + '" onclick=\'getGridByID("' + this.ID + '").PrintGrid();\'></IMG></TD>';
	    sStr += '<TD Width="3%">';
	    sStr +=     '<IMG ' + btnHoverHandlerJS + ' NAME="IMG_EXPORT" ID="IMG_EXPORT" alt="Export To Excel" Class="GridBarButton16" src = "' + createGeminiImage('images/icons/gif_grey/page_excel.gif') + '" onclick=\'getGridByID("' + this.ID + '").export2Excel();\'></IMG>';
	    sStr += '</TD>';
		
	    if (!this.NoSearching)
	    {
	        var searchTxt = this.IsSearchRunning || this.ShowSearch ? 'Cancel Search' : 'Search';
	        var searchImg = this.IsSearchRunning || this.ShowSearch ? 'magnifier_cancel.gif' : 'magnifier.gif';
            
            sStr += '<TD><span class="GridBarDivider"/></TD>';		    
	        sStr += '<TD Width="3%">';
	        sStr += '<IMG ' + btnHoverHandlerJS + ' ID="IMG_SEARCH_' + this.ID + '" alt="' + searchTxt + '" Class="GridBarButton16" src="' + createGeminiImage('images/icons/gif_grey/' + searchImg) + '" onclick=\'getGridByID("' + this.ID + '").HandleSearch();\' />';
	        sStr += '</TD>';
	    }
	}

	sStr += '<TD Width="1%"><span class="GridBarDivider"/></TD>';
	sStr += '<TD Class="RecordsCount" style="width:110px; text-align:right;" nowrap="true">';
	sStr += '<LABEL>';
	sStr += '&nbsp;&nbsp;' + this.FromRecord + '..' + this.ToRecord + ' / ' + this.RecordsCount;
	if (this.MaxRows == this.RecordsCount) sStr += "+";
	sStr += '&nbsp;'
	sStr += '</LABEL>';

	sStr += '</TD>';
	sStr += '<TD Width="1%"><span class="GridBarDivider"/></TD>';

	if (!this.NoPaging)
	{	
		if (this.FromRecord > 1)
	    {
		    sStr += '<TD>';
		        sStr += '<a href="#" onclick="getGridByID(\'' + this.ID + '\').getNavigatorGrid().GotoFirstPage();return false;">';
		        sStr += '<img ' + btnHoverHandlerJS + ' src="skins/common/images/icons/gif_grey/resultset_first.gif" border="0" alt="Go To First Page" />';
		        sStr += '</a>';
		    sStr += '</TD><TD>';
		        sStr += '<a href="#" onclick="getGridByID(\'' + this.ID + '\').getNavigatorGrid().GotoPrevPage();return false;">';
		        sStr += '<img ' + btnHoverHandlerJS + ' src="skins/common/images/icons/gif_grey/resultset_previous.gif" border="0" alt="Go To Previous Page" />';
		        sStr += '</a>';
		    sStr += '</TD>';
		} 
		else
		{
		    sStr += '<TD>';
		        sStr += '<img src="skins/common/images/icons/gif_grey/resultset_first_disabled.gif" border="0" alt="Goto First Page" />';
		    sStr += '</TD><TD>'; 
		        sStr += '<img src="skins/common/images/icons/gif_grey/resultset_previous_disabled.gif" border="0" alt="Go To Previous Page" />';
		    sStr += '</TD>';
		}			
		
		sStr += '<TD>&#160;</TD>';
        
        if (this.ToRecord < this.RecordsCount)
	    {
	        sStr += '<TD>';
		        sStr += '<a href="#" onclick="getGridByID(\'' + this.ID + '\').getNavigatorGrid().GotoNextPage();return false;">';
		        sStr += '<img ' + btnHoverHandlerJS + ' src="skins/common/images/icons/gif_grey/resultset_next.gif" border="0" alt="Go To Next Page" />';
		        sStr += '</a>';
			sStr += '</TD><TD>';    
		        sStr += '<a href="#" onclick="getGridByID(\'' + this.ID + '\').getNavigatorGrid().GotoLastPage();return false;">';
		        sStr += '<img ' + btnHoverHandlerJS + ' src="skins/common/images/icons/gif_grey/resultset_last.gif" border="0" alt="Go To Last Page" />';
		        sStr += '</a>';
		    sStr += '</TD>';
		} 
		else
		{
		    sStr += '<TD>';
		        sStr += '<img src="skins/common/images/icons/gif_grey/resultset_next_disabled.gif" border="0" alt="Go To Next Page"/>';
		    sStr += '</TD><TD>'; 
		        sStr += '<img src="skins/common/images/icons/gif_grey/resultset_last_disabled.gif" border="0" alt="Go To Last Page"/>';
		    sStr += '</TD>';  			
		}
	}
	sStr += '<TD Width="82%">&nbsp;</TD>';
	sStr += '</TD>';
	sStr += '</TR>';
	sStr += '</TABLE>';
	sStr += '</SPAN>';
	
	var sLastViewHtml = '';
	if (this.IsUsingSavedState)
    {
        sLastViewHtml += '<table nowrap="1" cellpadding="0" cellspacing="0" border="0"><tr>';
        sLastViewHtml += '<td style="padding-right:3px;"><nobr>Using Last View (<a href="#" onclick="getGridByID(\'' + this.ID + '\').ClearLastView();return false;">clear</a>)</nobr></td>';
        sLastViewHtml += '<td><span class="GridBarDivider"/></td>';
        sLastViewHtml += '</tr></table>';
    }
	
	//alert(sLastViewHtml);

	var oNavigator = null;
	var oNavigatorWindow = self;



	oNavigator = oNavigatorWindow.document.getElementsByName('GridNavigator' + this.ID);
	if (oNavigator.length>0)
	{
	    //debugger;
	
		oNavigator = oNavigator[oNavigator.length-1];
		oNavigator.innerHTML = sStr;
		
		var oLastView = document.getElementById('GridBarLastView' + this.ID);
		if (oLastView != null)
		    oLastView.innerHTML = sLastViewHtml;
	}
	else
	{
		m_bNavigatorNotFound = true;
		var oGrid = getDomElement('SEARCH_TABLE_' + this.ID);
		if (null != oGrid)
		{
		    var sHtml = '<div class = "GridBar" style="text-align:right;">';
		    sHtml += '<TABLE ID = "GRID_NAVIGATOR_TABLE" cellpadding="0" cellspacing="0" border="0"  class = "GridBar" style="width:99%;">';
		    sHtml += '<TR>';
		    sHtml += '<TD width="100%">&#160;</TD>';
		    sHtml += '<TD ID = "GridBarLastView' + this.ID + '" NAME = "GridBarLastView' + this.ID + '">' + sLastViewHtml + '</TD>';
		    
		    sHtml += '<TD ID = "GridBarViewPlaceHolder' + this.ID + '" NAME = "GridBarViewPlaceHolder' + this.ID + '"/>';
		    sHtml += '<TD ID = "GridNavigator' + this.ID + '" NAME = "GridNavigator' + this.ID + '">' + sStr + '</TD>';
		    sHtml += '</TR>';
		    sHtml += '</TABLE>';
		    sHtml += '</div>';
		    
		    oGrid.parentNode.insertAdjacentHTML('beforeBegin',sHtml);
		}
	}
}

// Private Functions ///////////////////////

function hoverGridBarButton(state)
{
    var o = event.srcElement;
    
    while (o != null && o.tagName.toLowerCase() != 'td')
        o = o.parentNode;
    
    if (o == null)
        return;
    var os = o.style;
    os.border =     (state == 1) ? '1px solid #bbbbbb' : '0px';
    os.padding =    (state == 1) ? '1px' : '2px';
    os.background = (state == 1) ? '#d0d0ff' : 'transparent';
}



function setTitles(GridID, Page)
{}

function setTitlesTimer(GridID, Page)
{}

function onGridClick(ObjectID, ClassID, OpenSummaryPage)
{
	if (OpenSummaryPage)
		hideSummaryPage();
	return openGeminiWindow(null,ObjectID,ClassID,m_ParentObjectID,m_ParentClassID,m_TaskID,m_SubType);
}


function hideColumn(ColumnID)
{

	var aColumns = document.getElementsByName(ColumnID.toString());
	for (var i=0;i<aColumns.length;i++)
		aColumns[i].className = 'Hidden';

}

function getGrid()
{//fix naama
    var iCount = 0;
    
    for (var iGridID in  m_arGrids)
        iCount++;
    
    if(iCount == 1)
        for (var iGridID in  m_arGrids)
            return(m_arGrids[iGridID]);
    else
        return(null);
}

function getGridByID(ID)
{
	try
	{
		//eval will throw an exception if grid not found
		
		//var m_sGridIdentifier = "m_oGrid" + ID;
		//var oGrid = eval(m_sGridIdentifier);			
		var oGrid = m_arGrids[ID];
		
		return(oGrid);
	}
	catch(e)
	{
		return(null);
	}
}


function getNavigatorGrid()
{
	var iIndex = 0;
	var oGridWindow = self;
	var oSplit = getDomElement('SPLIT');

	if ((oSplit != null) && (frames.length >= 0))
	{
		oSplit = frames(0);
		if (oSplit != null)
			while (iIndex < oSplit.frames.length)
			{
				if (typeof(oSplit.frames[iIndex].getGrid) == 'function')
				{
					oGridWindow = oSplit.frames[iIndex];
					break;
				}
				iIndex++;
			}
	}
	// retval
	return(oGridWindow.getGridByID(this.ID));
}

function GetMoreData()
{
	this.Refresh(true);
}

function GetHeight()
{
	return this.Height;
}

function isScrollAble()
{
	return this.ScrollAble;
}
function getClassID()
{
	return this.ClassID;
}

function getRecordsCount()
{
	return this.RecordsCount;
}

function setGridHeight(TopOffset,PageNumber)
{
	var iDelta = 20;
	var lheight = 0;
	//WriteToLog('setGridHeight');

	// for shrink grid
	if (m_bNoResize) return;

	if 	(this.NoScroll==1)
	{
		this.resizeHandler();

		var oFrame;
		
		if (window.name != '')
		    oFrame = parent.document.getElementById(window.name);
		if (oFrame)
		{
			var oWorkspace = getDomElement('WORKSPACE');
			if (oWorkspace != null) return; // the grid is part of the page, not in IFRAME

			var oGrid = getDomElement("GRID_DIV_" + this.ID);
		    if (oGrid == null) return;
			var iFrameHeight = oGrid.offsetHeight;
			var oSearchTable = getDomElement("SEARCH_TABLE_" + this.ID);
			if (oSearchTable != null)
				if (oSearchTable.className != 'Hidden')
					iFrameHeight+=oSearchTable.offsetHeight;
			iFrameHeight+=55;
		}

        if ((null != top.resizeFrame) && ('undefined' != top.resizeFrame)) 
            top.resizeFrame();

		return;
	}

	this.resizeHandler();

	if (m_bIgnoreResize==true)
	{
		m_bIgnoreResize=false;
		return;
	}

	if (PageNumber==null)
	{
		TopOffset = this.TopOffset;
		PageNumber = this.PageNumber;
	}

	var oGrid = getDomElement('DIV_DATA_' + this.ID + '_' + this.PageNumber);
	if (oGrid != null)
	{
		if (this.OverideHeight==0)
		{
			var iParentPageID=0;
			try
			{
				iParentPageID=top.m_PageID;
			}
			catch(e)
			{
				iParentPageID=0;
			}
			
			//debugger;
							
			if (iParentPageID == 1030300)
				iDelta+=5;
			else
				if (this.FirstLoad)
				{
					this.FirstLoad=false;
					iDelta+=9;
				}

			if (getDomElement('DataDiv0')==null)
			{
				var oDiv = getDomElement('DIV_DATA_' + this.ID + '_' + this.PageNumber);
				if (oDiv!=null)
				{
					var oData = document.getElementsByName('TOPOFFSET_DIV');
					if (oData.length>0 && !m_bNavigatorNotFound)
                        iDelta+=(oData[0].firstChild.offsetHeight-24);
						

					iDelta+=parseFloat(TopOffset);
					//-- Add Grid Header Delta
					var oH =  getDomElement('GRID_HEADER_' + this.ID + '_' + this.PageNumber);
					iDelta+=oH.offsetHeight;

					//-- Add Search Delta
					
					var oTable = getDomElement('SEARCH_TABLE_' + this.ID);
					if (oTable!=null && oTable.className != 'Hidden' && oTable.className != 'HIDDEN')
						iDelta+=22;
                    

					var oGridDiv = getDomElement("GRID_DIV_" + this.ID);
					oGridDiv.className='Hidden';
					lheight = document.body.offsetHeight - iDelta;
											
					oGridDiv.className='Shown';
				}
			}
			else
				lheight=200;
			if (m_lShrinkSize>0)
			{
				lheight-=m_lShrinkSize;
				this.OverideHeight=lheight;
			}
		}
		else
		{
			lheight=this.OverideHeight;
		}


		try
		{
			if ((lheight)!=0)
			{
				m_lPageHeight = lheight;
	  			oGrid.style.height = lheight;
			}
		}
		catch(e)
		{
			// sometimes the page is not visible and you get an error, try for 5 times before stoping
			if (this.SetGridHeightError < 5)
			{
				this.SetGridHeightError++;
				setTimeout('getGridByID("' + this.ID + '").setGridHeight(' + TopOffset + ',' + PageNumber + ')', 1000);
			}
			else
			{
				if(lheight < 0)
					this.SetGridHeightError = 0;
				else
					alert('Internal error: setGridHeight, height = ' + lheight + ' ' + e);
			}
			return;
		}

		if (null != oGrid)
		{
  			oGrid.style.overflowY = 'auto';
  		}

  		this.SetGridHeightError = 0;
	}
}

function hideGridScroll()
{
	var oGrid = getDomElement('GRID_BODY_' + this.PageNumber);
	if (oGrid != null)
	{
		oGrid.style.height = '300px';
		oGrid.style.overflowY = '';
	}
}

function ItemExists(ObjectID, ColumnName)
{
	var oInput = getDomElement(this.ID + '_' + ObjectID + '_' + ColumnName);
	return (null!=oInput)
}	

function GetItem(ObjectID, ColumnName)
{
	//returns the value of a cell        
	var oInput = getDomElement(this.ID + '_' + ObjectID + '_' + ColumnName);
	if (null==oInput)
	{
		alert('Cant Find Column ' + ObjectID + '_' + ColumnName);
		return;
	}

	var sStr = (oInput.outerText != null && oInput.outerText != '') ? oInput.outerText : oInput.innerHTML;
	
	var iBegin = sStr.toUpperCase().indexOf('<G_VALUE>');
	var iEnd = sStr.toUpperCase().indexOf('</G_VALUE>');
	if (iEnd>0)
		sStr= sStr.substring(iBegin+9,iEnd);
	sStr=sStr.replace('&nbsp;','');

	// boolean
	if (sStr.indexOf('gd_checked.gif') > -1) return (true);
	if (sStr.indexOf('gd_unchecked.gif') > -1) return (false);

	return trim(sStr);
}

function Sort(Column,Order)
{
	var bFound=false;
	var iPos=0;
	var iLength=0;
	var oSortOrderType;
	if (event.ctrlKey)
	{
		for (iIndex = 0; iIndex<=this.SortOrder.length - 1;iIndex++)
			if (this.SortOrder[iIndex].ColumnID== Column)
			{
				this.SortOrder[iIndex].Order=Order;
				bFound=true;
			}
		if (!bFound)
		{
			iLength=this.SortOrder.length;
			iPos = parseInt(this.SortOrder[iLength-1].Position);
			iPos++;
			oSortOrderType= new SortOrderType(Column,iPos,'ASC');
			this.SortOrder[iLength]=oSortOrderType;
		}
	}
	else
	{
		this.SortOrder = null;
		this.SortOrder = new Array;
		iLength=0;
		iPos = 1;
		oSortOrderType= new SortOrderType(Column,iPos,Order);
		this.SortOrder[iLength]=oSortOrderType;
	}

	//this.FromRecord=0;
	//this.ToRecord=0;
	this.PageNumber=1;
	this.isFilter=false;
	this.Refresh(true);
	this.RaiseEvent('Sort');
}

function Search(ColumnID, SearchString, MatchWhole, CaseSensative)
{
	this.SearchColumnID= ColumnID;
	this.SearchString= SearchString;
	this.IsMatchWhole= MatchWhole;
	this.IsCaseSensitive = CaseSensative
	//this.FromRecord=0;
	//this.ToRecord=0;
	this.PageNumber=1;
	this.isFilter=true;
	
	this.SearchIsActive = (ColumnID>0);

	//m_bIsSearchRunning=false;
	//m_bSearchIsActive=false;

	this.Refresh(true);
	this.isFilter=false;
}

function Filter(WhereClause)
{
	this.WhereClause = WhereClause;
	//this.FromRecord=0;
	//this.ToRecord=0;
	this.PageNumber=1;
	this.isFilter=true;
	this.Refresh(true);
	this.isFilter=false;
	this.RaiseEvent('Filter');
}

function ApplyMultyFilters(FiltersIDs)
{
	killSearch();
	this.MultyFilters = FiltersIDs;
	//this.FromRecord=0;
	//this.ToRecord=0;
	this.PageNumber=1;
	this.isFilter=true;
	this.Refresh(true);
	//this.isFilter=false;
	this.RaiseEvent('Filter');
}

function MarkSelection(IDs)
{
	for (var iIndex = 0; iIndex < IDs.length ; iIndex++)
		document.getElementsByID('CHK_' + this.ID + '_' + IDs[iIndex])[0].status=true;
}

function MarkAll(isChecked)
{
    var CheckBoxs = window.document.getElementsByName('CHECK_BOX' + '_' + this.ID + '_' + this.PageNumber);
    	for (var i = 0; i < CheckBoxs.length; i++)
	{
	    CheckBoxs[i].checked = isChecked;
		this.handleSelectedRow(CheckBoxs[i]);			
	}
}

function ShowPage(PageNo)
{
	var oPages = document.getElementsByName('GRID_PAGE_' + this.ID);
	for (var iIndex=0; iIndex<oPages.length;iIndex++)
		if (oPages(iIndex).NAME == 'PAGE_' + this.ID + '_' + PageNo)
		{
			oPages(iIndex).className = 'Shown';
			return;
		}
	oPages=null;
}

function HidePages()
{
	var oPages;
	var iIndex;

	oPages = document.getElementsByName('GRID_PAGE_' + this.ID);
	for (iIndex=0;iIndex<oPages.length;iIndex++)
		oPages(iIndex).className="Hidden";
}

function doesPageExist(GridID, PageNo)
{
	var oPages = document.getElementsByName('GRID_PAGE_' + this.ID);
	for (var iIndex=0; iIndex<oPages.length;iIndex++)
		if (oPages(iIndex).NAME == 'PAGE_' + GridID + '_' + PageNo)
		{
			oPages = null;
			return true;
		}
	oPages=null;
	return false;
}


function ClearLastView()
{
    if (this.ShowView)
        this.ViewID = null;
    this.PageNumber = null;
    this.SearchString = null;
    this.SearchColumnID = null;
    this.SortOrder = null;
    this.ShowSearch = false;
    this.CancelSearch();
    this.Refresh();
}

function RefreshGrid(firstPage, KeepOnPage, forReal, IsFirstLoad)
{
	var sXML;
	var oBroker;
	var iIndex = 0;
	var Response;
	var bNavigate;
	var bRemoveChild=true;

	if (forReal == null) 
	    forReal = false;
	if (KeepOnPage == null)
	    KeepOnPage=true;		
	if (IsFirstLoad == null)
	    IsFirstLoad = false;

	if (firstPage == true)
	{
		bNavigate = false;
		this.PageNumber = 1;
		this.GridPages = new Array();
	}
	else
		bNavigate = true;

	// so caller does not wait for grid to refresh
	//if (!forReal) setTimeout('getGridByID('\' + this.ID + '\').Refresh(' + firstPage + ',' + KeepOnPage + ', true)', 0);
	if (!doesPageExist(this.ID, this.PageNumber) || bNavigate==false || KeepOnPage==true)
	{
		//construct the XML
		sXML = this.GetGridXML(null, IsFirstLoad);
		
		oBroker = getBroker();
		var oRequest = oBroker.createRequest(window);
		oRequest.setPage(parseFloat(m_PageID),
				 		 parseFloat(m_ObjectID),
						 parseFloat(m_ClassID),
						 parseFloat(m_ParentObjectID),
						 parseFloat(m_ParentClassID),
						 parseFloat(m_SubType),
						 parseFloat(m_TaskID),
						 parseFloat(m_VirtualParentObjectID),
						 parseFloat(m_VirtualParentClassID));

        oRequest.m_bRequiresTransaction = 0;
        
        this.tmp_bNavigate = bNavigate;
        this.tmp_KeepOnPage = KeepOnPage;
        this.tmp_firstPage = firstPage;
        
        if (this.AsyncRefresh && document.getElementById('GRID_INDICATOR_' + this.ID) != null)
            document.getElementById('GRID_INDICATOR_' + this.ID).style.display = 'inline';
        
		Response = oRequest.Execute('2000000', 'refresh', sXML, this.RefreshCallback, this, !this.AsyncRefresh);

        if (!this.AsyncRefresh)
            this.RefreshCallback(Response);
		
	}
	else
	{
		this.HidePages();
		this.ShowPage(this.PageNumber);
		//this.FromRecord = parseInt(this.PageSize)* (parseInt(this.PageNumber) -1);
		//this.ToRecord = parseInt(this.FromRecord) + parseInt(this.PageSize);
		oNavigator = null;
		var oNavigatorWindow = self;
		if (parent != self && parent.name == 'SPLIT')
				oNavigatorWindow = parent.parent;
		var oNavigator = oNavigatorWindow.document.getElementsByName('GridNavigator' + this.ID);

		if (oNavigator.length>0)
			oNavigator=oNavigator[this.PageNumber-1];

		if (oNavigator != null)
		{
			var sNavigatorHTML = '';
			if (this.GridPages[this.PageNumber-1].NavigatorHTML==null)
				sNavigatorHTML = this.GridPages[1].NavigatorHTML;
			else
				sNavigatorHTML = this.GridPages[this.PageNumber-1].NavigatorHTML;
			oNavigator.innerHTML = sNavigatorHTML;
		}
	}
	this.setGridHeight();
	this.RaiseEvent('Refresh');	

	getBroker().Clean();
	
	try {
	    top.resizeFrame();
	} catch(e) {}
	
	// matt h - 062907
	// for now introduce this functionality only on task bulk action pages - need more testing before rolling to other pages
	//if(m_PageID==704030500 || m_PageID==704030600 || m_PageID==704030700 || m_PageID==704030800 || m_PageID==755030100)
	//{
	    var CheckBoxs = window.document.getElementsByName('CHECK_BOX' + '_' + this.ID + '_' + this.PageNumber);
		
		if(CheckBoxs != null && CheckBoxs.length > 0 && getGridByID(this.ID).aManuallySelectedArray != null)
	        for(var iCheckboxCount = 0; iCheckboxCount < CheckBoxs.length; iCheckboxCount++)
		        for(var iSelectedCount = 0; iSelectedCount < getGridByID(this.ID).aManuallySelectedArray.length; iSelectedCount++)
		            if(CheckBoxs[iCheckboxCount].OBJECT_ID==getGridByID(this.ID).aManuallySelectedArray[iSelectedCount])
		            {
		                CheckBoxs[iCheckboxCount].checked=true;
		                this.handleSelectedRow(CheckBoxs[iCheckboxCount]);
		            }
	//}		
}

function RefreshGridCallback(Response)
{	    
    if ((null == Response) || ('undefined' == Response)) 
        return;
    
    var bNavigate = this.tmp_bNavigate;
    var KeepOnPage = this.tmp_KeepOnPage;
    var firstPage = this.tmp_firstPage;


	this.HTML = Response.substring(0, Response.length);
	//m_lPageWidth=0;


	//replace current grid
	if (this.HTML != '')
	{
		if (this.GridBody != null)
			if (!bNavigate || KeepOnPage || firstPage)
			{
				// remove all grids (new one coming)
				var oChild = null;
				iIndex = 0;
				var iLength = this.GridBody.childNodes.length;
				while  (iIndex < iLength)
				{
					oChild = this.GridBody.childNodes[iLength - iIndex -1];
					if (oChild != null)
						this.GridBody.removeChild(oChild);
					iIndex++;
				}
			}
		
		// insert new child
		var sHTML;
		sHTML = '<DIV NAME = "PAGE_' + this.ID + '_' + this.PageNumber + '" ID = "GRID_PAGE_' + this.ID + '">';
		
		this.SanitizeImagePaths();
        
		sHTML += unWellFormXML(this.HTML);
		sHTML += '</DIV>';
						
		this.GridBody.innerHTML = sHTML;
		HandleGridScript(sHTML);				

		this.SetNavigator();
		this.setTitles(this.ID, this.PageNumber);

		initLinks();

		this.HidePages();
		this.ShowPage(this.PageNumber);
		this.setGridViews();
		
		
		if (document.getElementById('GRID_INDICATOR_' + this.ID) != null)
            document.getElementById('GRID_INDICATOR_' + this.ID).style.display = 'none';
		
		
		if (this.AsyncRefresh && this.AsyncCallback != null)
            this.AsyncCallback(this);
	}
	else
		return;

}




function SanitizeImagePaths()
{    
    this.HTML = this.HTML.replace(/src='images\//ig, "src='skins/common/images/");
    this.HTML = this.HTML.replace(/src='images\\/ig, "src='skins/common/images/");
    
    this.HTML = this.HTML.replace(/src="images\//ig, 'src="skins/common/images/');
    this.HTML = this.HTML.replace(/src="images\\/ig, 'src="skins/common/images/');
 }


function HandleGridScript(HTML)
{         
    var iBegin =  HTML.lastIndexOf('<GRID_SCRIPT>')
    var iEnd =  HTML.lastIndexOf('</GRID_SCRIPT>')
    
    iBegin+=22; // for the script tag
    iEnd-=iBegin;
    iEnd-=10; // for the script tag
    
    var sScript = HTML.substr(iBegin, iEnd)
    
    if (sScript.length == 0)
	    return alert ('Internal error: script tag not found.');
    else
    {
	    try
	    {
		    eval(sScript);
	    }
	    catch (e)
	    {
		    alert ('Internal error: bad script tag.\n' + e);
		    //debugger;
		    return;			    
	    }
    }
}


function BuildGrid(PlaceHolderID)
{
	var sXML = "";
	var oBroker = null;
	var iIndex = 0;
	var Response = null;		

	//construct the XML
	sXML = this.GetGridXML(true, true);

	oBroker = getBroker();
	var oRequest = oBroker.createRequest(window);
	oRequest.setPage(parseFloat(m_PageID),
			 		 parseFloat(m_ObjectID),
					 parseFloat(m_ClassID),
					 parseFloat(m_ParentObjectID),
					 parseFloat(m_ParentClassID),
					 parseFloat(m_SubType),
					 parseFloat(m_TaskID),
					 parseFloat(m_VirtualParentObjectID),
					 parseFloat(m_VirtualParentClassID));

    this.tmp_PlaceHolderID = PlaceHolderID;
    
    
	Response = oRequest.Execute('2000000', 'build', sXML, this.BuildCallback, this, !this.AsyncRefresh);
	
	if (this.AsyncRefresh)
	    return;
	
	if ((null == Response) || ('undefined' == Response) || (Response.length == 0)) 
	    return;

    buildGridFromResponse(this.ID, PlaceHolderID, Response);
}

function BuildGridCallback(Response)
{
    if ((null == Response) || ('undefined' == Response) || (Response.length == 0)) 
	    return;
	
	buildGridFromResponse(this.ID, this.tmp_PlaceHolderID, Response);
    
    //alert('build ' + this.ID + '\n\n' + this.AsyncRefresh);
    var oGrid = getGridByID(this.ID);
    oGrid.AsyncRefresh = this.AsyncRefresh;
    oGrid.AsyncCallback = this.AsyncCallback;
    
    if (this.AsyncCallback != null)
        this.AsyncCallback(this);
}

function buildGridFromResponse(ID, PlaceHolderID, HTML)
{
	//replace current grid					
              
    HandleGridScript(HTML);
    
    var oGrid = getGridByID(ID);
    if (null == oGrid) return;
            
    try
    {
        // grid
        oGrid.HTML = HTML;
        oGrid.SanitizeImagePaths();
        
        // insert into place holder							
        var oPlaceholder = getDomElement(PlaceHolderID);
        oPlaceholder.insertAdjacentHTML('afterBegin', "<DIV>" + oGrid.HTML + "</DIV>");	
        oGrid.GridBody = getDomElement('GRID_PAGE_' + oGrid.ID).parentNode;							        
    }
    catch (e)
    {
        alert ('Internal error: buildGridFromResponse() error, ' + e.description);
        return;
    }


    initLinks();

    oGrid.HidePages();
    oGrid.ShowPage(oGrid.PageNumber);
    oGrid.setGridViews();
	
	oGrid.initGrid();
	
	oGrid.setGridHeight();
	
	getBroker().Clean();	
}

function GetGridXML(BuildGrid, IsFirstLoad)
{    
    BuildGrid = (BuildGrid == null ? false : BuildGrid);
    IsFirstLoad = (IsFirstLoad == null ? false : IsFirstLoad);
	
	var sXML = '<GUI ID="2000000">';
	sXML += '<PARAM NAME="ID" VALUE="' + this.ID + '"/>';
	if (this.ViewID != null) sXML += '<PARAM NAME="VIEW_ID" VALUE="' + this.ViewID + '"/>';
	if (this.ShowView != null) sXML += '<PARAM NAME="SHOW_VIEW" VALUE="' + this.ShowView + '"/>';
	if (this.NoScroll != null) sXML += '<PARAM NAME="NO_SCROLL" VALUE="' + this.NoScroll + '"/>';		
	if (this.PageSize != null) sXML += '<PARAM NAME="PAGE_SIZE" VALUE="' + this.PageSize + '"/>';
	if (this.PageNumber != null) sXML += '<PARAM NAME="PAGE_NUMBER" VALUE="' + this.PageNumber + '"/>';
	if (this.MaxRows != null) sXML += '<PARAM NAME="MAX_RECORDS" VALUE="' + this.MaxRows + '"/>';
	//if (this.NavigateToPage != null) sXML += '<PARAM NAME="NAVIGATE_TO_PAGE" VALUE="' + this.NavigateToPage + '"/>';
	//if (this.FromRecord != null) sXML += '<PARAM NAME="FROM_RECORD" VALUE="' + this.FromRecord + '"/>';
	//if (this.ToRecord != null) sXML += '<PARAM NAME="TO_RECORD" VALUE="' + this.ToRecord + '"/>';
	if (this.TopOffset != null) sXML += '<PARAM NAME="TOP_OFFSET" VALUE="' + this.TopOffset + '"/>';
	if (this.HasCheckBox != null) sXML += '<PARAM NAME="HAS_CHECKBOX" VALUE="' + this.HasCheckBox + '"/>';
	if (this.IsCaseSensitive != null) sXML += '<PARAM NAME="IS_CASE_SENSATIVE" VALUE="' + this.IsCaseSensitive + '"/>';
	if (this.IsMatchWhole != null) sXML += '<PARAM NAME="IS_MATCH_WHOLE" VALUE="' + this.IsMatchWhole + '"/>';
	if (this.HasSummaryPage != null) sXML += '<PARAM NAME="HAS_SUMMARY_PAGE" VALUE="' + this.HasSummaryPage + '"/>';
	if (this.SearchColumnID != null) sXML += '<PARAM NAME="SEARCH_COLUMN_ID" VALUE="' + this.SearchColumnID + '"/>';
	if (this.SearchString != null) sXML += '<PARAM NAME="SEARCH_STRING" VALUE="' + this.SearchString + '"/>';
	if (this.NoNavigate != null) sXML += '<PARAM NAME="NO_NAVIGATE" VALUE="' + this.NoNavigate + '"/>';
	if (this.NoSorting != null) sXML += '<PARAM NAME="NO_SORTING" VALUE="' + this.NoSorting + '"/>';
	if (this.NoSearching != null) sXML += '<PARAM NAME="NO_SERCHING" VALUE="' + this.NoSearching + '"/>';
	if (this.NoPaging != null) sXML += '<PARAM NAME="NO_PAGING" VALUE="' + this.NoPaging + '"/>';
	if (this.ForcingSortColumnID != null) sXML += '<PARAM NAME="FORCING_SORT_COLUMN_ID" VALUE="' + this.ForcingSortColumnID + '"/>';
	if (this.IgnoreView != null) sXML += '<PARAM NAME="IGNORE_VIEW" VALUE="' + this.IgnoreView + '"/>';
	if (this.HiddenColumns != null) sXML += '<PARAM NAME="HIDDEN_COLUMNS" VALUE="' + this.HiddenColumns + '"/>';
	if (this.OverideHeight != null) sXML += '<PARAM NAME="OVERIDE_HEIGHT" VALUE="' + this.OverideHeight + '"/>';
	if (this.MultyFilters != null) sXML += '<PARAM NAME="MULTY_FILTERS" VALUE="' + this.MultyFilters + '"/>';
	if (this.HasSelectColumn != null) sXML += '<PARAM NAME="HAS_SELECT_COLUMN" VALUE="' + this.HasSelectColumn + '"/>';
	if (this.HasMenuColumn != null) sXML += '<PARAM NAME="HAS_MENU" VALUE="' + this.HasMenuColumn + '"/>';
	if (this.RowClass != null) sXML += '<PARAM NAME="ROW_CLASS" VALUE="' + this.RowClass + '"/>';
	if (this.LinkClass != null) sXML += '<PARAM NAME="LINK_CLASS" VALUE="' + this.LinkClass + '"/>';
	if (this.CellClass != null) sXML += '<PARAM NAME="CELL_CLASS" VALUE="' + this.CellClass + '"/>';
	if (this.NoHeader != null) sXML += '<PARAM NAME="NO_HEADER" VALUE="' + this.NoHeader + '"/>';
	if (this.isFilter != null)  sXML += '<PARAM NAME="IS_FILTER" VALUE="' + (this.isFilter ? 1 : 0) + '"/>';
	if (this.MenuIconColumnName != null) sXML += '<PARAM NAME="MENU_ICON_COLUMN_NAME" VALUE="' + this.MenuIconColumnName + '"/>';
	if (this.MenuIcon != null) sXML += '<PARAM NAME="MENU_ICON" VALUE="' + this.MenuIcon + '"/>';
	sXML += '<PARAM NAME="EXEC_TYPE" VALUE="-1" />';
	sXML += '<PARAM NAME="IS_FIRST_LOAD" VALUE="' + (IsFirstLoad) + '" />';
	sXML += '<PARAM NAME="SAVE_STATE" VALUE="' + (this.SaveState) + '" />';
	
	
	if (this.SortOrder != null) 
	{
	    sXML += '<PARAM NAME="SORT">';
	    
	    var oSortOrder = '';
	    if (this.SortOrder)
		    oSortOrder =this.SortOrder;

	    for (iIndex = 0; iIndex<=oSortOrder.length - 1;iIndex++)
	    {
		    sXML += '<ARGUMENT COLUMN_ID = "' + this.SortOrder[iIndex].ColumnID + '"' ;
		    sXML += ' POSITION = "' + this.SortOrder[iIndex].Position + '"';
		    sXML += ' TYPE = "' + this.SortOrder[iIndex].Order + '"/>';
	    }
	    sXML += '</PARAM>';
    }


    if (this.WhereClause != null) 
    {
	    sXML += '<PARAM NAME="ADDITIONAL_WHERE" VALUE="' + this.WhereClause.ID + '">';
	    if (this.WhereClause.Arguments != null)
	    {
		    for (iIndex = 0; iIndex<=this.WhereClause.Arguments.length - 1;iIndex++)
		    {
			    sXML += '<ARGUMENT NAME = "' + this.WhereClause.Arguments[iIndex].Name + '"' ;
			    sXML += ' VALUE = "' + wellFormXML(this.WhereClause.Arguments[iIndex].Value) + '"/>';
		    }
	    }
	    sXML += '</PARAM>';
    }
	sXML += '</GUI>';

	return sXML;
}

function getExcelXML()
{
	sXML = '<GUI>';
	sXML += '<PARAM NAME="ID" VALUE="' + this.ID + '"/>';
	sXML += '<PARAM NAME="VIEW_ID" VALUE="' + this.ViewID + '"/>';		
	sXML += '<PARAM NAME="EXCEL_OBJECT_ID" VALUE="' + m_ObjectID + '"/>';
	sXML += '<PARAM NAME="EXCEL_CLASS_ID" VALUE="' + m_ClassID + '"/>';
	sXML += '<PARAM NAME="EXCEL_PARENT_OBJECT_ID" VALUE="' + m_ParentObjectID + '"/>';
    sXML += '<PARAM NAME="EXCEL_PARENT_CLASS_ID" VALUE="' + m_ParentClassID  + '"/>';
    //sXML += '<PARAM NAME="EXCEL_TASK_ID" VALUE="' + m_TaskID  + '"/>';
    //sXML += '<PARAM NAME="EXCEL_SUBTYPE_ID" VALUE="' + m_SubType + '"/>';	    
	sXML += '<PARAM NAME="SEARCH_COLUMN_ID" VALUE="' + this.SearchColumnID + '"/>';
	if (null != this.SearchString) 
	    sXML += '<PARAM NAME="SEARCH_STRING" VALUE="' + escape(this.SearchString) + '"/>';	
					 
	sXML += '<PARAM NAME="SORT">';
	
	var oSortOrder = '';
	if (this.SortOrder)
		oSortOrder = this.SortOrder;

	for (iIndex = 0; iIndex<=oSortOrder.length - 1;iIndex++)
	{
		sXML += '<ARGUMENT COLUMN_ID="' + this.SortOrder[iIndex].ColumnID + '"' ;
		sXML += ' POSITION="' + this.SortOrder[iIndex].Position + '"';
		sXML += ' TYPE="' + this.SortOrder[iIndex].Order + '"/>';
	}
	
	sXML += '</PARAM>';

	sXML += '<PARAM NAME="ADDITIONAL_WHERE" VALUE="' + this.WhereClause.ID + '">';

	if (this.WhereClause.Arguments != null)
		for (iIndex=0; iIndex<=this.WhereClause.Arguments.length-1; iIndex++)
		    if (this.WhereClause.Arguments[iIndex].Name != '')
		    {
			    sXML += '<ARGUMENT NAME="' + this.WhereClause.Arguments[iIndex].Name + '"' ;
			    sXML += ' VALUE="' + wellFormXML(this.WhereClause.Arguments[iIndex].Value) + '"/>';
			}
	sXML += '</PARAM>';
	sXML += '<PARAM NAME="MAX_RECORDS" VALUE="' + this.MaxRows + '"/>';
	
	sXML += '</GUI>';			
	
	return sXML;
}	

function GetSummaryPage(ObjectID, GridID)
{
	OpenSummaryPage(ObjectID, GridID, getGridByID(GridID).ViewID);
}

function Check(lDBId,lDBClass)
{
  this.ldbId=lDBId;
  this.ldbClass=lDBClass;
  this.ClassID = lDBClass;	  
  this.ClassInstance = lDBId;
}

function GetSelection()
{
	var CheckBoxs = document.getElementsByName('CHECK_BOX' + '_' + this.ID + '_' + this.PageNumber);
	var arTemp,iNextIndex=0,arInnerTemp;
	var i = 0
	var oGrid = null;

	arTemp=new Array();

	 while (i < CheckBoxs.length)
	 {
		var CheckBox = CheckBoxs[i];
		if (CheckBox.checked)
		{
		    iNextIndex=arTemp.length;
		    oCheck=new Check(CheckBox.getAttribute('OBJECT_ID'),CheckBox.getAttribute('CLASS_ID'));
		    arTemp[iNextIndex]=oCheck;
		    iNextIndex++;
		    oCheck=null;
		}
		i++;
	 }

	 oGrid = this;

	 if ((oGrid != null) && (!oGrid.HasCheckBox) && (oGrid.HasSelectColumn))
		if(oGrid.LastSelectedID != -1)
		{
			var oLabel = getDomElement('CHK_' + this.ID + '_'+ oGrid.LastSelectedID);
			if(oLabel != null)
				arTemp[0]= new Check(oGrid.LastSelectedID, oLabel.CLASS_ID);
		}

	 return(arTemp);
}

function getGridCollection(Columns, Selection)
{
// selection can get: All, SELECTED, UNSELECTED //
	var oCollection = new Collection();
	var oRows;
	var oCells;
	var oGrid;
	var iRowIndex;
	var iColumnIndex;
	var sEvaluate;
	var bAccept;
	var sElementName;
	var oCheckBox;
	
	oRows = document.getElementsByName('GRID_ROW');

	if (oRows.length<=1)
	{
		var oRow = getDomElement('NO_RECORDS');
		if (oRow!=null) 
		    return oCollection;
	}

	for (iRowIndex=0;iRowIndex<oRows.length;iRowIndex++)
	{
		//oCells = oRows[iRowIndex].children[0];
		switch  (Selection)
		{
			case 'SELECTED':
				oCells = oRows[iRowIndex].children[0];
				//alert(getGridByID().PageNumber);

				oCheckBox = oCells.children('CHECK_BOX' + '_' + this.ID + '_' + this.PageNumber);

				if(oCheckBox == null)
				{
					try
					{
						oCheckBox = oCells.children[0];
					}
					catch(e) {}
				}

				if (oCheckBox != null)
				{
					if ((!this.HasCheckBox) && (this.HasSelectColumn) && (this.LastSelectedID != -1))
						bAccept = (oCheckBox.OBJECT_ID == this.LastSelectedID);
					else
						bAccept = (oCheckBox.status);
				}
				else
					bAccept=false;

				break;
			case 'UNSELECTED':
				oCells = oRows[iRowIndex].children[0];
				oCheckBox = oCells.children('CHECK_BOX' + '_' + this.ID + '_' + this.PageNumber);
				if (oCheckBox != null)
					bAccept = (!oCheckBox.status);
				else
					bAccept=false;
				break;
			default:
				bAccept=true;
				break;
		}
		if (bAccept) //check For Selection
		{
			var oItem = new Object();
			for (iColumnIndex=0;iColumnIndex<Columns.length;iColumnIndex++)
			{
				sElementName = this.ID + '_' + oRows[iRowIndex].getAttribute('OBJ_ID') + '_' + Columns[iColumnIndex];

				var sElementValue = getRowItem(oRows[iRowIndex],sElementName);
				sElementValue = unWellFormXML(sElementValue + '');
				if (m_bIsFirefox)
				    sElementValue = sElementValue.substring(sElementValue.indexOf('<g_value>')+9,sElementValue.indexOf('</g_value>'));
				else
				    sElementValue = sElementValue.substring(sElementValue.indexOf('<G_VALUE>')+9,sElementValue.indexOf('</G_VALUE>'));
				sElementValue=sElementValue.replace('&nbsp;','');

                
				sEvaluate = "oItem." + Columns[iColumnIndex] + "='" + escape(sElementValue) + "';";
				eval(sEvaluate);
				sEvaluate = "oItem." + Columns[iColumnIndex] + " = unescape(oItem." + Columns[iColumnIndex] + ");";
				eval(sEvaluate);
			}
			oCollection.Add(oItem);
		}
	}
	return oCollection;
}

function getRowItem(Row,Column)
{
	var index;
	var cellIndex;
	var oCells;
	
	for (var c = 0; c < Row.cells.length; c++)
	    if (Row.cells[c].id == Column)
	        return Row.cells[c].innerHTML;
	
	for(index=1;index<Row.children.length;index++)
	{
		oCells = Row.children[index];
		for(cellIndex=0;cellIndex<oCells.children.length;cellIndex++)
			if (oCells.children[cellIndex].id==Column)
				return oCells.children[cellIndex].innerHTML;
	}
	return null;
}



//////////////////////////////////////////// views function ////////////////////////////////////
function viewProc(functionBody)
{
	eval (functionBody);
}

function setGridViews()
{	    
	if (document.getElementsByName('ViewsCombo' + this.ID).length == 0)
		return showViewInMainScreen('');
	
	var oViewsCombo = document.getElementsByName('ViewsCombo' + this.ID)[document.getElementsByName('ViewsCombo' + this.ID).length-1]
	var oViewsList = null;

	if ((oViewsCombo == null) || (oViewsCombo.parentNode == null))
		return showViewInMainScreen('');
        
	var oPlaceHolder = getDomElement('GridBarViewPlaceHolder' + this.ID);
	var oGridPage = getDomElement('GRID_PAGE_' + this.ID).parentNode;	//
	var oGridViews = getDomElement ('GridViews' + this.ID);

	if ((oGridViews != null) && (oGridPage != null))
	{		    
		var oNode = getDomElement('GRID_VIEW_TABLE_' + this.ID)
		if (oNode!=null)
		{
			var oParent = oNode.parentNode;
			oParent.removeChild(oNode);
			oNode=null;
			oParent=null;
		}
		
		var imgUrl = 'gb_customize.gif';
		
		var sHTML = '<TABLE BORDER="0" Cellpadding="0" Cellspacing="0" class="GridNavigator" ID = "GRID_VIEW_TABLE_' + this.ID + '">';
		sHTML +=        '<TR>';
		sHTML +=            '<TD nowrap="true"><LABEL Class="NewHeader" >&nbsp;View&nbsp;</LABEL>' + unWellFormXML(oViewsCombo.innerHTML) + '&nbsp;</TD>';
		sHTML +=            '<TD>';
		sHTML +=                '<img ' + btnHoverHandlerJS + ' id="customizeView' + this.ID + '" Class="GridBarButton16" src="skins/common/images/' + imgUrl + '" alt="Customize View" onclick="editView(null, null,\'' + this.ID + '\');" />';
		sHTML +=            '</TD>';
		sHTML +=            '<TD><span class="GridBarDivider"/></TD>';			
		sHTML +=        '</TR>';
		sHTML +=    '</TABLE>';
		if (oPlaceHolder)
			oPlaceHolder.innerHTML=sHTML;
		else
			oGridPage.insertAdjacentHTML('afterBegin', sHTML);
		
		oViewsList = getDomElement("GridViewsCombo" + this.ID);
		if(oViewsList != null && this.ViewID!=null && this.ViewID > 0)
		    for(iIndex = 0 ; iIndex < oViewsList.options.length ; iIndex++)
		        if(oViewsList.options[iIndex].getAttribute('ViewID') == this.ViewID)
		        {
		            oViewsList.options.selectedIndex = iIndex;			            
		            break;
		        }
		setCustomizeViewState(this.ID);			
	}
}

function setCustomizeViewState(GridID)
{
    var oViewsList = getDomElement("GridViewsCombo" + GridID);
    var btnCust = document.getElementById('customizeView' + GridID);
    if (oViewsList == null || btnCust == null)
        return;
    var i = oViewsList.selectedIndex;

    var imgUrl = 'gb_customize.gif';
    if (oViewsList.options[i].getAttribute('ReadOnly') ==0 && oViewsList.options[i].getAttribute('ViewID') != -1)
        imgUrl = 'gb_customize_disabled.gif';
    btnCust.src = 'skins/common/images/' + imgUrl;
    
}

function showViewInMainScreen(HTML)
{
	if (top != self)
		if (typeof(top.getApplicationsManager) == "function")
		{
			var oApplicationsManager = top.getApplicationsManager();
			if (oApplicationsManager != null)
				oApplicationsManager.SetView(oApplicationsManager.ActiveApplication, HTML, self);
		}
		
}

function viewProc(functionBody)
{
	eval (functionBody);
}


function openViewMenu(screenX, screenY)
{
	oMenu5110100.openMenu(0, screenX, screenY);
}

function viewChanged(ViewsCombo, GridID)
{
	//m_oViewsCombo=ViewsCombo;
	if (ViewsCombo)
		applyView(ViewsCombo.options[ViewsCombo.selectedIndex].getAttribute('ViewID'), GridID);
	else
		applyView(null, this.ID);
}

function removeView(ViewID, GridID)
{
    applyView(0, GridID);
    
    var ViewsCombo = getViewsCombo(GridID);
    if (ViewsCombo == null)
        return;
        
    for (var i = 0; i < ViewsCombo.length; i++)
        if (ViewsCombo[i].ViewID == ViewID)
            break;
    if (i < ViewsCombo.length)
        ViewsCombo.options[i].removeNode(true);
    
}

function applyView(ViewID, GridID)
{
	var bActiveSearchValid = false;

    setCustomizeViewState(GridID);

	if (ViewID == null)
	{
		var ViewsCombo = getViewsCombo(GridID);
		ViewID = ViewsCombo.options[ViewsCombo.selectedIndex].getAttribute('ViewID');
	}

	if (ViewID < 0)
	    editView(null, null, GridID);
	else
	{
		//m_oViewsCombo=null;
		var oGrid = getGridByID(GridID);
		if (null == oGrid) return;

		oGrid.ViewID = ViewID;
		oGrid.SortColumn = 0;
		oGrid.SortOrder = 0;
		oGrid.SortOrder=null;
		oGrid.isFilter=true;

		oGrid.Refresh();

		if (oGrid.SearchIsActive)
		{
			var oColumnsCombo = oGrid.ColumnsCombo;
			for (var i =0; i < oColumnsCombo.length;i++)
				if (oColumnsCombo[i].ColumnID == oGrid.SearchColumnID)
				{
					bActiveSearchValid=true;
					break;
				}
		}
		if (!bActiveSearchValid)
		{
			oGrid.SearchIsActive=false;
			//need to  Search Combo
			//getGridByID().CancelSearch(true);
		}
		oGrid.ReloadSearchCombo();
		//this.setGridHeight();
	}

}

function ReloadSearchCombo()
{
    var oGrid =  this;
    var aValues = oGrid.ColumnsCombo;
    var iIndex=0;
    var oCombo = getDomElement('CBO_SEARCH_' + this.ID);
    var bFound=false;

    // clean the Combo
    oCombo.options.length = 0;

    //Reload The Combo
    var listOptions=oCombo.options;
    var aValues = oGrid.ColumnsCombo;

    var sAllOption = '';

    for (iIndex=0;iIndex<aValues.length;iIndex++)
    {
	    sAllOption+=aValues[iIndex].ColumnID + ';'
	    var oOption = document.createElement("OPTION");
	    listOptions.options.add(oOption,iIndex+1);
	    oOption.innerHTML = unWellFormXML(aValues[iIndex].ColumnName);
	    oOption.value = aValues[iIndex].ColumnID;
	    // must have this becuase same columns can have special search by diffrent column
	    if (parseInt('0' + oGrid.SearchColumnID) > 0)
	    {
		    if (aValues[iIndex].ColumnID == oGrid.SearchColumnID)
		    {
			    oCombo.selectedIndex = iIndex;
			    bFound=true;
		    }
	    }
	    else
		    if (aValues[iIndex].ColumnName.toLowerCase().indexOf('name')>-1)
			    oCombo.selectedIndex = iIndex;
    }
    var oOption = document.createElement("OPTION");
    listOptions.options.add(oOption,iIndex+1);
    oOption.innerHTML = '- All -';
    oOption.value = sAllOption;

    if (!bFound)
    {
	    getDomElement('TXT_SEARCH_FOR_' + this.ID).value='';
	    oGrid.SearchString = null;
    }
}

function editView(ViewID, Enabled, GridID)
{
	var bEnabled;
	if (GridID==null)
	{
		alert ('Internal error: editView, Unknown grid.')
		return;
	}

	if (Enabled != null)
		bEnabled = Enabled;
	
	if (ViewID == null)
	{
		var ViewsCombo = getViewsCombo(GridID);
		ViewID = ViewsCombo.options[ViewsCombo.selectedIndex].ViewID;
		bEnabled =  (ViewsCombo.options[ViewsCombo.selectedIndex].ReadOnly != 0);
	}
	
	if ((bEnabled) || (ViewID==-1))
	{
		openSMSPopup(5030600,
					  ViewID,
					  5000000,
					  GridID,
					  m_ClassID);
	}
}

function getViewsCombo(GridID)
{
	var arGridViewsCombo = document.getElementsByName('GridViewsCombo' + GridID);
	//return(arGridViewsCombo[arGridViewsCombo.length-1]);
	return(arGridViewsCombo[0]);
}

function nameExists(viewName, GridID)
{
	var oViewsCombo = getViewsCombo(GridID);
	var oOption;
	var iIndex = 0;
	if (oViewsCombo == null)
		return(false);
	while (iIndex < oViewsCombo.options.length)
	{
		oOption = oViewsCombo.options[iIndex];
		if (oOption.text == viewName)
			return(true);
		iIndex++;
	}
	return(false);
}

function GridListener(CallBack,Event) // the listener object
{
	this.CallBack = CallBack;
	this.Event = Event;
	this.Equal = ListenerEqual;
}

function GridAttachEvent(CallBack,Event) // add listener object
{
	var Listener = new GridListener(CallBack,Event);
	this.Listeners[this.Listeners.length]=Listener;
	if (Event=='Refresh')
		this.RaiseEvent('Refresh');
}

function dettachEvent(CallBack,Event)
{
	var iIndex;
	var oItem;
	var Listener = new GridListener(CallBack,Event);
	for (iIndex=0;iIndex<	this.Listeners.length;iIIndex++)
	{
		oItem = Listeners[iIndex];
		if (oItem.Equals(Listener))
			RemoveItem(iIndex);
	}
	Listener = null;
}

function RemoveItem(index)
{
	// This function recreates the array excluding the undesired element
	var arTemp,iTempIndex=0;

	arTemp=new Array();
	for (var i=0; i < this.Listeners.length; i++)
	  if (i!=index)
	  {
	    arTemp[iTempIndex]=this.Listeners[i];
	    iTempIndex++;
	  }
	this.Listeners=arTemp;
	arTemp=null;
}

function ListenerEqual(Listener)
{
	if (this.CallBack == Listener.CallBack && this.Event == Listener.Event)
		return true;
	return false;
}


function RaiseEvent(EventName, Param)
{
	var iIndex;

	if(this.Listeners==null) return;

	for(iIndex=0;iIndex<this.Listeners.length;iIndex++)
		if (this.Listeners[iIndex].Event == EventName)
			if(eval("typeof(" + this.Listeners[iIndex].CallBack + ")" ) == "function")
				eval(this.Listeners[iIndex].CallBack + '("' +  this.ID + '");');
}


function getViewSource()
{
	return getTitle();
}


///////////////////////////////////////////////////////////////////////////////////////////

function startDrag()
{
    var oDiv = getDomElement('SUMMARY_DIV');
    m_SummaryWidth = oDiv.offsetWidth;
    oDiv._dx = window.event.screenX - oDiv.offsetLeft;
    oDiv._dy = window.event.screenY - oDiv.offsetTop;
    oDiv.attachEvent("onmousemove", doDrag);
    oDiv.attachEvent("onmouseup", stopDrag);
    oDiv.attachEvent("onlosecapture", stopDrag);
    oDiv.setCapture();

}// end function startDrag


function doDrag()
{
    var oDiv = getDomElement('SUMMARY_DIV');
    oDiv.style.left = window.event.screenX - oDiv._dx;
    oDiv.style.top = window.event.screenY -  oDiv._dy;
    oDiv.style.width= m_SummaryWidth;

}// end function doDrag


function stopDrag()
{
	var oDiv = getDomElement('SUMMARY_DIV');
	oDiv.releaseCapture();
	oDiv.detachEvent("onmousemove", doDrag);
	oDiv.detachEvent("onmouseup", stopDrag);
	oDiv.detachEvent("onlosecapture", stopDrag);

}// end function stopDrag

function getVersion()
{
		var sAppVersion = navigator.appVersion;
		var sIEVersion;
		var myArray = sAppVersion.split(";");

		for(i=0;i<myArray.length;i++)
			if(myArray[i].indexOf("MSIE")!=-1)
			{
				sIEVersion = myArray[i].split("MSIE");
				return parseFloat(sIEVersion[1]);
			}
}


function throwGridRow(ID)
{
	this.LastSelectedID = ID;
	this.RaiseEvent('SelectRow');
}

function setFormHTMLtoRow(ObjectID,HTML)
{
    if (this.LastID!=0)
        this.cleanFormHTMLtoRow(this.LastID);
     

    var sTD = 'PLACEHOLDER_' + this.ID;
    if (ObjectID > 0)
        sTD += '_' + ObjectID;
    
    var oTD = getDomElement(sTD);
    if (oTD == null)
    {
        this.GridBody.innerHTML = '<div id="' + sTD + '"/>';
        oTD = getDomElement(sTD);
    }
    oTD.innerHTML = HTML;
	oTD.className = 'Placeholder';
	this.LastID = ObjectID;
	
	try
	{
	    top.resizeFrame();
	}
	catch (e) {}
}

function cleanFormHTMLtoRow(ObjectID)
{
    var sTD;
    if (ObjectID>0)
        sTD = 'PLACEHOLDER_' + this.ID + '_' + ObjectID;
    else
        sTD = 'PLACEHOLDER_' + this.ID;
	
	
	var oTD = getDomElement(sTD);
	if (oTD!=null)
	{
	    oTD.innerHTML = '';
	    oTD.className = 'Hidden';
	    this.LastID = 0;
    }
    
    try
	{
	    top.resizeFrame();
	}
	catch (e) {}
}

function gridPlaceHolderResize()
{
	if ((null != top.resizeFrame) && ('undefined' != top.resizeFrame)) top.resizeFrame();
}



function initGridProperties(ID)
{    	
    var oGrid = new Grid();
    oGrid.ID = ID;
    return(oGrid);
}


function loadGrid(containerId,gridId,whereClause,showView,viewId,noScroll,showMenu)
{      
   	var oGrid = null;
   	var oArguments = new Array();
   	
   	//clear contents of the container
   	getDomElement(containerId).innerHTML = '';
   	        						
    // init the essential parameters in the grid		
    oGrid = initGridProperties(gridId);		
    
    oGrid.ShowView = showView;
    oGrid.ViewID = viewId;	    
    oGrid.NoScroll = noScroll;		
    oGrid.HasMenuColumn = showMenu;
    
    oGrid.WhereClause = whereClause;
    oGrid.Build(containerId);
}


function toggleDebugSql(ID)
{
    var obj = document.getElementById('GridDebugSql' + ID);
    if (obj == null)
        return;
    
    obj.style.display = (obj.style.display == 'block') ? 'none' : 'block';
    
    if (top.resizeFrame != null)
        top.resizeFrame();
}

function toggleDebugSqlParams(ID)
{
    var obj = document.getElementById('GridDebugParamSql' + ID);
    if (obj == null)
        return;
    
    document.getElementById('GridDebugPlainSql' + ID).style.display = (obj.style.display == 'none') ? 'none' : '';
    obj.style.display = (obj.style.display == 'none') ? '' : 'none';
        
    if (top.resizeFrame != null)
        top.resizeFrame();
    return false;
}