// MultilogicGrid Client Script Library
// Alfa-XP, Michael Isipciuc, 2006-2007.
//
Type.registerNamespace("FM");
Type.registerNamespace("FM.UI");

FM.DataGridCollection= function() {
	this._grids= [];
	this.Register= function(dg) { this._grids[dg.id]= dg;	this._sid= dg.id; }
	this.Unregister= function(dg) { this._grids[dg.id]= null;	this._sid= null; }
	this.Find= function(id) { return (id) ? this._grids[id] : this._grids[this._sid]; }
}
var RESULT_CANCEL= -1;
var RESULT_CURRENTPAGE= 0;
var RESULT_ALLPAGES= 1;
window.fmGrids= new FM.DataGridCollection();

//trace= function(s, end) { var dt2= new Date(); var i= dt2 - dt; this.dt= dt2;	window.status+= s + ":" + i + ","; if (end) window.status+= " Total:" + (dt2 - window.Start); }

FM.DataGrid= function(element) {
		FM.DataGrid.initializeBase(this, [element]);
		// Properties
		this.id= element.getAttribute('id');
		this.tableName= "";
		this.viewName= "";
		this.selectOnStart= (element.getAttribute('selectOnStart') == '1');
		this.allowSelect= (element.getAttribute('allowselect') == '1');
		this.autoRefreshTime= element.getAttribute('autoRefreshTime');
		this.regScripts= element.getAttribute('regScripts')
		this.allowGrouping= false;
		this.InputParameters= "";

		this.onrecordhandle= null;

		this.selectedID= null;
		this.selectedIndex= 0;
		this.selectedIndexes= [];

    // Variables

		this._selectedIDs= null;
    this._lastRow= null;
    this._iTotalOnPage= 0;
    this._iShiftClickedIndex= -1;
    this._iLastPickedIndex= -1;
    this._iTotalSelected= 0;
    this._aSelectedRows= [];
    this._oLastOver= null;
    this._service= null;
    this._oSortColumns= null;

    // Events
    this.OnDoubleClick= null;
    // Dlgs
    this._scrollBodyDlg= null;

    // paging
    this._nextPageImg= null;this._prevPageImg= null;this._fastRewindImg= null;this._oItemsTotal= null;this._oPageNumLabel= null;
    //
		this.divGridProps= null;this.divGridParams= null;this.divPageNum= null;

		this._gridFooter= null;this._gridBody= null;
		this._pmenu= null;
		this._bPagingEnabled= false;
		this._loadingLabel= null;
		this._expandedRow= null;
		this._groupingZone= null;
		this._recordExpandMode= 2; // { 0:off, 1: info}

		//
		this._bRefreshing= false;
		this._preventRE= false;
		this.OnRefresh= null;
		this.divHeader= null;
		this.panelsHeight= 0;

		this._timerID= null;
}

