// MultilogicGrid Client Script Library
// Alfa-XP, Michael Isipciuc, 2006-2007.
//
Type.registerNamespace("FM");

FM.DataGridCollection= function() {
	this._grids= [];
	this.Register= function(dg) { this._grids[dg.id]= dg;	}
	this.Unregister= function(dg) { this._grids[dg.id]= null;	}
	this.Find= function(id) { return this._grids[id]; }
}
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) {
		//trace('a0');
		FM.DataGrid.initializeBase(this, [element]);
		// Properties
		this.id= element.getAttribute('id');
		this.tableName= element.getAttribute('tableName');
		this.viewName= element.getAttribute('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.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;

    // 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._progressBar= null;
		this._groupingZone= null;
		this._recordExpandMode= 2; // { 0:off, 1: info}

		//
		this._bRefreshing= false;
		this.divHeader= null;
		this.panelsHeight= 0;

		this._timerID= null;

		this.progressTimeout= 400;
}

FM.DataGrid.prototype= {

  initialize : function() {
		FM.DataGrid.callBaseMethod(this, 'initialize');
		this.initContainer();
		this.initScrollTable();

		window.fmGrids.Register(this);

		if (this.autoRefreshTime != "0") {
			var refreshCallback= Function.createDelegate(this, this.AutoRefresh);
			this._timerID= window.setInterval(refreshCallback, parseInt(this.autoRefreshTime));
		}
		if (this.regScripts != null) fmLoadScript(this.regScripts); // fix it for multi
		//trace('end', true);
  },

  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.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.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].innerText != "";
			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);
			}
		}
		this.initInnerGrid();
		this.load();
  },

  dispose : function() {
			if (this.get_element() == null) return;
      $clearHandlers(this._gridBar);
			if (this._gridBody != null) $clearHandlers(this._gridBody);
			if (this._groupingZone != null) this._groupingZone.dispose();

			if (this._bPagingEnabled) {
				$clearHandlers(this._nextPageImg);
				$clearHandlers(this._prevPageImg);
				$clearHandlers(this._fastRewindImg);
			}
			if (this._timerID != null) window.clearInterval(this._timerID);
			$clearHandlers(this.get_element());
			window.fmGrids.Unregister(this);
      FM.DataGrid.callBaseMethod(this, 'dispose');
  },

  initInnerGrid : function() {
		if (this._gridBodyContainer == null) return;
		this._gridBody= this._gridBodyContainer.firstChild;

		$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);
		}

		this._aSelectedRows= [];
		this._iTotalSelected= 0;
		this.updatePagingUI();
	},

  load : function() {
		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":case "SPAN":
				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();
	},

	_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;

		//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);
			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") {
					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 ? "block" : "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");
  },

  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.onServiceFailed, this);
  },

  Select : function() {
		this.clearPagingCookie();
		this.divPageNum.setAttribute('value', 1);
		this.Refresh();
	},

  Refresh : function(preserveSelected) {
		if (this._bRefreshing) return;
		this._bRefreshing= true;
		var evt= Sys.EventArgs.Empty;

		//this.disablePaging();

		var gridXml= this.buildGridXml(preserveSelected);
		this.prepareProgress();
		this.initService();
		this._service.Refresh(gridXml, this.onRefreshComplete, this.onServiceFailed, this);
	},

	AutoRefresh : function() {
		this.Refresh(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.hideProgress();
		if (!html) return;
		element.setGridInnerHtml(html);
	},

  Reload : function() {
		this.initService();
		var gridXml= this.buildGridXml(false);
		this.prepareProgress();
		this._service.Reload(this.id, gridXml, this.onReloadComplete, this.onServiceFailed, this);
  },

  onReloadComplete : function(gridHtml, element) {
		element.hideProgress();
		var parent= element.get_element().parentNode;
		var _loadSC= element._loadSearchColumns;
		element.dispose();

		parent.innerHTML= gridHtml;
		var grid= $create(FM.DataGrid, {}, null, null, parent.firstChild);
		if (_loadSC) grid.fillSearchSelector();
  },

  onServiceFailed : function(res, element) {
		element.hideProgress();
		if (res.get_statusCode() == 500) window.parent.location.reload(true);
		else alert(res.get_message());
  },

  Reset : function() { this.ChangeView(this.viewName); },

  LoadSubGroups : function(tbody) {
		if (!tbody) return;
		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) {
		var wrapDiv= document.createElement("DIV");
		//alert(tbodyHtml);
		wrapDiv.innerHTML="<TABLE>" + tbodyHtml + "</TABLE>";
		var tBodies= wrapDiv.firstChild.childNodes;
		var len= tBodies.length;
		while (len > 0) {
			len--;
			var newTBody= tBodies[tBodies.length-1];
			tbody.parentNode.insertBefore(newTBody, tbody.nextSibling);
		}
		tbody.GridInstance.toggleRow(tbody, true, true);
		tbody.GridInstance.hideProgress();
		tbody.GridInstance= null;
  },

  onSubGroupsFailed : function(res, tbody) {
		tbody.GridInstance.hideProgress();
		tbody.GridInstance= null;
		alert(res.get_message());
  },

  ChangeView : function(newView) {
		this.SetProperty("viewName", newView);
		this.SetProperty("reloadMode", "changeView");
		this._loadSearchColumns= (this.GetProperty("searchSelector") == 'true');
		this.Reload();
  },

  prepareProgress : function() {
		window.status= "Loading ...";
		if (this._progressBar == null) {
			this._progressBar= $get("_ProgressBarPanel", this.get_element());
			window.document.body.appendChild(this._progressBar);
		}
    if (this.progressTimeout > 0 && this._progressBar != null) {
      this._progressTimer= window.setTimeout(Function.createDelegate(this._progressBar, this.showProgress), this.progressTimeout);
    }
  },

  showProgress : function() {
		this.style.posTop= (document.body.clientHeight / 2 - 100);
		this.style.posLeft= (document.body.clientWidth / 2 - 50);
		this.style.display= "inline";
  },

  hideProgress : function() {
		window.status= "";
		this._bRefreshing= false;
		if (this._progressTimer) {
      window.clearTimeout(this._progressTimer);
      this._progressTimer= null;
    }
		if (this._progressBar) this._progressBar.style.display= "none";
  },

  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 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 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;
	},


	disablePaging : function() {
		if (!this._bPagingEnabled) return;
		with (this._prevPageImg) {
			style.cursor= "auto";
			title= "";
			src= fmCommonPath + "Images/Grid2/page_L0.gif";
			disabled= true;
		}

		with (this._fastRewindImg) {
			style.cursor= "auto";
			title= "";
			src= fmCommonPath + "Images/Grid2/page_FL0.gif";
			disabled= true;
		}

		with (this._nextPageImg) {
			style.cursor= "auto";
			title= "";
			src= fmCommonPath + "Images/Grid2/page_R0.gif";
			disabled= true;
		}
	},

	updatePagingUI : function() {
		if (!this._gridBody) return;
		var total= this._gridBody.getAttribute('found');
		if (total != null && this._oItemsTotal != null) this._oItemsTotal.innerText= total;
		if (this._bPagingEnabled) {
			if (this._gridBody.MoreRecords == null) {
				this._gridBody.MoreRecords= (this._gridBody.getAttribute('morerecords') == "1");
			}
			var bAreMore= this._gridBody.MoreRecords;

			var bRDisable= false;
			var bLDisable= false;
			var sL= "0";
			var sR= bAreMore ? "1" : "0";
			var sLCursor= "hand";
			var sRCursor= "hand";
			var	sLTitle= this._prevPageImg.altTitle;
			var sFRTitle= this._fastRewindImg.altTitle;
			var sFRTitle= "";
			var	sRTitle= this._nextPageImg.altTitle;
			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();
		//OnChangePage.fire(oEvent);
		//if (!IsNull(oEvent.returnValue) && !oEvent.returnValue) return;
		this.divPageNum.setAttribute('value', iPage);

		this.Refresh();
	},

	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.raiseSelectionChangeEvent();
	},

  is_in_array : function(id, ids) {
		if (ids.length == 1) return (id == 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.raiseSelectionChangeEvent();
				}
				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.raiseSelectionChangeEvent();
			}
		}
	},

	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.innerText= iNum;
			if (this._itemsOnPage != null) this._itemsOnPage.innerText= 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.raiseSelectionChangeEvent();
	},
	/*
	SelectRecordsArray : function(indexes) {
		var rows= this._gridBody.rows;
		var bResult= false;
		for (var i= 0; i < indexes.length; i++) {
			bResult= this.selectRow(rows[indexes[i]], false);
			if (!bResult) break;
		}
		this._iLastPickedIndex= indexes[indexes.length - 1];
		this.raiseSelectionChangeEvent();
	},
*/
	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);
		}
		this.raiseSelectionChangeEvent();
	},

	raiseSelectionChangeEvent : function() {
		this.updateSelectedItemsUI(this._aSelectedRows.length, this._iTotalOnPage);
	},


	// 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) {
		if (oIcon.tagName != "IMG") return;
		var 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 {
			this.collapseRow(oRow);
		}
  },


	onRecordMasterDetailComplete : function(html, element) {
		element.hideProgress();
		var newRow= element.expandRowHtml(element._expandedRow, html);
		if (newRow != null) {
			$create(FM.DataGrid, {}, null, null, newRow.cells[1].firstChild);
		}

	},

	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= "4px";
		oTD.colSpan= oTr.cells.length - colspan;
		oTD.innerHTML= html;
		//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) {
		if (oIcon.tagName != "IMG") return;
		var 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.LoadRecordPreview(this.tableName, this.viewName, keyValue, this.onRecordPreviewComplete, this.onServiceFailed, this);
		} else {
			this.collapseRow(oRow);
		}
  },
  onRecordPreviewComplete : function(html, element) {
		element.hideProgress();
		element.expandRowHtml(element._expandedRow, html, true);
	},

	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() {
		//trace('x');
		if (!this._gridBodyContainer) return;
		var o= this.get_element();
		if (o.className != "scrollTable") return;

		var head= o.firstChild;
		var topHeight= head.offsetHeight;
		if (head.id == "_gZoneContainer") { head= head.nextSibling; topHeight+= head.offsetHeight; }
		this.divHeader= head;
		this.panelsHeight= topHeight + o.lastChild.offsetHeight;
		this.resizeScrollTable(o);
		head.syncTo= this._gridBodyContainer.uniqueID;
		head.syncDirection= "horizontal";
		$addHandlers(o, { 'resize' : this.resizeScrollTable }, this);
		//trace('dx');
	},

	resizeScrollTable : function() {
		var o= this.get_element();
		var w= o.clientWidth; var h= o.clientHeight;
		if (o.storedWidth == w && o.storedHeight == h) return;
		o.storedWidth= w; o.storedHeight= h;

		var head= this.divHeader;
		var body= this._gridBodyContainer;
		var headTable= head.firstChild;
		var bodyTable= body.firstChild;
		body.style.height= Math.max(0, h - this.panelsHeight);

		var hasVScroll= body.scrollHeight > body.offsetHeight;
		if (hasVScroll != head.hasVScroll) {
			//window.status= hasVScroll;

			var headCells= headTable.rows[0].cells;
			var _headCols= $get('_headCols', headTable);
			var last= _headCols.childNodes[_headCols.childNodes.length - 3];
			//var w= last.offsetWidth;
			if (hasVScroll) {
				if (last.originalWidth == null) last.originalWidth= parseInt(last.width);
				last.width= last.originalWidth + 16;
			} else if (last.originalWidth != null) {
				last.width= last.originalWidth;
			}

		}
		head.hasVScroll= hasVScroll;

		var scrollBarWidth= body.offsetWidth - body.clientWidth;
		// set width of the table in the head
		headTable.style.width = Math.max(0, Math.max(bodyTable.offsetWidth + scrollBarWidth, o.clientWidth));
		/*
		// go through each cell in the head and resize
		var headCells= headTable.rows[0].cells;
		var bodyCells= bodyTable.rows[0].cells;

		for (var i = 0; i < bodyCells.length; i++)
			headCells[i].style.width = bodyCells[i].offsetWidth;
			*/
	},


	_onmouseover : function(e) {
		var oRow= this.GetParentRow(e.target);
		if (oRow && oRow.oid) oRow.style.backgroundColor= "#FEFDE0";
	},

	_onmouseout : function(e) {
		var oRow= this.GetParentRow(e.target);
		if (oRow && oRow.oid) oRow.style.backgroundColor= "";
	},
	
	// 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();
		}
	},
	
	ExportToExcel : function() {
		var iResult= this.determineExportPrintPaging("export");
		if (iResult) {
			switch (iResult.result) {
			case RESULT_CANCEL: return;
			case RESULT_CURRENTPAGE:
			case RESULT_ALLPAGES:
				var oForm= this.createExportPrintForm(iResult.result, true);
				oForm.action= fmDataViewerPath + "Print/Export_data.aspx";
				oForm.target= "gridExportFrame";
				break;
			}
			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") this._searchSelector.setListHtml(div.innerHTML);
	},

	EndFunc : function() {
		alert('Refresh');
	}

}

