/// <reference path="jquery-1.2.6.js" />
/// <reference path="MicrosoftAjax.js" />
/// <reference path="SysControls.jQuery.js" />

// Java script for grid and matrix controls
// ----------------------------------------

//Clipboard copy and paste
function SysGridCopyClipboard(gridID) {
	SysCopyClipboard(gridID, 1, 3, 2, 0);
}

function SysMatrixCopyClipboard(matrixID)
{
	SysCopyClipboard(matrixID, 2, 2, 1, 1);
}

function SysCopyClipboard(ID, headerRowCount, footerRowCount, headerColCount, footerColCount) {
	if (!window.clipboardData) {
		return; 	//Only IE supports copy and paste to and from the clipboard
	}

	var g = SysGetElement(ID);
	var s = '';
	for (row=headerRowCount; row<g.rows.length-footerRowCount; row++) {
		var tr = g.rows[row];
		if (jQuery(tr).is(":not(:hidden)")) {
			for (cell=headerColCount; cell<tr.cells.length-footerColCount; cell++) {
				var td = tr.cells[cell];
				if (jQuery(td).is(":visible")) {
					if (td != null) {
						var el = td.firstChild;
					}
					if (el!=null) {
						var bRef = false;
						if (el.type == "hidden") {
							bRef = true;
							el = el.nextSibling;
						}
						if (el != null) {
							var v = el.value;
							if (v == null) {
								v = SysGetInnerText(el);
								if (v != null) {
									if (bRef) {
										s += v.substring(0, v.indexOf(" - "));
									}
									else {
										s += v;
									}
								}
							}
							else {
								s += v;
							}
							s += '\t';
						}
					}
				}
			}
			s += '\n';
		}
	}
	window.clipboardData.setData("Text", s);
}

function SysGridPasteClipboard(gridID)
{
	SysPasteClipboard(gridID, 1, 3, 2, 0);
}

function SysMatrixPasteClipboard(matrixID)
{
	SysPasteClipboard(matrixID, 2, 2, 1, 1);
}

function SysPasteClipboard(ID, headerRowCount, footerRowCount, headerColCount, footerColCount) {
	if (!window.clipboardData) {
		return; 	//Only IE supports copy and paste to and from the clipboard
	}
	
	var ch = window.clipboardData.getData("Text");
	if (ch == null) return;
	var lines = ch.split('\n');
	var lineCount = lines.length;
	if (lines[lineCount-1] == "") lineCount--;
	var g = SysGetElement(ID);
	var row = -1;
	for(j=0; j < lineCount; j++)
	{
		var tr;
		do {
			row += 1;
			if (g.rows.length - footerRowCount <= row + headerRowCount) {
				var el = SysGetElement(ID + "_addnew");
				if (el != null) {
					SysGridAddRows(el, ID, false);
				}
			}
			tr = null;
			if (g.rows.length - footerRowCount > row + headerRowCount) {
				tr = g.rows[row + headerRowCount];
			}
		} while (jQuery(tr).is(":hidden"));

		if (tr != null) {
			var values = lines[j].split('\t');
			var col = -1;
			for(i=0; i < values.length; i++)
			{
				var td;
				do {
					col += 1;
					td = null;
					if (tr.cells.length - footerColCount > col + headerColCount) {
						td = tr.cells[col + headerColCount];
					}
				} while (td != null && jQuery(td).is(":hidden"));

				if (td != null) {
					var el = td.firstChild;
					if (el!=null) {
						while (el != null && el.type == "hidden") {
							el = el.nextSibling;
						}
						if (!el.disabled && !el.readOnly && el.type != "button" && el.value != values[i]) {
							try
							{
								el.value = values[i];
								$(el).change();  //el.fireEvent('onchange');
							}
							catch(ex) {}
						}
					}
				}
			}
		}
	}
	SysGridCheckPaging(ID);
}

//	Grid functions
function SysGridSwitchColor(row)
{
	if (row != null)
	{
		var item = row.cells[0];
		var color;
		if (window.getComputedStyle) 
			color = window.getComputedStyle(item, 'background-color');		
		else
			color = item.currentStyle.backgroundColor;

		$(item).css({ 'background-color': color, 'color': color });
			
		//item.runtimeStyle.backgroundColor = item.currentStyle.color;
		//item.runtimeStyle.color = color;
	}
}

var sysGridSelectedRow;
function SysGridFirstRow(gridID) {
	var g = SysGetElement(gridID);
	var r = g.rows[1];
	return r;
}

function SysGridLastRow(gridID) {
	var g = SysGetElement(gridID);
	var r = g.rows[g.rows.length-3];
	return r;
}