FM.DataGrid.prototype= {

  initialize : function() {
		FM.DataGrid.callBaseMethod(this, 'initialize');
		this.initializeBody();

		window.fmGrids.Register(this);
		if (this.autoRefreshTime != null && this.autoRefreshTime != "0") {
			var refreshCallback= Function.createDelegate(this, this.AutoRefresh);
			this._timerID= window.setInterval(refreshCallback, parseInt(this.autoRefreshTime));
		}
  },

  initializeBody : function() {
		this.initContainer();
		this.initScrollTable();

		this.initInnerGrid();
		this.load();
  },

  disposeBody : function() {
			if (this._gridBar) { $clearHandlers(this._gridBar); this._gridBar= null; }
			if (this._gridBody) { $clearHandlers(this._gridBody); this._gridBody= null; }
			if (this._groupingZone) { this._groupingZone.dispose(); this._groupingZone= null; }

			if (this._bPagingEnabled) {
				$clearHandlers(this._nextPageImg);
				$clearHandlers(this._prevPageImg);
				$clearHandlers(this._fastRewindImg);
				this._bPagingEnabled= false;
			}

			if (this._scrollBodyDlg && this._gridBodyContainer) {
				$removeHandler(this._gridBodyContainer, 'scroll', this._scrollBodyDlg);
				this._scrollBodyDlg= null;
			}
			this._oGridStatusBar= this._itemsSelected= this._itemsOnPage= null;
  },

  dispose : function() {
			if (this.get_element() == null) return;

			this.disposeBody();

			window.fmGrids.Unregister(this);
			if (this._timerID != null) window.clearInterval(this._timerID);

      FM.DataGrid.callBaseMethod(this, 'dispose');
  },

  initContainer : function() {
		//trace('a');
		var o= this.get_element();
		this._gridBar= $get('gridBar', o);
		this._gridBodyContainer= $get('_gridBodyContainer', o);
		if (!this._gridBodyContainer) return;
		$addHandlers(this._gridBar, {
			'click': this._onColumnClick,
			'dblclick': this._onColumnDblClick,
			'mouseover': this._onColumnOver,
			'mouseout': this._onColumnOut,
			'contextmenu': this._onselectstart
		}, this);
		this._gridFooter= this._gridBodyContainer.nextSibling;

 		this.divGridProps= $get('divGridProps', this._gridFooter);
		this.divGridParams= $get('divGridParams', this._gridFooter);
		this.tableName= this.GetProperty("tableName");
		this.viewName= this.GetProperty("viewName");

		this.allowGrouping= (this.GetProperty("grouping") == "true");
		if (this.allowGrouping) {
			var gcontainer= o.firstChild;
			if (gcontainer != null) {
				this._groupingZone= $create(FM.UI.GroupingZone, {}, null, null, gcontainer);
				this._groupingZone.setupGridBar(this._gridBar, Function.createDelegate(this, this.addGroupingColumnBefore), Function.createDelegate(this, this.removeGroupingColumn));
			}
			this.groupColumns= this.GetProperty("groupColumns");
			if (this.groupColumns != "") this._gridBodyContainer.GridInstance= this;				
		}
		this.divPageNum= $get("pageNum", this.divGridProps);
		this._oGridStatusBar= $get("gridStatusBar", this._gridFooter);
		if (this._oGridStatusBar) {
			this._oItemsTotal= $get("_ItemsTotal", this._oGridStatusBar);
			this._nextPageImg= $get("_nextPageImg", this._oGridStatusBar);
			this._bPagingEnabled= (this._nextPageImg != null);
			this._bSelectionEnabled= this._oGridStatusBar.rows[0].cells[0].innerHTML != "";
			if (this._bPagingEnabled) {
				this._prevPageImg= $get("_prevPageImg", this._oGridStatusBar);
				this._fastRewindImg= $get("_fastRewindImg", this._oGridStatusBar);
				this._oPageNumLabel= $get("_PageNum", this._oGridStatusBar);
				$addHandlers(this._nextPageImg, { 'click' : this.nextPage }, this);
				$addHandlers(this._prevPageImg, { 'click' : this.prevPage }, this);
				$addHandlers(this._fastRewindImg, { 'click' : this.firstPage }, this);
			}
		}
  },


  initInnerGrid : function() {
		if (this._gridBodyContainer == null) return;
		this._gridBody= this._gridBodyContainer.firstChild;
		if (this._gridBody.tagName == 'TABLE') {
			$addHandlers(this._gridBody, {
				'click': this._onclick,
				'dblclick' : this._onDblClick,
				'keydown': this._onKeyDown,
				'mouseover': this._onGridOver,
				'contextmenu': this._onContextMenu,
				'selectstart' : this._onselectstart
			}, this);

			if (this.GetProperty("allowover") == "true") {
				$addHandlers(this._gridBody, {
					'mouseover': this._onmouseover,
					'mouseout': this._onmouseout
				}, this);
			}
		} else {
			this._gridBody= null;// message DIV element
		}
		this._aSelectedRows= [];
		this._iTotalSelected= 0;
		this.updatePagingUI();
	},

  load : function() {
		if (!this._gridBody) { this.updateSelectedItemsUI(0, 0); return; }
		var count= 0;
		var rows= this._gridBody.rows;
		var oid;
		var selByID= (this._selectedIDs != null && this._selectedIDs.length > 0);
		var selected= false;
		for (var i= 0; i < rows.length; i++) {
			oid= rows[i].getAttribute('oid');
			if (oid) {
				count++;
				if (selByID && this.is_in_array(oid, this._selectedIDs)) { this.SelectRecords(i, i); selected= true; }
			}
		}
		this._iTotalOnPage= count;
		if (this.selectOnStart && this.allowSelect && !selected) {
			if (count > 0) {
				var p= this.selectedIndex;
				if (p < 0 || p >= count) p= 0;
				this.SelectRecords(p, p);
			} else {
				this.updateSelectedItemsUI(0, this._iTotalOnPage);
			}
		}
  },

  _onColumnClick : function(e) {
		var o= e.target;
		switch (o.tagName) {
			case "INPUT":
				o.checked ? this.SelectRecords() : this.UnselectRecords(this._gridBody.rows[0]);
				return;
			case "IMG":
				if (o.className == "Refresh") { this.Refresh(true); return; }
				o= o.parentNode;
			case "NOBR":
				o= o.parentNode;
			case "TD":
				break;
		}
		var fname= o.getAttribute("field");
		var sort= o.getAttribute("sort");
		if (IsNull(fname) || IsNull(sort)) return;

		if (o.runtimeStyle) o.runtimeStyle.backgroundImage= "";
		if (this._oSortColumns == null) {
			this._oSortColumns= new FM.SortColumnCollection();
			this._oSortColumns.Deserialize(this.GetProperty('sortColumns'));
		}

		var nLength= this._oSortColumns.aSortColumns.length;
		var oi;
		for (var i= 0; i < nLength; i++) {
			var oColumn= this.findColumn(this._oSortColumns.aSortColumns[i].sName);
			if (oColumn != null) {
				var oi= window.getFirstElement(oColumn.firstChild);
				if (oi) oi.style.visibility= "hidden";
			}
		}

		var fMultiSort= this.GetProperty('enableMultiSort') == "true";
		this._oSortColumns.Toggle(fname, fMultiSort && e.shiftKey);

		nLength= this._oSortColumns.aSortColumns.length;
		for (var i= 0; i < nLength; i++) {
			var oColumn= this.findColumn(this._oSortColumns.aSortColumns[i].sName);
			var oImg= getFirstElement(oColumn.firstChild);
			if (!oImg) break;
			oImg.style.visibility= "visible";
			oImg.src= window.fmCommonPath + ((this._oSortColumns.aSortColumns[i].fAscend) ? "Images/Grid2/bar_up.gif" : "Images/Grid2/bar_dn.gif");
		}

		this.SetProperty('sortColumns', this._oSortColumns.Serialize());
		this.divPageNum.setAttribute('value', 1);
		this.clearPagingCookie();
		this.Refresh(false, true);
	},

	_onColumnOver : function(e) {
		var o= this.GetParentCell(e.target);
		if (!o) return;
		if (o.getAttribute('sort') == '1' && o.style.backgroundImage != sortOverImage) o.style.backgroundImage= window.sortOverImage;
	},
	_onColumnOut : function(e) {
		var o= this.GetParentCell(e.target);
		if (o && o.getAttribute('sort') == '1') o.style.backgroundImage= "";
	},

	_onColumnDblClick : function(e) {
		e.stopPropagation();
	},

	_onDblClick : function(e) {
		e.stopPropagation();
		//if (this._iTotalRecords == 0) return;

		if(!IsNull(e.target.isLink) && e.target.isLink == 1) {
			//this.handleClick(e);
		}
		var oRow= this.GetParentRow(e.target);
		if (!oRow || oRow.getAttribute("oid") == null) return;

		if (this.OnDoubleClick) {
			var mas= new Array(); mas[0]= oRow;
			this.OnDoubleClick(mas);
		}
		//var oEvent= raiseOnBeforeFormLoadEvent(oTr, iOTC, oTr.oid);
		//if (oEvent.returnValue == true) {
			try {
				var recordID= oRow.getAttribute('oid');
				if (this.dblclickHandler == null) {
					this.dblclickHandler= this.GetParameter('dblclickHandler');
					if (!this.dblclickHandler) return;
				}
				eval(this.dblclickHandler);
			} catch (e) {
				alert(e.description);
			}
		//}

	},

	_onContextMenu	: function(e) {
		e.stopPropagation();
		e.preventDefault();

		if (this._iTotalRecords == 0) return;
		if (!this._pmenu) {
			var pm= $get('_PopupMenu', this._gridFooter);
			//var pm= this._gridFooter.nextSibling;
			if (!pm) return;
			this._pmenu= new FM.PopupMenu(pm, this);
		}
		this._pmenu.Show(e, this.GetParentRow(e.target));
	},

  _onclick : function(e) { this.handleClick(e); },

  _onKeyDown : function(e) {
		//
  },
  _onselectstart : function(e) { e.preventDefault(); return false; },

	handleClick : function(e) {
		e.stopPropagation();
		var o= e.target;
		switch (o.tagName) {
			case "IMG":
				if (o.className == "g_label") this.ToggleGroup(o);
				else if (o.className == "masterdetail") this.MasterDetail(o);
				else if (o.className == "preview") this.Preview(o);
				else if (o.className == "hierarchy") this.ToggleHierarchy(o);
				break;
			case "A":
				if (o.className == "g_label") this.ToggleGroup(o);
				break;
			case "NOBR": case "SPAN": o= o.parentNode;
			case "TD": o= o.parentNode;
			case "TR":
				if (this.allowSelect && (o.className == "grid" || o.className == "gridSelectOn")) {
					if (e.ctrlKey && o.selected) {
						this.unselectRow(o, true, true);
					} else {
						this.handleSelectRow(e, o);
					}
				}
			break;
		}
	},

  ToggleGroup : function(o) {
		var tbody= this.GetParentTBody(o);
		var isClosed= tbody.getAttribute('expanded') != '1';
		if (isClosed) {
			if (tbody.getAttribute('loaded') == "1") {
				this.toggleRow(tbody, true);
			} else {
				this.LoadSubGroups(tbody);
			}
		} else {
			this.toggleRow(tbody, false);
		}
  },

  toggleRow : function(tbody, open, loaded) {
		var groupIndex= parseInt(tbody.getAttribute("groupIndex"));
		if (open != null) {
			var subtbody= tbody.nextSibling;
			var gi;
			while (subtbody != null && subtbody.tagName == "TBODY" && parseInt(subtbody.getAttribute("pi")) >= groupIndex) {
				subtbody.style.display= open ? "" : "none";
				subtbody= subtbody.nextSibling;
			}
		}
		if (open != null) {
			tbody.setAttribute('expanded', (open) ? '1' : '0');
			var img= tbody.rows[0].cells[groupIndex].firstChild;
			if (open) img.src= img.src.replace("plus.gif", "minus.gif");
			else img.src= img.src.replace("minus.gif", "plus.gif");

		}
		if (loaded != null) tbody.setAttribute("loaded", loaded ? "1" : "0");
  },

	toggleNextDetails : function() {
		if (!this._gridBody) return;
  	if (this._dindex == null) this._dindex= 0;
  	else this._dindex+=1;
  	if (this._dindex >= this._gridBody.rows.length) {
  		this.isAutoExpanded= null;
  		this._dindex= null;
  		return;
  	}
  	
  	var row= this._gridBody.rows[this._dindex];
  	var img= row.cells[0].firstChild;
  	if ((img == null) || (row.className != "gridSelectOn" && row.className != "grid")) { this.toggleNextDetails(); return; }
  	
  	if (img.className == "preview") {
  		this.isAutoExpanded= true;
  		this.Preview(null, row);
  	} else if (img.className == "masterdetail") {
  		this.isAutoExpanded= true;
  		this.MasterDetail(null, row);
  	}
		
	},

  initService : function() {
		if (this._service == null) this._service= new AX.FM.RecordsService.GridXDataHandler();
  },

  ExecCommand : function(cmd, preserveSelected) {
		var gridXml= this.buildGridXml(preserveSelected);
		this.prepareProgress();
		this.initService();
		this._service.ExecCommand(gridXml, cmd, this.GetSelectedIDArray(), this.onRefreshComplete, this.onRefreshFailed, this);
  },

  Select : function() {
		this.clearPagingCookie();
		this.divPageNum.setAttribute('value', 1);
		this.Refresh();
	},

  Refresh : function(preserveSelected, preventEvent) {
		if (this._bRefreshing) return;
		this._bRefreshing= true;
		var evt= Sys.EventArgs.Empty;

		if (preventEvent) this._preventRE= true;

		var gridXml= this.buildGridXml(preserveSelected);
		this.prepareProgress();
		this.initService();

		this._service.Refresh(gridXml, this.onRefreshComplete, this.onServiceFailed, this);
	},

	AutoRefresh : function() {
		this.Refresh(true, true);
	},

	setGridInnerHtml : function(gridBodyHtml) {
		if (this._gridBody != null) $clearHandlers(this._gridBody);
		this._gridBodyContainer.innerHTML= gridBodyHtml;

		this.initInnerGrid(true);

		this.load();
	},

	onRefreshComplete : function(html, element) {
		element._bRefreshing= false;
		element.hideProgress();
		if (!html) return;
		element.setGridInnerHtml(html);
		if (!element._preventRE) { element.raiseOnRefresh(); element._preventRE= false; }
	},
	onRefreshFailed : function(res, element) {
		element._bRefreshing= false;
		element.hideProgress();
		alert(res.get_message());
  },



  Reload : function() {
		this.initService();
		var gridXml= this.buildGridXml(false);
		this.prepareProgress();
		this._service.Reload(this.id, gridXml, this.onReloadComplete, this.onServiceFailed, this);
  },

  onReloadComplete : function(gridInnerHtml, element) {
		element.hideProgress();
		element.disposeBody();
		element.get_element().innerHTML= gridInnerHtml;
		element.initializeBody();
		if (element._loadSearchColumns) element.fillSearchSelector();
  },

  onServiceFailed : function(res, element) {
		element.hideProgress();
		alert(res.get_message());
  },

  Reset : function() { this.ChangeView(this.viewName); },

  LoadSubGroups : function(tbody) {
		if (!tbody) return;//tbody - is a group header
		this.initService();

		this.SetProperty("groupIndex", tbody.getAttribute("groupIndex"));
		this.SetProperty("groupValues", this.getGroupValues(tbody));

		var gridXml= this.buildGridXml();
		this.prepareProgress();
		//alert(gridXml);
		tbody.GridInstance= this;
		this._service.LoadSubGroupsOrRecords(gridXml, this.onSubGroupsLoaded, this.onSubGroupsFailed, tbody);
  },

  onSubGroupsLoaded : function(tbodyHtml, tbody, bReload) {
		var wrapDiv= document.createElement("DIV");
		wrapDiv.innerHTML="<TABLE>" + tbodyHtml + "</TABLE>";
		var tbodyRows= tbody.nextSibling;
		var table= tbody.parentNode;
		var tBodies= wrapDiv.firstChild.childNodes;
		var len= tBodies.length;
		while (len > 0) {
			len--;
			var newTBody= tBodies[tBodies.length-1];
			table.insertBefore(newTBody, tbodyRows);
		}
		if (!bReload) {
			tbody.GridInstance.toggleRow(tbody, true, true);
		} else {
			table.removeChild(tbodyRows);
		}
		tbody.GridInstance.hideProgress();
		tbody.GridInstance= null;
  },
  
  ReloadGroupRecords : function(tbody) {
		if (!tbody) return;
		this.initService();
		this.SetProperty("groupIndex", tbody.getAttribute("groupIndex"));
		this.SetProperty("groupValues", this.getGroupValues(tbody));
		this.SetProperty("groupPage", tbody.getAttribute("page"));

		var gridXml= this.buildGridXml();
		this.prepareProgress();
		tbody.GridInstance= this;
		this._service.LoadSubGroupsOrRecords(gridXml, this.onReloadSubGroups, this.onSubGroupsFailed, tbody);
  },
  
  onReloadSubGroups : function(tbodyHtml, tbody) {
		//tbody - is a group header
		tbody.GridInstance.onSubGroupsLoaded(tbodyHtml, tbody, true);
  },

  onSubGroupsFailed : function(res, tbody) {
		tbody.GridInstance.hideProgress();
		tbody.GridInstance= null;
		alert(res.get_message());
  },

  ChangeView : function(newView, newTable) {
		this.SetProperty("viewName", newView);
		if (newTable != null) this.SetProperty("tableName", newTable);
		this.SetProperty("reloadMode", "changeView");
		this._loadSearchColumns= (this.GetProperty("searchSelector") == 'true');
		this.Reload();
  },

  prepareProgress : function(s) {
		FM._ProgressBar.getInstance().Prepare(s);
  },

  hideProgress : function() {
		FM._ProgressBar.getInstance().Hide();
  },

  getGroupValues : function(tbody) {
		var v= tbody.getAttribute("value");
		var groupIndex= tbody.getAttribute("groupIndex");
		if (groupIndex == null) return "";
		while (groupIndex != "0") {
			tbody= this.getParentGroupBody(tbody, groupIndex);
			if (tbody == null || tbody.tagName != "TBODY") break;
			groupIndex= tbody.getAttribute("groupIndex");
			v= tbody.getAttribute("value") + "|" + v;
		}
		//alert(v);
		return v;
  },

  getParentGroupBody : function(tbody, groupIndex) {
		var index;
		var igroupIndex= parseInt(groupIndex);
		tbody= tbody.previousSibling;

		while (tbody != null && tbody.tagName == "TBODY") {
			index= tbody.getAttribute("groupIndex");
			if (index != null && index != groupIndex && (parseInt(index) < igroupIndex)) return tbody;
			tbody= tbody.previousSibling;
		}
		return null;
  },

  GetParentTBody : function(o) {
		while (o != null && o.tagName != "TBODY") {
			if (o.tagName == "TABLE") return null;
			o= o.parentNode;
		}
		return o;
  },

  GetParentRow : function(o) {
		while (o != null && o.tagName != "TR") {
			if (o.tagName == "TABLE") return null;
			o= o.parentNode;
		}
		return o;
  },
  GetParentCell : function(o) {
		while (o != null && o.tagName != "TD") {
			if (o.tagName == "TABLE") return null;
			o= o.parentNode;
		}
		return o;
  },

	GetProperty : function(name) {
		var o= $get(name, this.divGridProps);
		return (o) ? o.getAttribute('value') : "";
	},
	SetProperty : function(name, val) {
		var o= $get(name, this.divGridProps);
		if (!o) {
			o= document.createElement("DIV"); o.id= HtmlEncode(name);
			this.divGridProps.appendChild(o);
		}
		if (o) o.setAttribute('value', val);
	},
	GetParameter : function(name) {
		var o= $get(name, this.divGridParams);
		return (o) ? o.getAttribute('value') : null;
	},
	SetParameter : function(name, sValue) {
		var o= $get(name, this.divGridParams);
		if (!o) {
			o= document.createElement("DIV"); o.id= HtmlEncode(name);
			this.divGridParams.appendChild(o);
		}
		o.setAttribute('value', sValue);
	},

  GetSelectedIDArray : function() {
		var rows= this._aSelectedRows;
		var a= [];
		for (var i= 0; i < rows.length; i++) a[i]= rows[i].getAttribute('oid');
		return a;
	},
	GetSelectedID : function() {
		var a= this.GetSelectedIDArray();
		return (a.length > 0) ? a[0] : null;
	},
	GetSelectedRows : function() {
		return this._aSelectedRows;
	},


	buildGridXml : function(preserveSelected) {
		this._selectedIDs= (preserveSelected) ? this.GetSelectedIDArray() : null;
		var s= "<grid>";
		var i= 0;
		var oCol= this.divGridProps.childNodes;
		var iLen= oCol.length;
		for (i= 0; i < iLen; i++) {
			var v= oCol[i].getAttribute('value');
			if (v == "") {
				s+= "<" + oCol[i].id + "/>"
			} else {
				s+= "<" + oCol[i].id + ">" + XmlEncode(v) + "</" + oCol[i].id + ">";
			}
		}
		s+= "<parameters>";
		oCol= this.divGridParams.childNodes;
		iLen= oCol.length;
		for (i= 0; i < iLen; i++) {
			var v= oCol[i].getAttribute('value');
			if (v == "") {
				s+= "<" + oCol[i].id + "/>"
			} else {
				s+= "<" + oCol[i].id + ">" + XmlEncode(v) + "</" + oCol[i].id + ">";
			}
		}
		s+= "</parameters>";
		s+= "</grid>";
		return s;
	},

	updatePagingUI : function() {
		var total= (this._gridBody) ? this._gridBody.getAttribute('found') : "0";
		if (total != null && this._oItemsTotal != null) this._oItemsTotal.innerHTML= total;
		if (this._bPagingEnabled) {
			var bAreMore= false;
			if (this._gridBody) {
				this._gridBody.MoreRecords= (this._gridBody.getAttribute('morerecords') == "1");
				bAreMore= this._gridBody.MoreRecords;
			}
			var bRDisable= false;
			var bLDisable= false;
			var sL= "0";
			var sR= bAreMore ? "1" : "0";
			var sLCursor= "pointer";
			var sRCursor= "pointer";
			var	sLTitle= this._prevPageImg.alt;
			var sFRTitle= this._fastRewindImg.alt;
			var	sRTitle= this._nextPageImg.alt;
			var curPage= this.getPageNumber();

			this._oPageNumLabel.innerHTML= curPage;

			if (curPage > 1) {
				sL= "1";
			} else {
				sLCursor= "auto";
				sFRTitle= sLTitle= "";
				bLDisable= true;
			}
			if (!bAreMore) {
				sRCursor= "auto";
				sRTitle= "";
				bRDisable= true;
			}
			with (this._prevPageImg) {
				style.cursor= sLCursor;
				title= sLTitle;
				src= fmCommonPath + "Images/Grid2/page_L" + sL + ".gif";
				disabled= bLDisable;
			}

			with (this._fastRewindImg) {
				style.cursor= sLCursor;
				title= sFRTitle;
				src= fmCommonPath + "Images/Grid2/page_FL" + sL + ".gif";
				disabled= bLDisable;
			}

			with (this._nextPageImg) {
				style.cursor= sRCursor;
				title= sRTitle;
				src= fmCommonPath + "Images/Grid2/page_R" + sR + ".gif";
				disabled= bRDisable;
			}
		}
	},

	setPageNumber : function(iPage) {
		if (this._bRefreshing) return;
		if (iPage < 1) return;

		var oEvent= Sys.EventArgs.Empty;
		oEvent.NewPageNumber= iPage;
		oEvent.CurrentPageNumber= this.getPageNumber();
		this.divPageNum.setAttribute('value', iPage);

		this.Refresh(null, true);
	},

	getPageNumber : function() {
		return this._bPagingEnabled ? parseInt(this.divPageNum.getAttribute('value'), 10) : -1;
	},

	nextPage : function() {
		this.setPageNumber(this.getPageNumber() + 1);
	},
	prevPage : function() {
		this.setPageNumber(this.getPageNumber() - 1);
	},
	firstPage : function() {
		this.setPageNumber(1);
	},

	clearPagingCookie : function() {
		this.SetProperty('pagingCookie', "");
	},


	handleSelectRow : function(e, oRow) {
		if (!IsNull(oRow.IsDisabled) && oRow.IsDisabled == "1") return;

		if (e && e.shiftKey && this._iLastPickedIndex != -1) {
			if (this._iShiftClickedIndex == -1) {
				this._iShiftClickedIndex= this._iLastPickedIndex;
			}
			oRow.rowIndex < this._iShiftClickedIndex ? this.SelectRecords(oRow.rowIndex, this._iShiftClickedIndex, true) : this.SelectRecords(this._iShiftClickedIndex, oRow.rowIndex, true);
			this._iLastPickedIndex= oRow.rowIndex;
		} else {
			if (e && !e.ctrlKey) {
				this.UnselectRecords(oRow);
			}
			this.selectRow(oRow);
			this._iLastPickedIndex= oRow.rowIndex;
			this._iShiftClickedIndex= -1;
		}
		this.raiseOnSelectionChanged();
	},

  is_in_array : function(oid, ids) {
		if (ids.length == 1) return (oid == ids[0]);
		return Array.contains(this._selectedIDs, oid);
  },

	selectRow : function(oRow, fRaiseEvent) {
		if (IsNull(oRow)) return false;
		//var iMax= ParentGridControl.MaximumSelectableRecords;
		var iMax= 100;
		if (oRow.selected) return true;
		if (0 == iMax) return false;

		if ((iMax > 0 && (this._iTotalSelected + 1) <= iMax) || iMax == -1) {
			if (oRow.firstChild.className != "gridPreview") {
				this._iTotalSelected++;
				oRow.selected= true;
				this.applyStyle(oRow, "gridSelectOn");
				this._aSelectedRows.push(oRow);
				if (!IsNull(fRaiseEvent) && fRaiseEvent) {
					this.raiseOnSelectionChanged();
				}
				return true;
			}
		} else {
			alert(formatString(LOCID_GRID_TOO_MANY_RECORDS, iMax));
			return false;
		}
	},

	unselectRow : function(oRow, fUpdateSelectedRows, fRaiseEvent) {
		if (!IsNull(oRow) && oRow.selected) {
			var oTmp= this._gridBody.rows[oRow.rowIndex + 1];
			if (!IsNull(oTmp)) {
				oTmp= oTmp.firstChild.firstChild;
			}
			this._iTotalSelected--;
			oRow.selected= false;
			this.applyStyle(oRow, "grid");

			if (!IsNull(fUpdateSelectedRows) && fUpdateSelectedRows) {
				var iLength= this._aSelectedRows.length;
				for (var i= 0; i < iLength; i++) {
					if (oRow.rowIndex == this._aSelectedRows[i].rowIndex) {
						this._aSelectedRows.splice(i, 1);
						break;
					}
				}
			}
			if (!IsNull(fRaiseEvent) && fRaiseEvent) {
				this.raiseOnSelectionChanged();
			}
		}
	},

	findColumn : function(sName) {
		var i= 0;
		var oCells= this._gridBar.rows[0].cells;
		var iLen= oCells.length;
		while (i < iLen) {
			var f= oCells[i].getAttribute('field');
			if (f == sName) return oCells[i];
			i++;
		}
		return null;
	},

	updateSelectedItemsUI : function(iNum, iTotal) {
		if (!this.allowSelect) return;
		if (this._oGridStatusBar) {
			if (this._itemsSelected == null) this._itemsSelected= $get('_ItemsSelected', this._oGridStatusBar);
			if (this._itemsOnPage == null) this._itemsOnPage= $get('_ItemsOnPage', this._oGridStatusBar);
		//if (this._chkAll == null) this._chkAll= $get('chkAll', this._oGridStatusBar);

			if (this._itemsSelected != null) this._itemsSelected.innerHTML= iNum;
			if (this._itemsOnPage != null) this._itemsOnPage.innerHTML= iTotal;
		}
		if (this._chkAll != null) {
			this._chkAll.checked= ((iNum == iTotal) && iTotal > 0);
			this._chkAll.disabled= iTotal == 0;
		}
	},


	applyStyle : function(o, sClass) {
		o.className= sClass;
		var i= 0;
		if (sClass == "gridSelectOn") {
			//this.setIcon(o, (fmCommonPath + "Images/Grid2/row_selected.gif"));
		} else {
			//this.setIcon(o, (fmCommonPath + "Images/Grid2/r.gif"));
		}
	},

	SelectRecords : function(iStart, iStop, fUnselect) {
		var bResult;
		if (IsNull(iStart)) iStart= 0;
		var rows= this._gridBody.rows;
		if (IsNull(iStop)) iStop= rows.length - 1;

		if (!IsNull(fUnselect) && fUnselect && iStop != rows.length -1 && iStart != 0) {
			var iLength= this._aSelectedRows.length;
			for (var i=0; i < iLength; i++) {
				var oRow= this._aSelectedRows[i];
				if (!IsNull(oRow) && (oRow.rowIndex < iStart || oRow.rowIndex > iStop)) {
					this.unselectRow(oRow);
					this._aSelectedRows.splice(i, 1);
					i--;
					iLength--;
				}
			}
		}
		for (; iStart < iStop + 1; iStart++) {
			//this.collapseRow(rows[iStart]);
			bResult= this.selectRow(rows[iStart]);
			if (!bResult) break;
		}
		this._iLastPickedIndex= iStop;
		this.raiseOnSelectionChanged();
	},

	UnselectRecords : function(oSkip) {
		var oTr= this._aSelectedRows.pop();
		while (!IsNull(oTr)) {
			this.unselectRow(oTr);
			//m/this.collapseRow(oTr);
			oTr= this._aSelectedRows.pop();
		}

		if (!IsNull(oSkip)) {
			this.selectRow(oSkip);
		}
		// 2008-01-30: avoid double fireing
		/*
		this.raiseOnSelectionChanged();*/
	},


  raiseOnRefresh: function() {
		if (this.OnRefresh && this._gridBody) this.OnRefresh(this._gridBody.getAttribute('found'));
	},

	// Events	
	add_onSelectionChanged: function(h) { this.get_events().addHandler("onSelectionChanged", h); },
  remove_onSelectionChanged: function(h) { this.get_events().removeHandler("onSelectionChanged", h); },
  raiseOnSelectionChanged: function() { 
		this.updateSelectedItemsUI(this._aSelectedRows.length, this._iTotalOnPage);
		var h= this.get_events().getHandler("onSelectionChanged"); 
		if (h) h(); 
	},


	// DRAG COLUMN ZONE
	//
  addGroupingColumnBefore : function(newColumn, beforeColumn) {
		var sGroups= this.GetProperty("groupColumns");
		var groups= (sGroups != "") ? sGroups.split(',') : new Array();
		if (Array.indexOf(groups, newColumn) > -1) return;
		if (beforeColumn != null) {
			var beforeIndex= Array.indexOf(groups, beforeColumn);
			Array.insert(groups, beforeIndex, newColumn);
		} else {
			Array.add(groups, newColumn);
		}
		this.SetProperty("groupColumns", groups.toString());
		this.Reload();
  },
  removeGroupingColumn : function(field) {
		var sGroups= this.GetProperty("groupColumns");
		var groups= (sGroups != "") ? sGroups.split(',') : new Array();
		if (Array.indexOf(groups, field) == -1) return;
		Array.remove(groups, field);
		this.SetProperty("groupColumns", groups.toString());
		this.Reload();
  },

  MasterDetail : function(oIcon, oRow) {
		if (!oRow) {
			if (oIcon.tagName != "IMG") return;
			oRow= this.GetParentRow(oIcon);
		}	
		if (!oRow) return;
		oRow.ImageIcon= oIcon;
		if (oRow.getAttribute('exp') != '1') {
			this.initService();
			var keyValue= oRow.getAttribute("oid");
			this.prepareProgress();
			this.initService();
			this._expandedRow= oRow;
			this._service.LoadMasterDetail(this.tableName, this.viewName, keyValue, this.onRecordMasterDetailComplete, this.onServiceFailed, this);
		} else {
			if (oRow.grid != null) { oRow.grid.dispose(); oRow.grid= null;}
			this.collapseRow(oRow);
			if (this.isAutoExpanded) this.toggleNextDetails();
		}
  },


	onRecordMasterDetailComplete : function(html, element) {
		element.hideProgress();
		var newRow= element.expandRowHtml(element._expandedRow, html);
		if (newRow != null) {
			newRow.grid= $create(FM.DataGrid, {}, null, null, newRow.cells[1].firstChild);
		}
		if (element.isAutoExpanded) element.toggleNextDetails();

	},

	expandRowHtml : function(oTr, html, bPreview) {
		if (IsNull(oTr)) return null;
		if (html == "") { this.setIcon(oTr, null, true); return; }
		if (oTr.getAttribute('exp') == '1') {
			this.collapseRow(oTr);
			oTr.scrollIntoView(false);
			return null;
		}
		var tbody= oTr.parentNode;
		var pi= tbody.getAttribute('pi');
		var colspan= (pi != null) ? (parseInt(pi) + 2) : 1;
		var oNewTR= tbody.insertRow(oTr.sectionRowIndex+1);
		oNewTR.oid= oTr.oid;
		if (bPreview) colspan--;
		var oTD1= oNewTR.insertCell(0);
		oTD1.className= "recordDetails";
		oTD1.innerHTML= "&nbsp;";
		if (colspan > 1) oTD1.colSpan= colspan;
		var oTD= oNewTR.insertCell(1);
		oTD.className= "recordDetails";
		oTD.style.backgroundColor= "#FFFFFF";
		oTD.style.paddingRight= "6px";
		oTD.colSpan= oTr.cells.length - colspan;
		oTD.innerHTML= html;
		
		if (bPreview && !this.isAutoExpanded) FM._ResourceLoader.StartTransitionalEffect(oTD.firstChild, 20, 10, 30);
		
		//oTD.scrollIntoView(false);

		oTr.setAttribute('exp', '1');
		this.setIcon(oTr, true);
		return oNewTR;
	},


	collapseRow : function(oTr) {
		//var img= fmCommonPath + "Images/r_plus.gif";
		//if (oTr.className == "preview") img= fmCommonPath + "Images/Grid2/r.gif";
		//alert(img);
		if (!IsNull(oTr) && oTr.getAttribute('exp') == '1') {
			this.setIcon(oTr, false); //"Images/Grid2/row_selected.gif";
			this._gridBody.deleteRow(oTr.rowIndex + 1);
			oTr.setAttribute('exp', '0')
		}
	},

  Preview : function(oIcon, oRow) {
		if (oRow == null) {
			if (oIcon.tagName != "IMG") return;
			oRow= this.GetParentRow(oIcon);
		}	
		if (!oRow) return;
		oRow.ImageIcon= oIcon;
		if (oRow.getAttribute('exp') != '1') {
			var keyValue= oRow.getAttribute("oid");
			this.initService();
			this._expandedRow= oRow;
			this._service.LoadRecordPreview(this.tableName, this.viewName, keyValue, this.onRecordPreviewComplete, this.onServiceFailed, this);
		} else {
			this.collapseRow(oRow);
			if (this.isAutoExpanded) this.toggleNextDetails();
		}
  },
  onRecordPreviewComplete : function(html, element) {
		element.expandRowHtml(element._expandedRow, html, true);
		if (element.isAutoExpanded) element.toggleNextDetails();
	},

	HideRelations : function(oRow) {
		this.collapseRow(oRow);
	},

	setIcon : function(oTr, bOpenedIcon, bOff) {
		var tbody= oTr.parentNode;
		var pi= tbody.getAttribute('pi');
		if (pi != null) pi= parseInt(pi) + 1;
		else pi= 0;
		var img= window.getFirstElement(oTr.childNodes[pi]);
		if (img) {
			if (bOff) {
				img.src= fmCommonPath + "Images/r_off.gif";
				img.style.cursor= "default";
				img.onclick= null;
				return;
			}
			var img_src;
			if (bOpenedIcon) {
				img_src= fmCommonPath + "Images/r_minus.gif";
				if (img.className == "preview") img_src= fmCommonPath + "Images/Grid2/d.gif";
			} else {
				img_src= fmCommonPath + "Images/r_plus.gif";
				if (img.className == "preview") img_src= fmCommonPath + "Images/Grid2/r.gif";
			}
			img.src= img_src;
		}
	},

	ToggleHierarchy : function(img) {
		var oCell= img.parentNode;
		var oRow= oCell.parentNode;
		var plevel= oRow.getAttribute("level");
		if (plevel == null) plevel= 0;
		var expanded= img.src.indexOf('minus.gif') > 0;
		img.src= fmCommonPath + ((expanded) ? "Images/r_plus.gif" : "Images/r_minus.gif");
		var oRow= oRow.nextSibling;
		var iplevel= parseInt(plevel) + 1; // children level
		var open= !expanded;
		while (oRow != null) {
			var level= oRow.getAttribute('level');
			if (level == null) break;
			var ilevel= parseInt(level)
			if (ilevel < iplevel) break;
			if (ilevel == iplevel) { // set expanded state only for row children
				oRow.setAttribute('h_exp', open ? "1" : "0");
			}
			this.toggleHierarchiRow(oRow, !expanded);
		  oRow= oRow.nextSibling;
		}
	},

	toggleHierarchiRow : function(oRow, open) {
		if (open) {
			if (oRow.getAttribute('h_exp') == '0') return;
			oRow.style.display= (Sys.Browser.agent == Sys.Browser.Firefox) ? "table-row" : "inline";
		} else {
			oRow.style.display= "none";
		}
	},
	
	initScrollTable : function() {
		if (!this._gridBodyContainer) return;
		var o= this.get_element();
		if (o.className != "scrollTable") return;
		var gridbar= o.firstChild;
		var h= this._gridBodyContainer.style.height;
		if (h == "" || h == "10px") {
			//trace("111");
			var topDiv= getFirstElement(o.parentNode);
			var topHeight= 22; // footer
			topHeight+= topDiv.offsetHeight; // search bar
			//trace("topDivH:" + topDivH);
			//trace("end", true);
			if (this.allowGrouping) {
				gridbar= gridbar.nextSibling;
				topHeight+= o.firstChild.offsetHeight; // grouping height
				//if (Sys.Browser.agent === Sys.Browser.InternetExplorer) topHeight+= 2;
			}
			//this.divHeader= head;
			this.divFooter= o.lastChild;
			this.panelsHeight= topHeight + this.divFooter.offsetHeight;
			
			this.resizeScrollTable(o);
			
			this.divFooter.style.visibility= 'visible';
		}
		if (!this._scrollBodyDlg) this._scrollBodyDlg= Function.createDelegate(gridbar, this.scrollBody);
		$addHandler(this._gridBodyContainer, 'scroll', this._scrollBodyDlg);
	},

	scrollBody : function(e) { this.scrollLeft= e.target.scrollLeft; },

	resizeScrollTable : function() {
		var o= this.get_element();
		this.containerHeight= o.parentNode.clientHeight;
		if (Sys.Browser.agent == Sys.Browser.Safari) this.containerHeight= o.parentNode.offsetHeight;
		this._gridBodyContainer.style.height= Math.max(0, this.containerHeight - this.panelsHeight) + 'px';
		var ofw= this._gridBodyContainer.offsetWidth;
		var scw= this._gridBodyContainer.scrollWidth;
		if (ofw != scw) this._gridBodyContainer.style.overflowX= "scroll";
	},
	
	Resize : function() { // for search grid
		if (!this._gridBodyContainer) return;
		var o= this.get_element();
		var topDiv= getFirstElement(o.parentNode);
		var topHeight= 22 + topDiv.offsetHeight; // footer + search bar
		if (this.allowGrouping) topHeight+= o.firstChild.offsetHeight; // grouping height

		this.panelsHeight= topHeight + this.divFooter.offsetHeight;
		this._gridBodyContainer.style.height= Math.max(0, this.containerHeight - this.panelsHeight) + 'px';
	},
	

	_onmouseover : function(e) {
		var oRow= this.GetParentRow(e.target);
		if (oRow && oRow.getAttribute('oid')) { if (oRow._bgcolor == null) oRow._bgcolor= oRow.style.backgroundColor; oRow.style.backgroundColor= "#FEFDE0"; }	
	},

	_onmouseout : function(e) {
		var oRow= this.GetParentRow(e.target);
		if (oRow && oRow.getAttribute('oid')) { oRow.style.backgroundColor= oRow._bgcolor; }
	},

	// Print,Export
	//
	Print : function() {
		var iResult= this.determineExportPrintPaging("print");
		if (iResult && (iResult.result != RESULT_CANCEL)) {
			var oForm= this.createExportPrintForm(iResult.result);
			var winname= "print" + buildWinName(this.viewName);
			window.open("", winname, "left=150,top=100,width=850,height=500,status=1,resizable=1,scroll=0");
			oForm.action= window.fmDataViewerPath + "Print/Grid.aspx";
			oForm.target= winname;
			oForm.submit();
		}
	},
	Export : function() { 
		var iResult= this.determineExportPrintPaging("print");
		if (iResult && (iResult.result != RESULT_CANCEL)) {
			var oForm= this.createExportPrintForm(iResult.result, true);
			oForm.action= fmDataViewerPath + "Print/Export_data.aspx"; oForm.target= "gridExportFrame";
			oForm.submit();
		}
	},
	BulkProcess : function(params) {
		var oForm= this.createExportPrintForm(RESULT_ALLPAGES, true);
		var url= fmDataViewerPath + "Grid/Plugins/BulkProcess.aspx?t="+this.tableName+"&params="+params;
		oForm.action= url; oForm.target= "gridExportFrame";
		oForm.submit();
	},

	createExportPrintForm : function(iResult, bframe) {
		if (window.document.forms("gridExportPrint")) {
			var o= window.document.forms("gridExportPrint");
			o.elements["gridXml"].value= this.buildGridXml();
			o.elements["printAllPages"].value= iResult;
		} else {
			var oForm= document.createElement("<form name='gridExportPrint' method='post' style='display:none'>");
			var oInput= document.createElement("<input type=hidden name=gridXml>");
			oInput.value= this.buildGridXml();
			oForm.appendChild(oInput);
			oInput= window.document.createElement("<input type=hidden name=printAllPages>");
			oInput.value= iResult;
			oForm.appendChild(oInput);
			document.body.insertBefore(oForm);
		}
		if (bframe && $get('gridExportFrame') == null) {
			var af= document.createElement("<iframe id='gridExportFrame' name='gridExportFrame' style='display:none'></iframe>");
			document.body.insertBefore(af);
		}

		return window.document.forms("gridExportPrint");
	},

	determineExportPrintPaging : function(sMode) {
		var total= this._gridBody.getAttribute('found');
		if (total== null || total == "0") return false;

		var bMultiPage= (this._gridBody.MoreRecords || (this.getPageNumber() > 1));
		if (!bMultiPage) { var o= new Object(); o.result= RESULT_ALLPAGES; return o; }

		var sUrl= fmDataViewerPath + "Print/Print_dlg.aspx?mode=" + sMode + "&multipage=" + (bMultiPage ? "1" : "0");
		return openStdDlg(sUrl, null, 400, 240);
	},
	PrintRow : function(oRow) {
		var oid= oRow.getAttribute('oid');
		openStdWin(fmDataViewerPath + "Print/Item.aspx?t=" + this.tableName + "&id=" + oid, "printrow" + buildWinName(oid), 800, 500, false);
	},
	_onGridOver : function(e) {
		var o= e.target;
		if (o.tagName == "NOBR" && o.title != null) {
			o.title= o.innerText;
		}
	},
	//

	fillSearchSelector : function() {
		if (this._searchSelector == null) this._searchSelector= $get(this.id + "_fmFieldSelector");
		var div= this._gridFooter.lastChild;
		if (div.id == "divSearchColumns") {
			var o= this._searchSelector;
			var list= div.innerHTML.split(',');
			while (0 < o.options.length) o.remove(0);
			var j= 0;
			for (var i= 0 ; i < list.length; i+=2) {
				o.options[j++]= new Option(list[i+1], list[i]);
			}
		}
	},

	focus : function() {
		if (this._gridBody) this._gridBody.focus();
	}
}