window.sortOverImage= "url(" + fmCommonPath + "Images/Grid2/grid_BarBkOn.gif)";
/*
FM.DataGrid.descriptor= {
  properties: [   {name: 'tableName',	type: String},
                  {name: 'viewName',	type: String},
                  {name: 'selectOnStart', type: Boolean} ]
}
*/
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');

//	/	/	/	/	/	 POPUP MENU /	/	/	/	/	/	/	/	/	/	/
//

FM.PopupMenu= function(element, grid) {
	// Properties
	this.parentGrid= grid;

	this._oPop= null;

	FM.PopupMenu.initializeBase(this, [element]);
}

FM.PopupMenu.prototype= {

	initialize : function() {
	 	FM.PopupMenu.callBaseMethod(this, 'initialize');

	},

	dispose: function() {
		if (this._oPop != null) this._oPop.hide();
		this._oPop= null;
		FM.PopupMenu.callBaseMethod(this, 'dispose');
	},
	

	Show : function(e, r) {
		if (this.parentGrid.AllowSelect && !IsNull(r) && !IsNull(r.firstChild) && r.firstChild.className != "gridPreview") {
			this.parentGrid.UnselectRecords(r);
		}
		this.popupToggle(IsNull(r) || IsNull(r.getAttribute('oid')));
		this._oPop= window.openPopup();
		
		var oS= this._oPop.document.createStyleSheet();
		oS.addRule("div.item","cursor:hand;padding:3px;padding-left:15px;");
		oS.addRule("HR","margin-bottom:1px;cursor:default;");
		this._oPop.show(0, 0, 0, 0);
		var oBody= this._oPop.document.body;
		oBody.innerHTML= this.get_element().outerHTML;
		var _iPopH, _iPopW;

		with (oBody.firstChild) {
			style.display= "";
			onmouseover= this.popGlow;
			onmouseout= this.popGlow;
			_iPopH= offsetHeight;
			_iPopW= offsetWidth + 10;
		}

		this._oPop.document.parentPopup= this._oPop;
		this._oPop.document.parentGrid= this.parentGrid;
		this._oPop.document.parentRow= r;
		this._oPop.document.close= function a() { this.parentPopup.hide(); };

		this._oPop.show(e.screenX - 1, e.screenY - 5, _iPopW, _iPopH);
	},

	popGlow : function(e) {
		var o= this.document.parentWindow.event.srcElement;

		if (o.tagName == "NOBR" || o.tagName == "SPAN") o= o.parentNode;
		if ((o.tagName == "HR") || (o.id == "_PopupMenu")) return;

		with (o.runtimeStyle) {
			if (color == "highlighttext") {
				color= backgroundColor= "";
			} else {
				color= "highlighttext";
				backgroundColor= "highlight";
			}
		}
	},
	
	popupToggle : function(b) {
		var o= this.get_element().all.tags("div");

		if (o.length > 1 && o[0].disabled != b) {
			o[0].disabled= o[1].disabled= b;
			this._oPop= null;
		}
	}
	
}

FM.PopupMenu.inheritsFrom(Sys.UI.Control);
FM.PopupMenu.registerClass('FM.PopupMenu', Sys.UI.Control);

// END
Sys.Application.notifyScriptLoaded();