function SysGridSelectUp(gridID) {
	SysGridSwitchColor(sysGridSelectedRow);
	if (sysGridSelectedRow == null)
		sysGridSelectedRow = SysGridLastRow(gridID);
	else
	{
		var r = sysGridSelectedRow.previousSibling;
		while(r != null && r.getAttribute('rowid') != null && r.style.display == "none")
			r = r.previousSibling;
		if (r.getAttribute('rowid') != null)
			sysGridSelectedRow = r;
	}
	SysGridSwitchColor(sysGridSelectedRow);
}

function SysGridSelectDown(gridID) {
	SysGridSwitchColor(sysGridSelectedRow);
	if (sysGridSelectedRow == null)
		sysGridSelectedRow = SysGridFirstRow(gridID);
	else
	{
		var r = sysGridSelectedRow.nextSibling;
		while(r != null && r.getAttribute('rowid') != null && r.style.display == "none")
			r = r.nextSibling;
		if (r.getAttribute('rowid') != null)
			sysGridSelectedRow = r;
	}
	SysGridSwitchColor(sysGridSelectedRow);
}

function SysGridSelectDelete(gridID, func) {
	if (sysGridSelectedRow == null)
		return;
	var rid = sysGridSelectedRow.getAttribute('rowid');
	SysGridDelete(gridID, rid, func);

	var r = sysGridSelectedRow.previousSibling;
	while(r != null && r.getAttribute('rowid') != null && r.style.display == "none")
		r = r.previousSibling;
	if (r.getAttribute('rowid') != null)
	{
		sysGridSelectedRow = r;
		SysGridSwitchColor(sysGridSelectedRow); 
	}
	else
	{
		sysGridSelectedRow = SysGridFirstRow(gridID);
		r = sysGridSelectedRow.nextSibling;
		while(r != null && r.getAttribute('rowid') != null && r.style.display == "none")
						r = r.nextSibling;
		if (r.getAttribute('rowid') != null)
		{
			sysGridSelectedRow = r;
			SysGridSwitchColor(sysGridSelectedRow); 
		}
		else{
			sysGridSelectedRow = null;
			SysGridSwitchColor(r.previousSibling); 
		}
	}
}

var sysIsGridDirty = false;
function SysIsGridDirty() {
	/// <summary>Returns the value of [sysIsGridDirty]</summary>

	return sysIsGridDirty;
}

function SysGridKeyDown(e) {
	/// <summary>Grid control keyDown event handler</summary>
	
	var el = SysSrcElement(e);
	var sel = new SysSelection(el);
	if (SysIsCancelBubble(e)) return;

	var hdl = new SysHandleKey(e);
	if (hdl.HandleEnter()) return;
	
	if (hdl.IsLeftKey()) {
		var t = sel.GetSelection();
		if (t.length > 0) return;

		var pos = sel.GetCaretPosition();
		if (pos == 0) {
			var i;
			var f = document.forms[0];
			var el2 = null;
			for (i = 0; i < f.elements.length; i++) {
				if (f.elements[i] == el) {
					el2 = f.elements[i];
					break;
				}
			}
			if (el2 != null && i > 0) {
				i--;
				el2 = f.elements[i];
				while (el2 != null) {
					if (el2.tabIndex >= 0 && !el2.disabled) {
						try {
							el2.focus();
							if (el2 == document.activeElement) {
								return true;
							}
						}
						catch (ex) { }
					}
					i--;
					el2 = f.elements[i];
				}
			}
		}
	}
	else if (hdl.IsRightKey()) {
		var pos = sel.GetCaretPosition();
		if (pos == el.value.length) {
			hdl.HandleEnter(true);
		}
	}
}

// [choo225643]: compare with EOL again
function SysGridKeyUp(e) {
	/// <summary>Grid control keyUp event handler</summary>
	
	if (SysIsCancelBubble(e)) return;
	var me = SysSrcElement(e);
	if (me.tagName == 'SELECT') return;

	var hdl = new SysHandleKey(e);
	
	if (hdl.IsUpKey() || hdl.IsDownKey()) {
		var td = (me.tagName == 'TD') ? me : me.parentNode;
		if (td.tagName != 'TD') td = td.parentNode;
		var tr = td.parentNode;
		var tbody = tr.parentNode;
		var table = tbody.parentNode;
		var rIndex = tr.rowIndex;

		if (hdl.IsUpKey())
		{
			var bContinue = true;
			while (bContinue) {
				rIndex--;
				if (rIndex < 0) return;
				var tr = table.rows[rIndex];
				bContinue = (tr.style.display == "none");
			}
		}
		else if (hdl.IsDownKey())
		{
			var bContinue = true;
			while (bContinue) {
				rIndex++;
				if (rIndex >= table.rows.length) return;
				var tr = table.rows[rIndex];
				bContinue = (tr.style.display == "none");
			}
		}
		
		var tr = table.rows[rIndex];
		var td = tr.cells[(td.cellIndex < tr.cells.length) ? td.cellIndex : tr.cells.length - 1];
		if (td!=null)
		{
			var el = td.firstChild;
			if ((el != null) && (el.tagName == 'NOBR')) el = el.firstChild;
			if ((tr.className==''||tr.className.substr(0,4)=='Data'||tr.className=='Selected')&&!SysGridFocusEl(el))
				td.setActive();
		}
		return true;
	}
	return false;
}