FM.DataGrid.HandlePage= function(o, mode) { // for grouped pages
	var tbody= o.parentNode.parentNode.parentNode;
	var _gridBodyContainer= tbody.parentNode.parentNode;
	var grid= _gridBodyContainer.GridInstance;
	tbody= tbody.previousSibling;
	var p= parseInt(tbody.getAttribute("page"));
	if (mode == "next") p+= 1;
	else if (mode == "prev") p-= 1;
	else if (mode == "first") p= 1;
	tbody.setAttribute("page", p);
	grid.ReloadGroupRecords(tbody);
}

window.sortOverImage= "url(" + fmCommonPath + "Images/Grid2/grid_BarBkOn.gif)";

FM.DataGrid.inheritsFrom(Sys.UI.Control);
FM.DataGrid.registerClass('FM.DataGrid', Sys.UI.Control);



FM.SortColumnInfo= function () {
	this.sName= "";
	this.fAscend= true;
	this.Deserialize= function(sColumn) {
		var asParams= sColumn.split(":");
		if (asParams.length == 2) {
			this.sName= asParams[0];
			this.fAscend= (asParams[1] == "0");
		}
	},
	this.Serialize= function() {
		return this.sName + ":" + (this.fAscend ? "0" : "1");
	}
}
FM.SortColumnInfo.registerClass('FM.SortColumnInfo');

