var isShowValidateMessage = false;
var detect = navigator.userAgent.toLowerCase();
var OS, browser, version, total, thestring;
var corSimCornao = true;
var versaoDebug = false;

function getBrowserInfo() {
	if (checkIt('konqueror')) {
		browser = "Konqueror";
		OS = "Linux";
	} else if (checkIt('safari'))
		browser = "Safari"
	else if (checkIt('omniweb'))
		browser = "OmniWeb"
	else if (checkIt('opera'))
		browser = "Opera"
	else if (checkIt('webtv'))
		browser = "WebTV";
	else if (checkIt('icab'))
		browser = "iCab"
	else if (checkIt('msie'))
		browser = "Internet Explorer"
	else if (!checkIt('compatible')) {
		browser = "Netscape Navigator"
		version = detect.charAt(8);
	} else
		browser = "An unknown browser";

	if (!version)
		version = detect.charAt(place + thestring.length);

	if (!OS) {
		if (checkIt('linux'))
			OS = "Linux";
		else if (checkIt('x11'))
			OS = "Unix";
		else if (checkIt('mac'))
			OS = "Mac"
		else if (checkIt('win'))
			OS = "Windows"
		else
			OS = "an unknown operating system";
	}
}

function isIE() {
	return "Internet Explorer" == browser;
}

function ismaxlength(obj){
	var mlength=obj.getAttribute? parseInt(obj.getAttribute("maxlength"), 10) : ""
	if (obj.getAttribute && obj.value.length>mlength)
	obj.value=obj.value.substring(0,mlength)
}


function getCtxPath() {
	var url = window.location.pathname;
	url = url.substring(1, url.length);
	url = url.substring(0, url.indexOf('/') + 1);
	return '/' + url;
}

function checkIt(string) {
	place = detect.indexOf(string) + 1;
	thestring = string;
	return place;
}

function setEnabledColor(cp) {
	cp.style.background = '#DDD';
}

function setDisabledColor(cp) {
	cp.style.background = '#DDD';
}

function tbEditBlur(obj, key) {
	if (obj == null)
		return;
	var tableName = obj.attributes['tableName'].value;
	var field = obj.attributes['field'].value;
	var tb = $(tableName);

	tb.setKey(key);
	var rec = tb.getRecord();
	eval('rec.' + field + ' = obj.value');
	tb.rewriteHtml();

	if (tb.onBlurFieldEdit != null) {
		tb.onBlurFieldEdit(tb, key, obj);
	}

	tb.setKey(null);
	tb.rewriteHtml();
}

function colClick(obj, colName) {
	while ((obj != null) && (obj.tagName != 'TR'))
		obj = obj.parentNode;
	if (obj == null)
		return;
	var key = obj.attributes['keyValue'].value;
	obj = obj.parentNode.parentNode;
	eval('obj.getRecordByKey(key).'+colName+' = !obj.getRecordByKey(key).'+colName);
	if (obj.eventCellClick != null)
		obj.eventCellClick(key, colName);
}

function showErrorMessage(functionName, transport) {
	  if (!versaoDebug)
		  return;
	var w = window.open();
	w.document.writeln("<html>");
	w.document.writeln("<script language='Javascript'>");
	w.document.writeln("var transport = null;");
	w.document.writeln("function detalha() {");
	w.document.writeln("  var w = window.open();");
	w.document.writeln("  w.document.writeln(transport.responseText);");
	w.document.writeln("  w.document.close();");
	w.document.writeln("}");
	w.document.writeln("</script>");
	w.document.writeln("Remote call error [" + functionName + "]<p>");
	w.document.writeln("Error message :" + transport.statusText + "<p>");
	w.document
			.writeln("<button onclick='javascript:detalha()'>Show full error message</button>");
	w.document.writeln("</html>");
	w.document.close();
	w.transport = transport;
}

function showErrorList(erros) {
	var err = '';
	for (n = 0; n < erros.length; n++) {
		err = err + erros[n] + '\n';
	}
	alert(err);
}

function showValidationError(comp, message) {
	if (isShowValidateMessage)
		return;
	isShowValidateMessage = true;
	if (message != null)
		alert(message);
	$(comp).setFocus();
	isShowValidateMessage = false;
}

function openDialog(url, h, w, params, callbackFunction) {
	w += 32;
	h += 96;
	wleft = (screen.width - w) / 2;
	wtop = (screen.height - h) / 2;
	if (wleft < 0) {
		w = screen.width;
		wleft = 0;
	}
	if (wtop < 0) {
		h = screen.height;
		wtop = 0;
	}
	var opts = "width="
			+ w
			+ ", height="
			+ h
			+ ", "
			+ "left="
			+ wleft
			+ ", top="
			+ wtop
			+ ", location=no, menubar=no, status=no, toolbar=no, scrollbars=no, resizable=no";

	if (params != null)
		url = url + "?" + params;
	window.open(url, "mywindow", opts);
	if (($("auxdiv") != null) && (callbackFunction != null))
		$("auxdiv").callbackFunction = callbackFunction;
}

function getAttribute(componente, nomeAtributo, valorDefault) {
	var attr = $(componente).attributes[nomeAtributo];
	if (attr == undefined)
		return valorDefault;
	else
		return attr.value;
}

function enableFields(value, fieldList) {
	var ct;
	for (ct = 0; ct < fieldList.length; ct++) {
		var cp = $(fieldList[ct]);
		if (cp != undefined) {
			if (cp.getAttribute('sigeaType') == 'search'
					|| cp.getAttribute('sigeaType') == 'edit'
					|| cp.getAttribute('sigeaType') == 'textarea') {
				if (value) {
					cp.removeAttribute('readOnly');
					cp.style.background = '#FFF';
				} else {
					cp.setAttribute('readOnly', '');
					cp.style.background = '#DDD';
				}
			} else {
				cp.disabled = !value;
				cp.readOnly = !value;
			}
		}
	}
}

function onMouseOverTabela(row) {
	var e = Event.element(ev);
	row = e.parentNode;
	row.style.background = '#E9E9E9';
	row.style.cursor = 'hand';
}

function onMouseOutTabela(row) {
	if (row.id == '') {
		row.style.background = '#FFFFFF';
	} else {
		row.style.background = '#FFFFCC';
	}
}