function SysCellIndex(me)
{
	var td = me.parentNode;
	var tr = td.parentNode;
	var iCell;
	for (iCell = 0; iCell < tr.cells.length; iCell++) {
		var ctrCell = tr.cells[iCell];
		if (ctrCell != null) {
			var elem = ctrCell.firstChild;
			if (elem != null) {
				if (me.name!=null && elem.name!=null && me.name==elem.name)
					return iCell;
				if (me.id!=null && elem.id!=null && me.id==elem.id)
					return iCell;
			}
		}
	}
}

// [choo225643]: compare with EOL function
// [choo225643]: bastardized english... 
function SysGridTotalize(grid, field)
{
	var table = SysGetElement(grid);
	var st = SysGetElement(grid + '_SubTotal_' + field);
	var t = SysGetElement(grid + '_Total_' + field);
	if (t == null) return;

	var cellIndex;
	var value = 0;
	var tr = table.rows[1];
	
	for (var i = 0; i < tr.cells.length; i++)
	{
		var td = tr.cells[i];
		var el = td.firstChild;
		if (el != null && el.id != null) {
			var pos = el.id.indexOf('_');
			if (pos >= 0 && el.id.substring(pos+1) == field) {
				cellIndex = i;
				break;
			}
		}
	}
	
	for (var i = 1; i < table.rows.length - 1; i++)
	{
		var ctr = table.rows[i];
		if (ctr.cells.length > cellIndex && ctr.style.display!="none")
		{
			var ctd = ctr.cells[cellIndex];
			var el = ctd.firstChild;
			if (el != null)
			{
				var v = el.value;
				if (v == null)
					v = SysGetInnerText(el);
				v = SysUnFormatNumber(v);
				if (!isNaN(v))
					value += v;
			}
		}
	}
	
	if (st != null && t != null) {
		var newSubTotal = value;
		var newTotal = value - SysUnFormatNumber(st.value) + SysUnFormatNumber(t.value);
		if (ctr.cells.length >= cellIndex)
		{
			var ctd = ctr.cells[cellIndex - 1];
			SysSetInnerText(ctd, SysFormatNumber(newTotal));
			//ctd.innerText = SysFormatNumber(newTotal);
		}
	}
}

var sysGridLastWidth;
function SysGridHandleWidth(ctlId, noHeight) {	
	var dd = SysGetElement(ctlId + "_DataDiv");
	if (sysGridLastWidth == dd.offsetWidth) return;
	sysGridLastWidth = dd.offsetWidth;

	var ft = SysGetElement(ctlId);
	var tt = SysGetElement(ctlId + '_Header');
	if (ft == null || tt == null || ft.rows.length == 0 || tt.rows.length == 0) return;
	var fr = ft.rows(ft.rows.length-1);
	var tr = tt.rows(tt.rows.length - 1);
	$(tt).css('width', '10px');
	//tt.runtimeStyle.width = '10px';
	var i;
	for (i=0; i < fr.cells.length; i++)
	{
		var fd = fr.cells(i);
		var td = tr.cells(i);
		$(td).css('width', fd.offsetWidth); 
		//td.runtimeStyle.width = fd.offsetWidth;
	}
	tt = SysGetElement(ctlId + "_GrdFooter");
	if (tt != null)
	{
		if (ft == null || tt == null || ft.rows.length == 0 || tt.rows.length == 0)
			return;
		var fr = ft.rows(ft.rows.length-1);
		var tr = tt.rows(0);
		$(tt).css('width', '10px'); 
		//tt.runtimeStyle.width = '10px';
		for (i=0; i < fr.cells.length; i++)
		{
			var fd = fr.cells(i);
			var td = tr.cells(i);
			if (fd != null && td != null)
				$(td).css('width', fd.offsetWidth); 
				//td.runtimeStyle.width = fd.offsetWidth;
		}
	}
	
	SysListScroll(ctlId);
}

// [choo225643]: EOL: SysGridPaging(gridID + '_PageCtl', '-1'); instead of '0'
function SysGridCheckPaging(gridID) {
	var grid = SysGetElement(gridID);
	var pagesize = SysGet(gridID + '_PageSize');
	if (pagesize != null && pagesize != -1 && grid.rows.length - 4 > pagesize) {
		SysGridPaging(gridID + '_PageCtl', '0');
	}
}