FM.SortColumnCollection= function() {
	this.aSortColumns= new Array();

	this.Deserialize= function(sGridParameter) {
		var asColumns= sGridParameter.split(";");
		var nLength= asColumns.length;
		for (var i= 0; i < nLength; i++) {
			var oSortInfo= new FM.SortColumnInfo();
			oSortInfo.Deserialize(asColumns[i]);
			this.aSortColumns.push(oSortInfo);
		}
	},
	this.IndexOf= function(sColumnName) {
		var nLength= this.aSortColumns.length;
		for (var i= 0; i < nLength; i++) {
			if (this.aSortColumns[i].sName == sColumnName) return i;
		}
		return -1;
	},
	this.Serialize= function() {
		var sParameter= "";
		var nLength= this.aSortColumns.length;
		for (var i= 0; i < nLength; i++) {
		if (i > 0) sParameter+= ";"
		sParameter+= this.aSortColumns[i].Serialize();
		}
		return sParameter;
	},
	this.Toggle= function(sColumnName, fAppend) {
		var oSortInfo= new FM.SortColumnInfo();
		oSortInfo.sName= sColumnName;
		var nIndex= this.IndexOf(sColumnName);
		if (nIndex != -1) {
			oSortInfo.fAscend= !this.aSortColumns[nIndex].fAscend;
			if (fAppend) { this.aSortColumns[nIndex]= oSortInfo; return; }
		}

		if (!fAppend) { this.aSortColumns= new Array(); }
		this.aSortColumns.push(oSortInfo);
	}
}
FM.SortColumnCollection.registerClass('FM.SortColumnCollection');