function onMouseClickTable(ev) {
	var e = Event.element(ev);
	if (e.parentNode.attributes["keyValue"] == null
			|| e.parentNode.attributes["keyValue"] == undefined)
		return;
	var key = e.parentNode.attributes["keyValue"].value;
	tableName = e.parentNode.parentNode.parentNode.id;

	var selectedTemp = new Object();
	var tableDef = $(tableName).tableDef;
	if (!$(tableName).enabled) {
		alert('Tabela desabilitada.');
		return;
	}

	var isSelected = $(tableName).currentKey == key;
	if (isSelected)
		$(tableName).setKey(null);
	else
		$(tableName).setKey(key);
}

function getValue(comp) {
	return $(comp).value;
}

function setFocusWithTimeout(compToFocus) {
	setTimeout( function() {
		compToFocus.focus();
		compToFocus.select()
	}, 1);
}

var comps = [];

function dragInit(yInicial) {
	comps = $$('div[moveable="true"]');
	var c;
	for (c = 0; c < comps.length; c++) {
		if (comps[c].style.position != 'absolute') {
			comps[c].style.position = 'absolute';
			comps[c].style.left = 30;
			comps[c].style.top = yInicial;
			yInicial = yInicial + 20;
			if (comps[c].innerHTML == '')
				comps[c].innerHTML = '[' + comps[c].id + ']';
			Drag.init(comps[c]);
		}
	}
}

function dragShowPositions() {
	comps = $$('div[moveable="true"]');
	var c;
	for (c = 0; c < comps.length; c++)
		alert(comps[c].id + ' [x:' + comps[c].style.left + ',y:'
				+ comps[c].style.top + ']');
}

function currencyToString(v) {
	var v2;
	if (typeof (v) == "number")
		v2 = v.toFixed(2) + '';
	else
		v2 = v + '';
	var vl;
	if ((v2.indexOf('.') != -1) && (v2.indexOf(',') != -1)) {
		vl = '';
		for (n = 0; n < v2.length; n++) {
			var ch = v2.charAt(n);
			if (ch != '.')
				vl = vl + ch;
		}
	} else
		vl = v2;
	var rValue = '';
	var decimais = 0;
	var virgula = false;
	var n;
	for (n = 0; n < vl.length; n++) {
		var ch = vl.charAt(n);
		if (ch == '.')
			ch = ',';
		if (ch == ',')
			virgula = true;
		else if (virgula)
			decimais++;
		rValue = rValue + ch;
	}
	if (decimais == 0)
		rValue = rValue + ',00';
	else if (decimais == 1)
		rValue = rValue + '0';

	var nFormat = ',' + rValue.charAt(rValue.length - 2)
			+ rValue.charAt(rValue.length - 1);
	n = rValue.length - 4;
	var g = 0;
	while (n >= 0) {
		nFormat = rValue.charAt(n) + nFormat;
		n--;
		g++;
		if (g == 3 && n >= 0) {
			nFormat = '.' + nFormat;
			g = 0;
		}
	}
	return nFormat;
}

function getCellAttribute(cell, attrs) {
	var a = new Array();
	for (cc = 0; cc < cell.attributes.length; cc++) {
		var achou = false;
		for (cx = 0; cx < attrs.length; cx++)
			if (cell.attributes[cc].name == attrs[cx])
				achou = true;
		var vx = cell.attributes[cc].value;
		if (achou && vx != "" && vx != "null") {
			a.length = a.length + 1;
			a[a.length - 1] = new Object();
			a[a.length - 1].key = cell.attributes[cc].name;
			a[a.length - 1].value = vx;
		}
	}
	return a;
}

// Tree

function treeClickLeafNode(treeName, key) {
	$(treeName).onClick(key);
}

function treeClickRootNode(treeName, key) {
	var name = 'child:' + treeName.id + ':' + key;
	var e = $(name);
	if (e.style.display == 'none')
		e.style.display = '';
	else
		e.style.display = 'none';
}