//function SysGridAddRows2(tr, gridID, checkpagesize, setfocus) {
//	var table = tr.closest("table");
//	var i = tr.attr("rowIndex");
//	var lastID = new Number(SysGet(gridID + "_LastID")) + 1;
//	SysSet(gridID + "_LastID", lastID);
//	var rowCount = new Number(SysGet(gridID + "_Rows")) + 1;
//	SysSet(gridID + "_Rows", rowCount);
//	var rowIDs = SysGet(gridID + "_RowIDs");
//	if (rowIDs == null || rowIDs == "") {
//		SysSet(gridID + "_RowIDs", rowIDs + ",r" + lastID);
//	}
//	else {
//		SysSet(gridID + "_RowIDs", rowIDs + ",r" + lastID);
//	}
//	SysGridAllRows(table, lastID, tr, rowCount, checkpagesize);

//	if (setfocus == undefined) {
//		setfocus = true;
//	}
//	if (setfocus) {
//		var row = table.attr("rows")[i];
//		for (var c = 0; c < row.cells.length; c++) {
//			var td = row.cells[c];
//			var el = td.firstChild;
//			if (SysGridFocusEl(el)) return;
//		}
//	}
//}

//function SysGridAddRows(me, gridID, checkpagesize, setfocus) {
//	if (me == null) return;
//	sysIsGridDirty = true;

//	SysGridAddRows2($(me).closest("tr"), gridID, checkpagesize, setfocus)
//}

function SysGridAddRows(me, gridID, checkpagesize) {
	if (me == null) return;
	sysIsGridDirty = true;
	var td = me.parentNode;
	var tr = td.parentNode;
	var tbody = tr.parentNode;
	var table = tbody.parentNode;
	var i = tr.rowIndex;
	var lastID = new Number(SysGet(gridID + '_LastID')) + 1;
	SysSet(gridID + '_LastID', lastID);
	var rowCount = new Number(SysGet(gridID + '_Rows')) + 1;
	SysSet(gridID + '_Rows', rowCount);
	var rowIDs = SysGet(gridID + '_RowIDs');
	if (rowIDs==null || rowIDs=='')
		SysSet(gridID + '_RowIDs', rowIDs + ",r" + lastID);
	else
		SysSet(gridID + '_RowIDs', rowIDs + ",r" + lastID);
	
	SysGridAllRows(table, lastID, tr, rowCount, checkpagesize)
	var tr = table.rows[i];
	for (var c=0;c<tr.cells.length;c++)
	{
		var td = tr.cells[c];
		var el = td.firstChild;
		if (SysGridFocusEl(el))
			return;
	}
}

function SysGridFocusEl(el) {
	while(el!=null)
	{
		if (el.tabIndex >= 0)
		{
			try
			{
				el.focus();
				el.setActive();
				if (el == document.activeElement)
					return true;
			}
			catch(ex){}
		}
		el = el.nextSibling;
	}
	return false;
}

function SysInsertRow(table,tr) {
	var row = document.createElement("TR");
	if (tr==null)
		table.insertBefore(row);
	else
	{
		var tab = tr.parentElement;
		tab.insertBefore(row,tr);
	}
	return row;
}

function SysInsertCell(row,td) {
	var cell = document.createElement("TD");
	row.appendChild(cell);
	if (td==null)
		row.insertBefore(cell);
	else
		row.insertBefore(cell,td);
	return cell;
}

function SysGridAddCell(row, html, rowSpan, colSpan, noWrap, rowID, copy, rows, hidden, className, rowCount) {
	SysMatrixAddCell(row, html, rowSpan, colSpan, noWrap, rowID, copy, rows, hidden, className, rowCount, null);
}

// [choo225643]: there's an additional check to ensure that the rows to copy are not hidden in the EOL code. 
function SysGridCopy(cT, rows, copy) {
    var t = cT.parentNode.parentNode.parentNode;
    var rF = t.rows[cT.parentNode.rowIndex - rows];
    while (jQuery(rF).is(":hidden")) {
        rows += 1;
        rF = t.rows[cT.parentNode.rowIndex - rows];
    }
    
    var rowidF = SysGridRowID(rF);
    var rowidT = SysGridRowID(cT);
    for (var i = 0; i < cT.childNodes.length; i++) {
        var iT = cT.childNodes[i];
        if (iT.id != null) {
            var id = iT.id.replace(rowidT, rowidF);
            var iF = SysGetElement(id);
            if (iF != null && (iT.tagName == "INPUT" || iT.tagName == "SELECT")) {
                if (iF.value != null && copy == "1") {
                    iT.value = iF.value;
                }
                iT.disabled = iF.disabled;
                SysSetReadOnly(iT, iF.readOnly);
            }
        }
    }
}