//	/	/	/	/	/	 GROUPING ZONE /	/	/	/	/	/	/	/	/	/	/
//
FM.UI.GroupingZone= function(element) {
	// Properties
	this._gridBar= null;
	this._onmouseupCallback= null;
	this._onGroupClickCallback= null;
	this._gZoneTable= null;

	this._dummyColumn= null;
  this._moving= false;
  this._ismousedown= false;
	this._activeColumn= null;
	this._onmousemovedlg= null;
	this._onselectstartdlg= null;
	this._onmouseupdlg= null;
	this._onkeydowndlg= null;
	this._lastX= 0;
	this._lastY= 0;
	this._dragTarget= null;

	FM.UI.GroupingZone.initializeBase(this, [element]);
}

FM.UI.GroupingZone.prototype= {

	initialize : function() {
	 	FM.UI.GroupingZone.callBaseMethod(this, 'initialize');
	 	this._gZoneTable= this.get_element().firstChild;
	},

	dispose: function() {
		if (this._gridBar != null) $clearHandlers(this._gridBar);
		if (this._gZoneTable != null) $clearHandlers(this._gZoneTable);

		FM.UI.GroupingZone.callBaseMethod(this, 'dispose');
	},

	setupGridBar : function(gridBar, onmouseupCallback, onGroupClickCallback) {
		this._gridBar= gridBar;
		this._onmouseupCallback= onmouseupCallback;
		this._onGroupClickCallback= onGroupClickCallback;

		$addHandlers(this._gridBar,
		{ 'mousedown': this._onColumnDown }, this);

		$addHandlers(this._gZoneTable,
		{ 'dblclick': this._onDblClick }, this);

	},

	_onDblClick : function(e) {
		var o= e.target;
		if (o.tagName == "NOBR") o= o.parentNode;
		if (o.tagName != "SPAN") return;
		var field= o.getAttribute('field');
		if (field != null) this._onGroupClickCallback(field);
	},

	_onColumnDown : function(e) {
		var o= e.target;
		if (o.tagName == "IMG") return;
		while (o.tagName != "TD") o= o.parentNode;

		if (o.tagName == "TD" && o.getAttribute('field')) {
			this._ismousedown= true;
			this._activeColumn= o;
			this._lastX= e.clientX;
			this._lastY= e.clientY;
			this._onmousemovedlg= Function.createDelegate(this, this._onmousemove);
      $addHandler(document, 'mousemove', this._onmousemovedlg);
      this._onmouseupdlg= Function.createDelegate(this, this._onmouseup);
			$addHandler(document, 'mouseup', this._onmouseupdlg);
		}
	},


	_onmousemove : function(e) {
		if (!e) e= event;
    if (this._ismousedown) {
			if (this._moving == false) {
				if (this._lastX == e.clientX && this._lastY == e.clientY) return;
				this._prepareColumnDummy(this._activeColumn, e.clientX, e.clientY);
				if (this._dummyColumn == null) return;
				this._moving= true;

				this._onselectstartdlg= Function.createDelegate(this, this._onselectstart);
				$addHandler(document, 'selectstart', this._onselectstartdlg);
				this._onkeydowndlg= Function.createDelegate(this, this._onkeydown);
				$addHandler(document, 'keydown', this._onkeydowndlg);
			}
			//this._dragTarget= e.target;
			this._moveColumnDummy(e.clientX, e.clientY);
    }
  },

  _prepareColumnDummy : function(oCell, x, y) {
		if (this._dummyColumn == null) {
			try {
				var o= document.createElement("SPAN");
				o.style.position= "absolute";
				o.className= "gcolumn";
				document.body.insertBefore(o, document.body.firstChild);
				this._dummyColumn= o;
			} catch (e) {this._dummyColumn= null; alert(e.description); return; }
		} else {
			this._dummyColumn.style.visibility= "visible";
		}
		this._dummyColumn.setAttribute('field', oCell.getAttribute('field'));
		var textNode= oCell.firstChild.childNodes[0];
		this._dummyColumn.innerHTML= "<nobr>" + textNode.data + "</nobr>";
  },
  _moveColumnDummy : function(x, y) {
		var o= this._dummyColumn;
		if (!o) return;
		o.style.left= (x + 1) + "px";
		o.style.top= (y + 1) + "px";
  },

  _onmouseup : function(e, bCancel) {
    $removeHandler(document, 'mousemove', this._onmousemovedlg); this._onmousemovedlg= null;
    if (this._onkeydowndlg) { $removeHandler(document, 'keydown', this._onkeydowndlg); this._onkeydowndlg= null; }
    if (this._onmouseupdlg) { $removeHandler(document, 'mouseup', this._onmouseupdlg); this._onmouseupdlg= null; }
    if (this._onselectstartdlg) { $removeHandler(document, 'selectstart', this._onselectstartdlg); this._onselectstartdlg= null; }

		if (this._moving == false) return;
		e.stopPropagation(); // disable mouse click
		e.preventDefault();
    this._moving= false;
    this._ismousedown= false;

		if (!bCancel) {
			var zone= e.target;
			if (zone && zone.tagName == "TD" && zone.className == "gZone") {
				this._onmouseupCallback(this._dummyColumn.getAttribute('field'), null);
			}
    }
    if (this._dummyColumn != null) this._dummyColumn.style.visibility= "hidden";
  },

	_onselectstart : function(e) { e.preventDefault(); return false; },
	_onkeydown : function(e) {
		if (e.keyCode == 27) this._onmouseup(e, true);
	},

	EndFunc: function() {
	}
}