function initSigeaFunctions() {

	var extendDialog = {
		yPos :0,
		xPos :0,

		show : function() {
			this.activate();
		},

		hide : function() {
			this.style.top = '10px';
			this.style.left = '10px';
			this.style.display = 'none';
			if (browser == "Internet Explorer") {
				this.setScroll(0, this.yPos);
				this.prepareIE("auto", "auto");
				this.hideSelects("visible");
			}

			this.displayLightbox("none");
		},

		activate : function() {
			if (browser == 'Internet Explorer') {
				this.getScroll();
				this.prepareIE('100%', 'hidden');
				this.setScroll(0, 0);
				this.hideSelects('hidden');
			}
			this.displayLightbox("block");
		},

		prepareIE : function(height, overflow) {
			bod = document.getElementsByTagName('body')[0];
			bod.style.height = height;
			bod.style.overflow = overflow;

			htm = document.getElementsByTagName('html')[0];
			htm.style.height = height;
			htm.style.overflow = overflow;
		},

		hideSelects : function(visibility) {
			selects = document.getElementsByTagName('select');
			for (i = 0; i < selects.length; i++) {
				selects[i].style.visibility = visibility;
			}
		},

		getScroll : function() {
			if (self.pageYOffset) {
				this.yPos = self.pageYOffset;
			} else if (document.documentElement
					&& document.documentElement.scrollTop) {
				this.yPos = document.documentElement.scrollTop;
			} else if (document.body) {
				this.yPos = document.body.scrollTop;
			}
		},

		setScroll : function(x, y) {
			window.scrollTo(x, y);
		},

		displayLightbox : function(display) {
			$('overlay').style.display = display;
			this.style.display = display;
		}

	}

	var extendTable = {

		setEnabled : function(valueEnabled) {
			this.enabled = valueEnabled;
			this.rewriteHtml();
		},

		setReadOnly : function(valueReadOnly) {
			this.readOnly = valueReadOnly;
			this.rewriteHtml();
		},

		getEditRecord : function() {
			var rec = this.getRecord();
			if (rec == null) {
				rec = new Object();
				eval("rec." + this.attributes["keyName"].value
						+ " = --this.nextTempKey");
				this.data.length = this.data.length + 1;
				for (c = this.data.length - 1; c > 0; c--)
					this.data[c] = this.data[c - 1];
				this.data[0] = rec;
			}
			return rec;
		},

		uniqueFields : function(fieldNames, fieldValues) {
			var result = true;
			var c;
			for (c = 0; c < this.data.length; c++) {
				var ky = eval('this.data[' + c + '].'
						+ this.attributes["keyName"].value);
				var eq = true;
				for ( var i = 0; i < fieldNames.length; i++) {
					var fieldVl = eval('this.data[' + c + '].' + fieldNames[i]);
					if (fieldVl != fieldValues[i])
						eq = false;
				}
				if (eq && (ky != this.currentKey))
					result = false;
			}
			return result;
		},

		getRowDef : function(rowType) {
			var a = new Array();
			var p = 0;
			for (rowCount = 0; rowCount < this.tableDef.length; rowCount++) {
				if (this.tableDef[rowCount].type == rowType) {
					a.length = a.length + 1;
					a[p++] = this.tableDef[rowCount];
				}
			}
			return a;
		},

		writeRow : function(rowDef, dataRec, key) {
			var row = this.insertRow(this.rows.length);
			if (rowDef.className != null && rowDef.className != undefined) {
				var p = rowDef.className.indexOf(',');
				if (p == -1) {
					row.className = rowDef.className;
				} else {
					if (corSimCornao)
						row.className = rowDef.className.substring(0, p);
					else
						row.className = rowDef.className.substring(p + 1);
					corSimCornao = !corSimCornao;
				}
			}
			var c;
			for (c = 0; c < rowDef.cells.length; c++) {
				var cell = row.insertCell(row.cells.length);
				if (this.getKey() != null && this.getKey() == key) {
					cell.style.backgroundColor = '#CCC';
				}
				for (cc = 0; cc < rowDef.cells[c].props.length; cc++)
					cell.setAttribute(rowDef.cells[c].props[cc].key,
							rowDef.cells[c].props[cc].value);

				var htmlText;
				if (rowDef.cells[c].field == null)
					htmlText = rowDef.cells[c].innerHTML;
				else {
					if (rowDef.type == 'total') {
						var vlTotal = this.getFieldTotal(rowDef.cells[c].field);
						if (rowDef.cells[c].dataType == 'Currency')
							htmlText = currencyToString(vlTotal);
						else
							htmlText = vlTotal;
					} else
						htmlText = eval('dataRec.' + rowDef.cells[c].field);
				}

				if (htmlText == null || htmlText == undefined)
					htmlText = '';
				else {
					if (rowDef.cells[c].dataType == 'Currency')
						htmlText = currencyToString(htmlText);
					if (rowDef.cells[c].dataType == 'Image') {
						htmlText = "<image src='" + htmlText + "'/>";
					}
					if (rowDef.cells[c].type == 'checkbox') {
						var tempHtml = "<input type='checkbox' id='" + this.id
								+ ":" + rowDef.cells[c].idCol + ":" + key
								+ "' onclick='javascript:colClick(this, ";
						tempHtml = tempHtml + '"' + rowDef.cells[c].idCol + '"';
						tempHtml = tempHtml + ")'";
						if (this.readOnly)
							tempHtml = tempHtml + " disabled ";
						if (eval('dataRec.' + rowDef.cells[c].idCol))
							tempHtml = tempHtml + " checked ";
						tempHtml = tempHtml + "/>";
						htmlText = tempHtml + htmlText;
					}
					if (rowDef.cells[c].type == 'link') {
						if (!this.readOnly) {
							var tempHtml = "<a href='#' onclick='javascript:colClick(this, ";
							tempHtml = tempHtml + '"' + rowDef.cells[c].idCol
									+ '"';
							tempHtml = tempHtml + ")'>";
							htmlText = tempHtml + htmlText + "</a>";
						}
					}
					if (rowDef.cells[c].type == 'edit') {
						if (!this.readOnly) {
							var idEdit = 'edText:' + rowDef.cells[c].field
									+ ':' + key;
							var tempHtml = "<input type='text' id='" + idEdit
									+ "' name='" + idEdit + "' value='"
									+ htmlText + "' class='input_text'";
							tempHtml = tempHtml + " tableName='" + this.id
									+ "' ";
							tempHtml = tempHtml + " field='"
									+ rowDef.cells[c].field + "' ";
							if (this.onBlurFieldEdit != undefined) {
								tempHtml = tempHtml
										+ " onblur='javascript:tbEditBlur(this,";
								tempHtml = tempHtml + '"' + key + '"';
								tempHtml = tempHtml + ")' ";
							}
							htmlText = tempHtml + '>';
						}
					}
				}

				cell.innerHTML = htmlText;
			}
			return row;
		},

		rewriteHtml : function() {
			corSimCornao = true;
			this.style.display = 'none';
			while (this.rows.length > 0)
				this.deleteRow(0);

			var keyName = getAttribute(this, 'keyName', '');

			var rowDef = this.getRowDef('header');
			if (rowDef != null) {
				var p;
				for (p = 0; p < rowDef.length; p++)
					this.writeRow(rowDef[p], null, null);
			}

			if (this.data != undefined && this.data != null) {
				rowDef = this.getRowDef('detail');
				rowDef = rowDef[0];
				for (rowNum = 0; rowNum < this.data.length; rowNum++) {
					if (keyName == '')
						k = rowNum;
					else
						k = eval('this.data[rowNum].' + keyName);

					var row = this.writeRow(rowDef, this.data[rowNum], k);

					if (k != null)
						row.setAttribute("keyValue", k);
				}
			}

			rowDef = this.getRowDef('total');
			if (rowDef != null) {
				var p;
				for (p = 0; p < rowDef.length; p++)
					this.writeRow(rowDef[p], null, null);
			}
			this.style.display = '';
		},

		setSelectedRow : function(colName, key) {
			for ( var n = 0; n < this.data.length; n++) {
				var v = this.getKeyFromRec(this.data[n]);
				var result = false;
				if (v == key)
					result = true;
				var name = this.id + ":" + colName + ":" + v;
				$(name).checked = result;
			}
		},

		setSelectedRows : function(colName, keyList) {
			for ( var n = 0; n < this.data.length; n++) {
				var v = this.getKeyFromRec(this.data[n]);
				var result = false;
				for ( var c = 0; c < keyList.length; c++)
					if (v == keyList[c])
						result = true;
				var name = this.id + ":" + colName + ":" + v;
				$(name).checked = result;
			}
		},

		addSelectedRow : function(colName, key) {
			for ( var n = 0; n < this.data.length; n++) {
				var v = this.getKeyFromRec(this.data[n]);
				var result = false;
				var name = this.id + ":" + colName + ":" + v;
				if (v == key) {
					$(name).checked = true;
					break;
				}
			}
		},

		addSelectedRows : function(colName, keyList) {
			var nSelected = 0;
			for ( var n = 0; n < this.data.length; n++) {
				var v = this.getKeyFromRec(this.data[n]);
				var name = this.id + ":" + colName + ":" + v;
				var c;
				for (c = 0; c < keyList.length; c++)
					if (v == keyList[c]) {
						$(name).checked = true;
						nSelected++;
						break;
					}
			}

			return nSelected;
		},

		getEdits : function(colName) {
			var a = new Array();
			a.length = this.data.length;
			var q = 0;
			var n;
			for (n = 0; n < this.data.length; n++) {
				var v = this.getKeyFromRec(this.data[n]);
				var name = "edText:" + colName + ":" + v;
				a[n] = $(name);
			}
			return a;
		},

		selectAll : function(colName) {
			var n;
			for (n = 0; n < this.data.length; n++) {
				var v = this.getKeyFromRec(this.data[n]);
				var name = this.id + ":" + colName + ":" + v;
				$(name).checked = true;
			}
		},

		unselectAll : function(colName) {
			var n;
			for (n = 0; n < this.data.length; n++) {
				var v = this.getKeyFromRec(this.data[n]);
				var name = this.id + ":" + colName + ":" + v;
				$(name).checked = false;
			}
		},

		getSelectedRows : function(colName) {
			var q = 0;
			if (this.data != null)
				for (var n = 0; n < this.data.length; n++) {
					var v = this.getKeyFromRec(this.data[n]);
					var name = this.id + ":" + colName + ":" + v;
					if ($(name).checked)
						q++;
				}
			var a = new Array();
			a.length = q;
			var q = 0;
			for (var n = 0; n < this.data.length; n++) {
				var v = this.getKeyFromRec(this.data[n]);
				var name = this.id + ":" + colName + ":" + v;
				if ($(name).checked) {
					a[q] = v;
					q++;
				}
			}
			return a;
		},

		setActiveRec : function(rec) {
			v = this.getKeyFromRec(rec);
			this.setKey(v);
		},

		getRecord : function() {
			if (this.data == null || this.data == undefined)
				return null;
			for (var n = 0; n < this.data.length; n++) {
				var v = this.getKeyFromRec(this.data[n]);
				if (v == this.currentKey)
					return this.data[n];
			}
			return null;
		},

		getRecordByKey : function(k) {
			if (this.data == null || this.data == undefined)
				return null;
			var n;
			for (n = 0; n < this.data.length; n++) {
				var v = this.getKeyFromRec(this.data[n]);
				if (v == k)
					return this.data[n];
			}
			return null;
		},

		removeRec : function(rec) {
			var k = this.getKeyFromRec(rec);
			var p = 0;
			while ((p < this.data.length) && (this.getKeyFromDataTable(p) != k))
				p++;
			while (p < this.data.length - 1) {
				this.data[p] = this.data[p + 1];
				p++;
			}
			this.data.length = this.data.length - 1;
			if (k == this.currentKey)
				this.setKey(null);
			else
				this.rewriteHtml();
		},

		getKeyFromDataTable : function(nRec) {
			return this.getKeyFromRec(this.data[nRec]);
		},

		getKeyFromRec : function(rec) {
			return eval('rec.' + this.attributes["keyName"].value);
		},

		getKey : function() {
			return this.currentKey;
		},

		setKey : function(keyValue) {
			this.currentKey = keyValue;
			var event = this.eventSelect;
			if (event != null)
				event(this, this.currentKey != null);
			this.rewriteHtml();
		},

		getData : function() {
			return this.data;
		},

		setData : function(dadosToSet) {
			this.currentKey = null;
			this.data = dadosToSet;
			if ((dadosToSet == null) || (dadosToSet.length == 0))
				this.setKey(null);
			this.rewriteHtml();
		},

		getFieldTotal : function(fieldName) {
			if (this.data == null || this.data == undefined)
				return 0;
			var total = 0;
			for ( var ctFieldTotal = 0; ctFieldTotal < this.data.length; ctFieldTotal++) {
				var vlCel = eval('this.data[ctFieldTotal].' + fieldName);
				if (vlCel != undefined)
					total = total + vlCel;
			}
			return total;
		}
	}

	var extendCombo = {

		getData : function() {
			return this.data;
		},

		internalOnChange : function() {
			if (this.eventOnChange != null && this.eventOnChange != undefined)
				this.eventOnChange();
		},

		getRecord : function() {
			var campoChave = this.attributes["keyName"].value;
			if (this.data == null || this.data == undefined)
				return null;
			for (ct = 0; ct < this.data.length; ct++) {
				var chave = eval('this.data[ct].' + campoChave);
				if (chave == this.value)
					return this.data[ct];
			}
			return null;
		},

		setData : function(dados) {
			var chave;
			var valor;
			if (dados==null)
				dados = new Array();
			this.data = dados;
			var campoChave = this.attributes["keyName"].value;
			var campoTexto = this.attributes["labelName"].value;
			this.options.length = this.data.length;
			var ct;
			for (ct = 0; ct < this.data.length; ct++) {
				if (campoChave == '') {
					try {
						chave = eval('this.data[ct]');
						valor = eval('this.data[ct]');
					} catch (e) {
					//	showExceptionMessage(e);
					}
				} else {
					try {
						chave = eval('this.data[ct].' + campoChave);
						valor = eval('this.data[ct].' + campoTexto);
					} catch (e) {
					//	showExceptionMessage(e);
					}
				}
				this.options[ct] = new Option(valor, chave);
			}
			if (dados.length == 0)
				this.setKey(null);
			else {
				try {
					if (campoChave == '')
						chave = eval('this.data[0]');
					else
						chave = eval('this.data[0].' + campoChave);
					this.setKey(chave);
				} catch (e) {
				//	showExceptionMessage(e);
				}
			}
		},

		setKey : function(key) {
			this.value = key;
			this.internalOnChange();
		},

		getKey : function() {
			return this.value;
		}
	}

	var extendTextArea = {

		internalOnBlur : function() {
			if (this.eventOnBlur != null && this.eventOnBlur != undefined)
				this.eventOnBlur();
		},

		setFocus : function() {
			setFocusWithTimeout(this);
		}
	}

	var extendTab = {

		tabShow : function(tabNum) {
			if (this.tabber != null && this.tabber != undefined)
				this.tabber.tabShow(tabNum);
		}

	}

	var extendTree = {

		setData : function(data) {
			this.data = data;
			this.writeTree();
		},

		onClick : function(key) {
			var event = this.eventClick;
			if (event != null)
				event(this, key);
		},

		writeData : function(parentElement, dataToInsert, parentKey) {
			var campoChave = this.attributes["keyName"].value;
			var campoTexto = this.attributes["labelName"].value;

			var p = 0;
			var tableNode = document.createElement("table");
			parentElement.appendChild(tableNode);
			var n;
			for (n = 0; n < dataToInsert.length; n++) {
				var row = tableNode.insertRow(p);
				var key = eval('dataToInsert[n].' + campoChave);

				row.id = this.id + ':' + key;
				p++;
				cell = row.insertCell(0);
				if (dataToInsert[n].filhos == undefined)
					dataToInsert[n].filhos = new Array();
				var functionCall;
				if (dataToInsert[n].filhos.length == 0) {
					functionCall = 'treeClickLeafNode(' + this.id + ',' + key
							+ ')';
				} else {
					functionCall = 'treeClickRootNode(' + this.id + ',' + key
							+ ')';
				}
				cell.innerHTML = cell.innerHTML
						+ "<a href='#' onclick='javascript:" + functionCall
						+ "'>" + key + "</a>";
				cell = row.insertCell(1);
				cell.setAttribute('nowrap', '')
				cell.innerHTML = eval('dataToInsert[n].' + campoTexto);
				if (dataToInsert[n].filhos.length > 0) {
					row = tableNode.insertRow(p);
					row.id = 'child:' + this.id + ':' + key;
					row.style.display = 'none';
					p++;
					cell = row.insertCell(0);
					cell = row.insertCell(1);
					this.writeData(cell, dataToInsert[n].filhos, key);
				}
			}
		},

		writeTree : function() {
			this.writeData(this, this.data, '');
		}
	}

	var extendFocusMoveTo = {
		onFocus : function() {
			var cp = $(this.onFocusMoveTo);
			if (cp != null && cp != undefined)
				cp.setFocus();
		}
	}

	var extendEditNumber = {
		getAsNumber : function() {
    		try {
	   	      return parseFloat(this.value);
		    } catch (e) {
		      return 0;
		    }
		}
	}

	var extendSearch = {

		init : function() {
			if (this.attributes['desc'] != null
					&& this.attributes['desc'] != undefined)
				this.desc1 = $(this.attributes['desc'].value);
			else
				this.desc1 = null;

			if (this.attributes['desc2'] != null
					&& this.attributes['desc2'] != undefined)
				this.desc2 = $(this.attributes['desc2'].value);
			else
				this.desc2 = null;
		},

		onclickBtBusca : function() {
			var dialogName = this.mainCp.attributes['dialog'].value;
			var dialogWidth;
			var dialogHeight;
			if (this.mainCp.attributes['dialogWidth'] == undefined)
				dialogWidth = 600;
			else
				dialogWidth = parseInt(this.mainCp.attributes['dialogWidth'].value, 10);
			if (this.mainCp.attributes['dialogHeight'] == undefined)
				dialogHeight = 240;
			else
				dialogHeight = parseInt(this.mainCp.attributes['dialogHeight'].value, 10);
			$("auxdiv").searchComp = this.mainCp;
			openDialog(dialogName, dialogHeight, dialogWidth, "json="
					+ Object.toJSON(this.mainCp.param),
					this.mainCp.onDialogCloseInternal);
		},

		onDialogCloseInternal : function(r) {
			if (r.key != undefined)
				$("auxdiv").searchComp.setKey(r.key);
		},

		setKey : function(sKey) {
			if (this.search(sKey))
				this.key = sKey;
			else
				this.key = null;
			if (this.key == null)
				this.value = '';
			else
				this.value = sKey;
			if ((cp.eventOnSelect != null) && (cp.eventOnSelect != undefined))
				cp.eventOnSelect();
		},

		getKey : function() {
			return this.key;
		},

		showSearch : function(kSearchValue) {
			var searchButtonName = this.attributes['searchButton'].value;
			$(searchButtonName).onclick();
			var searchName = $(dialogName).attributes['onShowSearch'].value;
			eval(searchName + '(' + kSearchValue + ')');
		},

		search : function(kSearchValue) {
			var cp = this;
			if (kSearchValue == null
					|| ((typeof (kSearchValue) == 'string') && (kSearchValue == ''))
					|| kSearchValue == undefined) {
				if (cp.desc1 != null && cp.desc1 != undefined)
					cp.desc1.value = '';
				if (cp.desc2 != null && cp.desc2 != undefined)
					cp.desc2.value = '';
				cp.key = null;
				if ((cp.eventOnSelect != null)
						&& (cp.eventOnSelect != undefined))
					cp.eventOnSelect();
				return;
			}
			var groovyName = this.attributes['groovy'].value;
			var result = null;
			var parametrosBusca = Object.toJSON(this.param);

			ajaxMethodSynchronous("buscasRemote", groovyName, {
				codigo :kSearchValue,
				tipo :'busca',
				param :parametrosBusca
			}, function(json) {
				if (json.achou) {
					if (json.buscar) {
						cp.showSearch(kSearchValue);
					} else {
						if (cp.desc1 != null)
							cp.desc1.value = json.desc1;
						if (cp.desc2 != null)
							cp.desc2.value = json.desc2;
						cp.key = kSearchValue;
						if ((cp.eventOnSelect != null)
								&& (cp.eventOnSelect != undefined))
							cp.eventOnSelect();
						result = true;
					}
				} else {
					if (cp.desc1 == null)
						showValidationError(cp, 'N?o encontrado');
					else {
						showValidationError(cp, null);
						cp.desc1.value = 'N?o encontrado';
					}
					if (cp.desc2 != null)
						cp.desc2.value = '';
					cp.key = null;
					if ((cp.eventOnSelect != null)
							&& (cp.eventOnSelect != undefined))
						cp.eventOnSelect();
					result = false;
				}
			});
			return result;
		},

		setFocus : function() {
			setFocusWithTimeout(this);
		},

		onblurEdit : function(event) {
			this.search(this.value);
			if (this.eventOnBlur != undefined)
				this.eventOnBlur();
		}
	}

	var extendSearch2 = {

		init : function() {
		},

		onblurEdit : function(event) {
			var res = this.searchValue(this.value);
			if (res.ok) {
				this.setKey(res.id);
    			if (this.eventOnBlur != undefined)
	    			this.eventOnBlur();
			}
			else {
				this.setFocus();
			}
		},
		
		onclickBtBusca : function() {
			if (this.mainCp.search == undefined)
				return;
			var params;
			if (this.mainCp.eventOnGetParams!=null && this.mainCp.eventOnGetParams!=undefined)
				params = this.mainCp.eventOnGetParams(this.mainCp);
			else
				params = {};
			var info = this.mainCp.search.searchWindowInfo();
			var dialogName = info.dialogName;
			var dialogWidth;
			var dialogHeight;
			if (info.dialogWidth == undefined)
				dialogWidth = 600;
			else
				dialogWidth = info.dialogWidth;
			if (info.dialogHeight == undefined)
				dialogHeight = 240;
			else
				dialogHeight = info.dialogHeight;
			$("auxdiv").searchComp = this.mainCp;
			openDialog(dialogName, dialogHeight, dialogWidth, "json=" + Object.toJSON(params), this.mainCp.onDialogCloseInternal);
		},

		onDialogCloseInternal : function(r) {
			if (r.key != undefined)
				$("auxdiv").searchComp.setKey(r.key);
		},
		
		searchValue : function(value) {
			if (this.search == undefined)
		      return {ok : true, key : value};
		    else {
		        return this.eventOnSearch(this, value, false);
		    }
		},
		
		eventOnSearch:function(comp, value, tipoChave) {
			var params;
			if (this.eventOnGetParams!=null && this.eventOnGetParams!=undefined)
				params = this.eventOnGetParams();
			else
				params = {};
			return this.search.search(comp, value, tipoChave, params);
		},
		
		setKey : function(sKey) {
			if (this.key == sKey)
				return;
            var res = this.eventOnSearch(this, sKey, true);
		    if (res.ok)
		        this.key = sKey;
	        else
	            this.key = null;
			if ((this.eventOnSelect != null) && (this.eventOnSelect != undefined))
				this.eventOnSelect();
		},

		getKey : function() {
			return this.key;
		},

		setFocus : function() {
			setFocusWithTimeout(this);
		}

	}

	var extendFileUpload = {
		init : function() {
			var src = getCtxPath() + 'upload.vm?id=' + this.id;
			if (this.attributes['buttonLabel'] != null) {
				src = src + '&label=' + this.attributes['buttonLabel'].value;
			}
			var iframew;
			if (this.attributes['frameWidth'] == null || this.attributes['frameWidth'] == undefined)
				iframew = '700';
			else
				iframew = this.attributes['frameWidth'].value;
			var iframeh;
			if (this.attributes['frameHeight'] == null || this.attributes['frameHeight'] == undefined)
				iframeh = '60';
			else
				iframeh = this.attributes['frameHeight'].value;
			
			this.innerHTML = '<iframe src="' + src + '" width='+iframew+' height='+iframeh+'></iframe>';
		},

		onFileUpload : function(id, fileName) {
			if (this.eventFileUpload != undefined)
				this.eventFileUpload(id, fileName);
		}
	}

	var extendExtTab = {

		init : function() {
			var t = this;
			var newTab = document.createElement("table");
			this.newTab = newTab;
			var row = newTab.insertRow(0);
			var first = true;
			for (n = 0; n < t.childNodes.length; n++) {
				if (t.childNodes[n].tagName == 'DIV'
						&& t.childNodes[n].attributes != undefined
						&& t.childNodes[n].attributes['caption'] != undefined) {
					t.childNodes[n].key = n;
					var cell = row.insertCell(row.cells.length);
					cell.id = 'id:' + t.id + ':' + n;
					cell.innerHTML = t.childNodes[n].attributes['caption'].value;
					cell.onclick = this.onclick;
					cell.relatedDiv = t.childNodes[n];
					if (first) {
						first = false;
						cell.style.backgroundColor = '#AA00FF';
					} else
						t.childNodes[n].style.display = 'none';
				}
			}
			t.insertBefore(newTab, t.childNodes[0]);
		},

		rewriteHtml : function() {

		},

		getTabs : function() {
			var r = new Array();
			for (n = 0; n < this.childNodes.length; n++) {
				var node = this.childNodes[n];
				if (node.tagName == 'DIV') {
					if (node.attributes != undefined) {
						if (node.attributes['caption'] != undefined) {
							r.length = r.length + 1;
							r[r.length - 1] = node;
						}
					}
				}
			}
			return r;
		},

		createTab : function(id, caption) {
			var newTab = document.createElement("div");
			newTab.id = id;

			newTab.setAttribute('caption', caption);
			this.appendChild(newTab);
			this.updateTabs();

			return newTab;
		},

		updateTabs : function() {
			var row = this.newTab.rows[0];
			for (n = 0; n < this.childNodes.length; n++) {
				if ((this.childNodes[n].tagName == 'DIV')
						&& this.childNodes[n].attributes != undefined
						&& this.childNodes[n].attributes['caption'] != undefined
						&& (this.childNodes[n].key == undefined)) {
					this.childNodes[n].key = n;
					var cell = row.insertCell(row.cells.length);
					cell.innerHTML = this.childNodes[n].attributes['caption'].value;
					cell.onclick = this.onclick;
					cell.relatedDiv = this.childNodes[n];
					this.childNodes[n].style.display = 'none';
				}
			}
		},

		onclick : function(ev) {
			var e = Event.element(ev);
			var t = e.parentNode.parentNode;
			var sz = t.rows[0].cells.length;
			for (p = 0; p < sz; p++) {
				t.rows[0].cells[p].style.backgroundColor = '#FFFFFF';
				t.rows[0].cells[p].relatedDiv.style.display = 'none';
			}
			e.style.backgroundColor = '#AA00FF';
			e.relatedDiv.style.display = '';
		}

	}

	var extendEditString = {

		setFocus : function() {
			setFocusWithTimeout(this);
		},

		onBlurEditString : function(event) {
			if (this.eventOnBlur != undefined)
				this.eventOnBlur();
		}

	}
	
	var extendEditDate = {
        formatacaoData : function(tecla) {
	      var separador = "/";
	      tecla = tecla.keyCode; 

	      var valor = this.value.split('');
	      var formatado = "";
	      
	      var i = 0;
	      while (i < valor.length) {
		    var caractere = valor[i]; 
		    var numeros = /^\d+$/; 

		    if (numeros.test(caractere) || caractere == separador) 
			  formatado += String(caractere);
		    
		    if ((formatado.length == 2 || formatado.length == 5) && tecla != 8) {
			  formatado += separador;
			  i++;
		    }

		    i++; 
	      }
	    this.value = formatado;
	  }
	}

	var extendEditCurrency = {

		getAsNumber : function() {
			return this.content;
		},

		setAsNumber : function(vl) {
		    var v;
			if (typeof (vl) == 'string') {				
				v = parseFloat(vl);
			}
			else
				v = vl;
			if (v == null) {
				this.content = null;
				this.value = '';
			} else {
				this.content = v;
				this.value = currencyToString(this.content);
			}
		},

		setFocus : function() {
			setFocusWithTimeout(this);
		},

		onBlurEditCurrency : function(event) {
			var valor = this.value;
			var valido = true;
			var virgula = false;
			var decSeparator = String(3 / 2).charAt(1);
			var vx = '';
			var n;
			for (n = 0; n < valor.length; n++) {
				var ch = valor.charAt(n);
				if (ch != '.') {
					if ("0123456789,".indexOf(ch) == -1)
						valido = false;
					else if (ch == ',')
						if (virgula)
							valido = false;
						else {
							virgula = true;
							ch = decSeparator;
						}
					vx = vx + ch;
				}
			}
			if (!valido) {
				this.value = '';
				this.setAsNumber(0);
				return;
			}
			if (vx == '')
				this.setAsNumber(0);
			else
				this.setAsNumber(vx);
			if (this.eventOnBlur != undefined)
				this.eventOnBlur();
		}
	}

	getBrowserInfo();

	$$(".tabbertab").each( function(element) {
		if (element.style.display == 'none')
			element.style.display = '';
	});

	var comps = $$('*[sigeaType]');
	var c;
	for (c = 0; c < comps.length; c++) {
		var typeName;
		var cp;
					try {
		typeName = comps[c].attributes["sigeaType"].value;
		cp = comps[c];
					} catch (e) {
		typeName = '';
		cp = '';
		alert(comps[c].name+":"+comps[c].id);
					showExceptionMessage(e);
					}
		if (typeName == "dialog") {
			comps[c].hide();
			Object.extend(cp, extendDialog);
			cp.style.position = 'absolute';
			cp.style.zIndex = 1001;
			cp.style.backgroundColor = '#EEEEEE';
			cp.style.top = "10%";
			cp.style.left = "10%";
			cp.style.width = "80%";
			cp.style.height = "80%";
			cp.style.overflow = "auto";
		}
		if (typeName == "tab") {
			Object.extend(cp, extendTab);
		}
		if (typeName == "tree") {
			Object.extend(cp, extendTree);
		} else if (typeName == "edit") {
			if (cp.attributes["dataType"] == undefined)
				dataType = "String";
			else
				dataType = cp.attributes["dataType"].value;
			if (dataType == "Currency") {
				cp.content = null;
				Object.extend(cp, extendEditCurrency);
				cp.onblur = cp.onBlurEditCurrency;
				cp.style.textAlign = "right";
			} else 
			if (dataType == "Date") {
				cp.content = null;
				Object.extend(cp, extendEditDate);
			} else {
				cp.content = null;
				Object.extend(cp, extendEditString);
				cp.onblur = cp.onBlurEditString;
			}
			if (cp.attributes["onFocusMoveTo"] != undefined) {
				cp.onFocusMoveTo = cp.attributes["onFocusMoveTo"].value;
				Object.extend(cp, extendFocusMoveTo);
				cp.onfocus = extendFocusMoveTo.onFocus;
			}
			if (isIE()) {
				if (cp.attributes["readOnly"] != undefined) {
					setDisabledColor(cp);
				}
			}
		} else if (typeName == "combo") {
			Object.extend(cp, extendCombo);
			cp.onchange = cp.internalOnChange;
		} else if (typeName == "textarea") {
			Object.extend(cp, extendTextArea);
			cp.onblur = cp.internalOnBlur;
		} else if (typeName == "exttab") {
			Object.extend(cp, extendExtTab);
			cp.init();
		} else if (typeName == "fileUpload") {
			Object.extend(cp, extendFileUpload);
			cp.init();
		} else if (typeName == "search") {
			Object.extend(cp, extendSearch);
			cp.init();
			cp.onblur = cp.onblurEdit;
			var searchButtonName = cp.attributes['searchButton'].value;
			if (isIE())
				if (cp.attributes["readOnly"] != undefined)
					cp.style.background = '#DDD';
			if ($(searchButtonName) != null) {
				$(searchButtonName).onclick = cp.onclickBtBusca;
				$(searchButtonName).mainCp = cp;
			}
		} else if (typeName == "search2") {
			Object.extend(cp, extendSearch2);
			cp.init();
			cp.onblur = cp.onblurEdit;
			if (isIE())
				if (cp.attributes["readOnly"] != undefined)
					cp.style.background = '#DDD';
			var searchButtonName = cp.attributes['searchButton'].value;
			if ($(searchButtonName) != null) {
				$(searchButtonName).onclick = cp.onclickBtBusca;
				$(searchButtonName).mainCp = cp;
			}
		} else if (typeName == "table") {
			var tabela = comps[c];

			tabela.nextTempKey = 0;
			tabela.currentKey = null;
			tabela.readOnly = false;
			tabela.enabled = true;

			var tableDef = new Array(tabela.rows.length);
			tabela.tableDef = tableDef;
			for (rowNum = 0; rowNum < tabela.rows.length; rowNum++) {
				tableDef[rowNum] = new Object();
				tableDef[rowNum].type = getAttribute(tabela.rows[rowNum],
						"type", null);
				tableDef[rowNum].className = tabela.rows[rowNum].className;
				if (tableDef[rowNum].type == null)
					alert('Line of table [' + tabela.id + '] without row type ');
				tableDef[rowNum].cells = new Array(
						tabela.rows[rowNum].cells.length);
				for (celNum = 0; celNum < tabela.rows[rowNum].cells.length; celNum++) {
					tableDef[rowNum].cells[celNum] = new Object();
					tableDef[rowNum].cells[celNum].innerHTML = tabela.rows[rowNum].cells[celNum].innerHTML;
					tableDef[rowNum].cells[celNum].type = getAttribute(
							tabela.rows[rowNum].cells[celNum], "type", null);
					tableDef[rowNum].cells[celNum].field = getAttribute(
							tabela.rows[rowNum].cells[celNum], "field", null);
					tableDef[rowNum].cells[celNum].fieldLabel = getAttribute(
							tabela.rows[rowNum].cells[celNum], "fieldLabel",
							null);
					tableDef[rowNum].cells[celNum].dataType = getAttribute(
							tabela.rows[rowNum].cells[celNum], "dataType", null);
					tableDef[rowNum].cells[celNum].idCol = getAttribute(
							tabela.rows[rowNum].cells[celNum], "idCol", null);
					tableDef[rowNum].cells[celNum].props = getCellAttribute(
							tabela.rows[rowNum].cells[celNum], [ "align",
									"colspan", "colSpan", "bgcolor", "bgColor",
									"nowrap" ])
					if (tableDef[rowNum].cells[celNum].type == null) {
						if (tableDef[rowNum].cells[celNum].field == null)
							tableDef[rowNum].cells[celNum].type = 'label';
						else
							tableDef[rowNum].cells[celNum].type = 'field';
					}
				}
			}
			Event.observe(tabela, "click", onMouseClickTable, false);
			Event.observe(tabela, "onMouseOver", onMouseOverTabela, false);
			Object.extend(tabela, extendTable);
			tabela.rewriteHtml();
		}
	}
}