//function SysGridCopy(cT,rows,copy)
//{
//	var t = cT.parentNode.parentNode.parentNode;
//	var rF = t.rows[cT.parentNode.rowIndex-rows];
//	for (var i=0; i < cT.childNodes.length; i++)
//	{
//		var iT = cT.childNodes[i];
//		if (iT.id != null) {
//			var id = iT.id.replace(cT.parentNode.rowid, rF.rowid);
//			var iF = SysGetElement(id);
//			if (iF != null && (iT.tagName == "INPUT" || iT.tagName == "SELECT"))
//			{
//				if (iF.value != null && copy=='1')
//					iT.value = iF.value;
//				iT.disabled = iF.disabled;
//				SysSetReadOnly(iT, iF.readOnly);
//			}
//		}
//	}
//}

function SysGridShowDelete(rowid, show)
{
	var el = SysGetElement(rowid + '_Del');
	if (el != null) {
		if (show) 
			$(el).show(); //el.style.display = "block";
		else 
			$(el).hide(); //el.style.display = "none";
	}
}

function SysGridDelete(gridid, me, func) {
	sysIsGridDirty = true;
	SysSet(me, 'on');
	var el = SysGetElement(me);
	var tr = el.parentNode.parentNode;
	$(tr).hide();
	//tr.style.display = "none";
	
	for (var c=0;c<tr.cells.length;c++)	{
		var td = tr.cells[c];
		for (var i=0; i < td.childNodes.length; i++) {
			var el = td.childNodes[i];
			if (el != null && el.tabIndex != null) {
				el.tabIndex = -1;
				if (el.id != null && el.id.length > 0 && tr.rowid != null) {
					var field = el.id.substring(tr.rowid.length + 1);
					SysGridTotalize(gridid, field);
				}
				if (el.tagName == "SELECT") {
					$(el).hide(); //el.style.display = "none";
				}
				else {
					for (var j=0; j < el.childNodes.length; j++) {
						var el2 = el.childNodes[j];
						if (el2 != null && el2.style != null) {
							$(el2).hide(); //el2.style.display = "none";
						}
					}
				}
			}
		}
	}
	
	if (func != null) {
		var f = new Function('tr', 'return ' + func + '(tr)');
		f(tr);
	}

	var table = tr.parentNode.parentNode;
	for (var r=tr.rowIndex-1; r>0; r--)	{
		if (SysGridRowSetFocus(table.rows[r])) return;
	}
	
	for (var r=tr.rowIndex+1; r<(table.rows.length-2); r++) {
		if (SysGridRowSetFocus(table.rows[r])) return;
	}
	
	var fa = SysGetElement(gridid + '_addnew');
	if (fa != null) {
		fa.focus();
	}
}

function SysGridRowSetFocus(tr) {
	if (jQuery(tr).is(":not(:hidden)")) {
		for (var c=0;c<tr.cells.length;c++) {
			var td = tr.cells[c];
			var el = td.firstChild;
			if (SysGridFocusEl(el))	return true;
		}
	}
}

function SysGridSetFocus(grd) {
	var t = SysGetElement(grd);
	if (t!=null) {
		for (var r=1; r< t.rows.length-2; r++)	{
			if (SysGridRowSetFocus(t.rows[r])) return;
		}
	}
}

function SysGridOnFocus(el) {
	/// <summary>Grid onFocus event handler</summary>
	/// <param name="el" type="Object">The element</param>

	if (el.parentNode.tagName != "TD")
		el = el.parentNode;
		
	if (el.parentNode.tagName == "TD") {
		try {
			SysSet('BCField', el.id);
			SysGridHighLight(el.parentNode, true);
		}
		catch (ex) { }
		// highlight content
		SysSelect(el);
	}
}

function SysGridOnBlur(el) {
	/// <summary>Grid onBlur event handler</summary>
	/// <param name="el" type="Object">The element</param>

	//BR26.614.157 (Start)      	
	SysChangeOnBlur(el);

	if (el.parentNode.tagName != "TD")
		el = el.parentNode;

	if (el.parentNode.tagName == "TD") {
		try {
			SysGridHighLight(el.parentNode, false);
		}
		catch (ex) { }
	}
	//SysChangeOnBlur(el);
	//BR26.614.157 (End)	
}

function SysGridHighLight(td, bHighLight) {
	/// <summary>Adds/ removes highlighting CSS class for the element specified</summary>
	/// <param name="td" type="Object">The element to add/ remove highlight</param>
	/// <param name="bHighLight" type="Boolean">True to add highlight, false to remove</param>
	
	if (bHighLight) 
		$(td).addClass("selected");	
	else 
		$(td).removeClass("selected");
}

function SysGridGetElementID(rowid, ctl) {
	/// <summary>Returns the element id for the row in the grid specified</summary>
	/// <param name="rowid" type="String">The [rowid] in the grid</param>
	/// <param name="ctl" type="String">The grid</param>

	if (!isNaN(rowid)) rowid = "r" + rowid;
	return rowid + '_' + ctl;
}