FM.UI.GroupingZone.inheritsFrom(Sys.UI.Control);
FM.UI.GroupingZone.registerClass('FM.UI.GroupingZone', Sys.UI.Control);

//	/	/	/	/	/	 POPUP MENU /	/	/	/	/	/	/	/	/	/	/
//

FM.PopupMenu= function(element, grid) {
	// Properties
	this.parentGrid= grid;
	this.parentRow= null;
	this.menu= element;

	this._oPop= null;
	this.eventsAttached= false;
}

FM.PopupMenu.prototype= {

	dispose: function() {
		if (this.eventsAttached) {
			this.eventsAttached= false;
			$clearHandlers(o);
		}

		FM.PopupMenu.callBaseMethod(this, 'dispose');
	},
	
	Show : function(e, r) {
		this.parentRow= r;
		this.popupToggle(IsNull(r) || IsNull(r.getAttribute('oid')));
		
		var o= this.menu;
		var scrolledY;
		if (self.pageYOffset) {
			scrolledY= self.pageYOffset;
		} else if (document.documentElement && document.documentElement.scrollTop) {
			scrolledY= document.documentElement.scrollTop;
		} else if (document.body) {
			scrolledY= document.body.scrollTop;
		}
		with(o.style) {
			left= e.clientX - 3;
			top= e.clientY + scrolledY - 3;
			display= "block";
		}
		
		if (!this.eventsAttached) {
			this.eventsAttached= true;
			var f= Function.createDelegate(this, this.popGlow);
			$addHandlers(o, { 'mouseover': f, 'mouseout': f }, this);
			
			this.documentMouseUpHnd= Function.createDelegate(this, this.documentMouseUp);
		}
		
		$addHandler(window.document, 'mouseup', this.documentMouseUpHnd);
		
		this.parentGrid.handleSelectRow(e, r);
	},
	
	Hide : function() {
		if (this._lastGlow != null) { this.toggleItem(this._lastGlow, false); this._lastGlow= null; }
		this.menu.style.display= "none";
		//this.parentRow.style.backgroundColor= this.parentRow._bgc;
	},
	
	documentMouseUp : function(e) {
		$removeHandler(window.document, 'mouseup', this.documentMouseUpHnd);
		this.Hide();
	},

	popGlow : function(e) {
		var o= e.target;
		if (o.id == "_PopupMenu") {
			if (this._lastGlow != null) { this.toggleItem(this._lastGlow, false); this._lastGlow= null; }
			return;
		}

		if (o.tagName == "LABEL") o= o.parentElement;

		if (o.className == "item") {
			o.parentGrid= this.parentGrid;
			o.parentRow= this.parentRow;
			if (this._lastGlow != o) {
				if (this._lastGlow != null) this.toggleItem(this._lastGlow, false);
				this.toggleItem(o, true);
				this._lastGlow= o;
			}
		}
	},
	
	toggleItem : function(o, b) {
		o.runtimeStyle.backgroundColor= (b) ? "#d9eaff" : "transparent";
		o.runtimeStyle.borderColor= (b) ? "#2889ff" : "";
	},

	popupToggle : function(b) {
		var o= this.menu.all.tags("div");

		if (o.length > 1 && o[0].disabled != b) {
			o[0].disabled= o[1].disabled= b;
			this._oPop= null;
		}
	}

}

FM.PopupMenu.registerClass('FM.PopupMenu', null, Sys.IDisposable);


// END
Sys.Application.notifyScriptLoaded();