function showReport(context, path, className, functionName, params) {
	openDialog(context + '/' + path + '/' + className + '/' + functionName
			+ '?' + Hash.toQueryString(params), 420, 700, params, null)
}

function ajaxMethod(className, functionName, params, callback) {
	ajaxCall(getCtxPath(), 'script', className, functionName, params, callback,
			false);
}

function ajaxMethodSynchronous(className, functionName, params, callback) {
	ajaxCall(getCtxPath(), 'script', className, functionName, params, callback,
			true);
}

function ajaxReport(className, functionName, params) {
	ajaxCall(getCtxPath(), 'script', className, functionName, params, 
	  function(json) {
		var urlReport;
		if (json==null) {
			urlReport = getCtxPath()+'relatorio.vm';
			alert('erro gerando relatorio');
		}
		else
		    if (json.url.substr(0,7)=='http://' || json.url.substr(0,8)=='https://')
		      urlReport = json.url;
		    else
		    	urlReport = getCtxPath()+json.url;
		if (json.absoluteUrl!=undefined)
			if (json.absoluteUrl) 
				urlReport = json.url;
//		if (isIE())
//			urlReport = getCtxPath()+'report/report.pdf?id=report'; 
		openDialog(urlReport, 600, 900, null, null);
	  }, false);
}
function ajaxCall(context, path, className, functionName, params, callback,
		isSync, showDiv) {
	if ($("divInfoCarregando") == null) {
		newDiv = document.createElement('div');
		newDiv.id = "divInfoCarregando";
		newDiv.innerHTML = '<img alt="loading" src="' + context + '/img/ajax-loading.gif"/>Processando ...';
		newDiv.style.display = 'none';
		newDiv.style.border = '1px solid';
		newDiv.style.position = 'absolute';
		newDiv.style.top = '45%'
		newDiv.style.left = '40%';
		newDiv.style.background = '#CCC';
		document.body.appendChild(newDiv);
	}
	if (showDiv!=false)
		$("divInfoCarregando").style.display = '';
	new Ajax.Request(context + '/' + path + '/' + className + '/'
			+ functionName, {
		method :'post',
		parameters :params,
		asynchronous :!isSync,
		onSuccess : function(transport) {
 		if (showDiv!=false)
	    		$("divInfoCarregando").style.display = 'none';
			var json;
			try {
				json = transport.responseText.evalJSON();
			} catch (e) {
				showErrorMessage('Erro convetendo JSON : '+className + '.' + functionName, transport);
			}
			if (json != null && json.hasSigeaException) {
				showErrorMessage('Error on call to ' + className + '.' + functionName + ' : ' + json.msg, transport);
				return;
			}
			try {
				callback(json);
			} catch (e) {
				showExceptionMessage(e);
			}
		},
		onFailure : function(transport) {
     		if (showDiv!=false)
    			$("divInfoCarregando").style.display = 'none';
			showErrorMessage(className + '.' + functionName, transport);
		}
	});
}