function SysGridGetElement(rowid, ctl) {
	/// <summary>Returns the element for the row in the grid specified</summary>
	/// <param name="rowid" type="String">The [rowid] in the grid</param>
	/// <param name="ctl" type="String">The grid</param>

	return SysGetElement(SysGridGetElementID(rowid, ctl));
}

function SysGridGet(rowid, ctl) {
	/// <summary>Returns the element value for the row in the grid specified</summary>
	/// <param name="rowid" type="String">The [rowid] in the grid</param>
	/// <param name="ctl" type="String">The grid</param>

	var c = SysGridGetElement(rowid, ctl);
	if (c != null)
		return c.value;
}

function SysGridGetKey(rowid)
{
	return SysGridGet(rowid, 'K');
}

function SysGridGetNumber(rowid, ctl)
{
	return SysUnFormatNumber(SysGridGet(rowid, ctl));
}

function SysGridSet(rowid, ctl, value)
{
	var c = SysGridGetElement(rowid, ctl);
	if (c != null)
		c.value = value;
}

function SysGridSetNumber(rowid, ctl, value, prec)
{
	SysGridSet(rowid, ctl, SysFormatNumber(value, prec));
}

// Matrix functions
function SysMatrixSetGrandTotal(me)
{
	var td = me.parentNode;
	var tr = td.parentNode;
	var tbody = tr.parentNode;
	var table = tbody.parentNode;
	var cellIndex = tr.cells.length - 1;
	var value = 0;
	
	for (var i = 0; i < table.rows.length - 1; i++)	{
		var ctr = table.rows[i];
		if (ctr.cells.length > cellIndex) {
			var ctd = ctr.cells[cellIndex];
			var v = SysUnFormatNumber(SysGetInnerText(ctd)); //ctd.innerText);
			if (!isNaN(v))
				value += v;
		}
	}

	var ctr = table.rows[table.rows.length - 1];
	if (ctr.cells.length > cellIndex) {
		var ctd = ctr.cells[cellIndex];
		SysSetInnerText(ctd, SysFormatNumber(value));
		//ctd.innerText = SysFormatNumber(value);
	}
}

function SysMatrixTotalizeColumn(me)
{
	var td = me.parentNode;
	var tr = td.parentNode;
	var tbody = tr.parentNode;
	var table = tbody.parentNode;
	var cellIndex = SysCellIndex(me);
	var value = 0;
	for (var i = 0; i < table.rows.length; i++)
	{
		var ctr = table.rows[i];
		if (ctr.cells.length > cellIndex && ctr.style.display!="none")
		{
			var ctd = ctr.cells[cellIndex];
			var el = ctd.firstChild;
			if (el != null)
			{
				var v = el.value;
				if (v == null)
					v = SysGetInnerText(el);
				v = SysUnFormatNumber(v);
				if (!isNaN(v))
					value += v;
			}
		}
	}
	if (ctr.cells.length >= cellIndex)
	{
		var ctd = ctr.cells[cellIndex];
		SysSetInnerText(ctd, SysFormatNumber(value));
		//ctd.innerText = SysFormatNumber(value);
	}
}

function SysMatrixTotalize(me)
{
	var td = me.parentNode;
	var tr = td.parentNode;
	var value = 0;
	var iCell;
	for (iCell = 0; iCell < tr.cells.length; iCell++)
	{
		var ctrCell = tr.cells[iCell];
		if (ctrCell != null && ctrCell.cell == '1')
		{
			var el = ctrCell.firstChild;
			if (el != null)
			{
				var v = SysUnFormatNumber(el.value);
				if (!isNaN(v))
					value += v;
			}
		}
	}
	var ctrCell = tr.cells[tr.cells.length - 1];
	SysSetInnerText(ctrCell, SysFormatNumber(value));
	//ctrCell.innerText = SysFormatNumber(value);
	
	SysMatrixTotalizeColumn(me);
	SysMatrixSetGrandTotal(me);
}

function SysMatrixAddCell(row, html, rowSpan, colSpan, noWrap, rowID, copy, rows, hidden, className, rowCount, cell)
{
	var c = SysInsertCell(row);
	if (rowCount!=null)
	{
		var re1 = /r0wNR/g;
		html = html.replace(re1, rowCount);
	}
	var re = /r0w/g;
	html = html.replace(re, rowID);

	c.innerHTML = html;
	c.colSpan = colSpan;
	c.rowSpan = rowSpan;
	c.noWrap = noWrap == 1;
	if (className!=null)
		c.className = className;
	SysGridCopy(c,rows,copy);
	if (hidden=='1')
		c.runtimeStyle.display = 'none';
	if (cell == '1')
		c.cell = "1";
}

// List View
// ---------
function SysCheckList(listID, columnId)
{
	var f = new Function("return lvcCheckChecked" + listID + "_" + columnId + "()");
	return f();
}

function SysListViewCBXChecked(id)
{
	var inps  = document.getElementsByName(id);
	if (inps == null || inps.length == 0)
		return false;
	for (i=0; i < inps.length; i++) {
		var e = inps[i];
		if (e.type == 'checkbox' && e.checked)
			return true;
	}
	return false;
}

function SysListKD(e) {
	try {
		var hdl = new SysHandleKey(e);
		if (hdl.IsPageUpKey())
			ListNext();
		else if (hdl.IsPageDownKey())
			ListPrev();
		
//		if (event.altKey || event.alt)
//		{
//			if (SysGetKey(e) == 34)
//				ListNext();
//			else if(SysGetKey(e) == 33)
//				ListPrev();
//		}
	}
	catch (ex) {}
}
function SysListAddKD(e) {
	SysAttachEvent(document, "onkeydown", function() { SysListKD(e) });
}
function SysListSort(ctl, column, asc) {
	SysSet(ctl + '_sortcolumn', column);
	SysSet(ctl + '_sortorder', asc ? 1 : 0);
}

function SysListToggle(cb, prefix) {
	/// <summary>Handler for list header checkbox Click events. Checks/ unchecks the checkboxes in the list if necessary</summary>
	/// <param name="cb" type="Object">The element that triggered the event</param>
	/// <param name="prefix" type="String">The prefix to search</param>
	
	if (cb.checked)
		$('input:checkbox:enabled:not(:checked)[name*="' + prefix + '"]').attr('checked', true);
	else
		$('input:checkbox:enabled:checked[name*="' + prefix + '"]').attr('checked', false);
}

function SysListCheck(cb, prefix, headerCbId) {
	/// <summary>Handler for list checkbox Click events. Checks/ unchecks the checkbox in the list header if necessary</summary>
	/// <param name="cb" type="Object">The element that triggered the event</param>
	/// <param name="prefix" type="String">The prefix to search</param>
	/// <param name="headerCbId" type="String">The Id of the checkbox in the header</param>
	
	if (cb.checked) {
		if ($('input:checkbox:enabled:not(:checked)[name*="' + prefix + '"]').length == 0) 
			$('input:checkbox[id="' + headerCbId + '"]').attr('checked', true); 
	} else 
		$('input:checkbox[id="' + headerCbId + '"]').attr('checked', false); 
}

//BR 22.937.095
function SysListCheckHeader(prefix, headerCbId) {	
	var el = document.forms[0].elements;
	if (SysGetElement(headerCbId) == null) return false;
	if (el[headerCbId].checked) return;
	var checkALL= true;
	var re = new RegExp(SysReplaceRegEx(prefix), "i")
	var found = false;
	for (i=0; i < el.length; i++) 
	{
		var e = el[i];
		if (e.type == 'checkbox' && e.name.search(re) >= 0 && (!e.disabled)) 
		{
			found = true;
			if (!e.checked)
			{
				checkALL=false;
				break;
			}
		}
	}
	if (found){
		el[headerCbId].checked = (checkALL);	
	}
}

var SysIsBrowser = false; // BR 28.761.319 : Special handling for browser because long text can be v. long
function SysListSetHeight(e, ctlId) {	
	var tb = SysGetElement(ctlId + "_tb");   // document.getElementById(ctlId + "_tb");
	var div = SysGetElement(ctlId + "_div");  //document.getElementById(ctlId + "_div");
	var frm = document.body; //window.frameElement;

	if (tb == null || frm == null || div == null) return;

	if (SysIsBrowser) {
		try {
			var obj = tb;
			// http://www.quirksmode.org/js/findpos.html
			var curleft = curtop = 0;
			if (obj.offsetParent) {
				do {
					curleft += obj.offsetLeft;
					curtop += obj.offsetTop;
				} while (obj = obj.offsetParent);
			}

			tb.style.height = (frm.offsetHeight - curtop - ((tb.offsetWidth > frm.offsetWidth) ? 25 : 10));		

			div.style.width = frm.clientWidth;
			tb.style.width = frm.clientWidth;

			var parentTable = tb.parentNode;
			while ((parentTable != null) && (parentTable.nodeName != 'TABLE')) { parentTable = parentTable.parentNode; }
			if (parentTable) {
				parentTable.style.height = tb.offsetHeight;
				parentTable.style.width = frm.clientWidth;
			}
		}
		catch (ex) { }
	}
	else {
		if (tb.height != '100%') {
			try {
				tb.height = (frm.offsetHeight - tb.offsetTop - 10);
			}
			catch (ex) { }
		}

		try {
			//BR 34.446.727
			//BR 32.377.770
			if (tb.offsetWidth > frm.clientWidth) {
				$(tb).css({ 'width': frm.clientWidth - 4 });
				$(div).css({ 'width': frm.clientWidth - 4 });
			}
			else {
				div.style.width = tb.offsetWidth - 2;
				//div.runtimeStyle.width = tb.offsetWidth - 2;		
			}			
		}
		catch (ex) { }
	}
}