function showExceptionMessage(e) {
	var errMsg = 'showExceptionMessage :\n'+e.message + '\n';
	if (e.fileName != undefined)
		errMsg = errMsg + 'fileName:' + e.fileName + '\n';
	if (e.lineNumber != undefined)
		errMsg = errMsg + 'lineNumber:' + e.lineNumber + '\n';
	if (e.stack != undefined)
		errMsg = errMsg + 'stack:' + e.stack + '\n';
	alert(errMsg);
}

function parseDate(dt) {
	var d = new Date();
	if (dt.length==10) {
		d.setFullYear(parseInt(dt.substr(6,4), 10), parseInt(dt.substr(3,2), 10)-1, parseInt(dt.substr(0,2), 10));
	}
	return d;
}

function mascaraData(t) {
	var donepatt = /^(\d{2})\/(\d{2})\/(\d{4})$/;
	var patt = /(\d{2}).*(\d{2}).*(\d{4})/;
	var str = t.value;
	if (!str.match(donepatt)) {
		result = str.match(patt);
		if (result != null) {
			t.value = t.value.replace(/[^\d]/gi, '');
			str = result[1] + '/' + result[2] + '/' + result[3];
			t.value = str;
		} else {
			if (t.value.match(/[^\d]/gi))
				t.value = t.value.replace(/[^\d]/gi, '');
		}
	}
	if (t.value.length == 10) {
		valido = true;
		// mes
		var mes = t.value.substring(3, 5);
		if (mes == 0 || mes > 12)
			valido = false;
		// dia
		var dia = t.value.substring(0, 2);
		if (dia == 0 || dia > 31)
			valido = false;
		if (dia == 31)
			if (mes == 4 || mes == 6 || mes == 9 || mes == 11)
				valido = false;
		if (mes == 2)
			if (dia > 29)
				valido = false;
		//
		if (!valido) {
			alert('Data invalida');
			t.value = '';
		}
	}
}