function SysListScroll(ctlId) {
	var dd = $("#" + ctlId + "_DataDiv");
	if (dd.length > 0) {
		$("#" + ctlId + "_HeaderDiv").css({ position: "relative", width: dd.innerWidth() });
		$("#" + ctlId + "_Header").css({ position: "relative", left: -dd.scrollLeft() });
		$("#" + ctlId + "_FooterDiv").width(dd.innerWidth());
	}
}

function SysListCalcTop(par)
{
	var top = 0;
	while (par != null)
	{
		top += par.offsetTop;
		par = par.offsetParent;
	}
	return top;
}

function SysListPin(ctlId) {
	/// <summary>Pins the element specified</summary>
	/// <param name="ctlId" type="String">The ID of the element to pin</param>

	var pin = SysGetElement(ctlId + '_ListViewPin');
	if (pin != null) {
		pin.value = '1';
		SysSubmit();
	}
}

function SysListUnPin(ctlId) {
	/// <summary>Unpins the element specified</summary>
	/// <param name="ctlId" type="String">The ID of the element to unpin</param>
	
	var pin = SysGetElement(ctlId + '_ListViewPin');
	if (pin != null) {
		pin.value = '0';
		SysSubmit();
	}
}

function SysIsPinned(ctlId) {
	/// <summary>Returns true if the element specified is pinned, false otherwise</summary>
	/// <param name="ctlId" type="String">The ID of the element to check</param>
	/// <returns type="Boolean">Returns true if the element specified is pinned, false otherwise</returns>

	var pin = SysGetElement(ctlId + '_ListViewPin');
	if (pin == null) return false;

	return pin.value == '1';
}

var sysListPrevClass;
var sysListPrevRow;
var sysListRuler = true;
function SysListTable(tr)
{
	while (tr != null && tr.tagName != 'TABLE')
		tr = tr.parentNode;
	return tr;
}
function SysListRow(e) {
	var el = SysSrcElement(e);
	while (el != null && el.tagName != 'TR')
		el = el.parentNode;
	return el;
}
function SysListOver(e)
{
	if (!sysListRuler) return;
	var el = SysListRow(e);
	SysListUnSelect(el);
	SysListSelect(el);
}
function SysListSelect(el)
{
	if (el == null ) 
		return;
	if (el.className == 'DataDark' || el.className == 'DataLight')
	{
		sysListPrevRow = el;
		sysListPrevClass = el.className;	
		el.className = "Selected";
	}
}

// [choo225643]: no longer needed?
function SysListOut(e) {
	if (!sysListRuler) return;
	var ev = SysListRow(e);
	
	//SysListUnSelect(e);
}

function SysListUnSelect(el) {
	if (el == null) return;
	if (sysListPrevRow != null)
		sysListPrevRow.className = sysListPrevClass;
	sysListPrevRow = null;
}

function SysListDeActivate(e) {
	var el = SysListRow(e);
	SysListUnSelect(el);
}

function SysListActivate(e, trp) {
	if (trp != null) {
		SysListUnSelect(trp);
		SysListSelect(trp);
	}
	else {
		var tr = SysListRow(e);
		SysListUnSelect(tr);
		SysListSelect(tr);

		var p = SysFileName(document);
		var table = SysListTable(tr);
		//if (p!=null && table!=null) SysSetCookie('Exact.List', p + ':' +  table.id + ':' +  tr.rowIndex)
	}

	/* BR 23.861.721
	var e = SysSrcElement(event);
	if ((e!=null && e.tagName=='TD') || trp!=null)
	{
	if (trp==null)
	e=e.parentElement;
	else
	e=trp;
	var t=e.getElementsByTagName('A');
	for(var i=0;t.length;i++)
	{
	var a=t[i];
	try	{a.focus();	}catch(e){}
	return;
	}
	}
	*/
}

function SysListLoad(e) {
	var c = SysGetCookie('Exact.List');
	if (c == null)
		return;
	var p = SysFileName(document);
	var ss = c.split(':');
	if (ss[0] == p) {
		var i = new Number(ss[2]);
		var t = SysGetElement(ss[1]);
		if (t != null && t.rows.length > i) {
			var tr = t.rows[i];
			if (tr != null)
				SysListActivate(e, tr);
		}
	}
}

function SysListKeyDown(e) {
	/// <summary>List keyDown event</summary>
	/// <param name="e" type="DOMEvent"></param>
		
	try {
		if (SysGridKeyUp(e)) SysCancelBubble(e);
	}
	catch(ex) {}
}

