function get(id) {
	return document.getElementById(id);
}

function hide(id) {
	get(id).style.display = "none";
}
	
function show(id) {
	get(id).style.display = "";
}

function block_ctrl(e)
{
	if(!e) {
		if(window.event) { e = window.event; }
			else { return; }
	}	
	if(e.ctrlKey)
	{
		e.returnValue = false;
		return false;
	}
}


function SoNumeros(e)
{
	var key = 0;

	if(!e) {
		if(window.event) { e = window.event; }
			else { return; }
	}	
	if(typeof(e.keyCode) == 'number' && e.keyCode > 0) { key = e.keyCode; }									
	else if(typeof(e.which) == 'number') { key = e.which; }
	else if(typeof(e.charCode) == 'number') { key = e.charCode; }
	else { return; }
		
	var escapeKeys = '8,9,13,35,36,37,39,46';

	if (!(key>=48 && key<=57) && escapeKeys.indexOf(key) < 0)
	{
		e.returnValue = false;
		return false;
    }
}

// Seta a posicao do cursor
function textPos(textEl)
{
	try
	{
		var i=textEl.value.length+1;
		if (textEl.createTextRange)
		{
			theCaret = document.selection.createRange().duplicate();
			while (theCaret.parentElement() == textEl && theCaret.move('character',1)==1)
			{
				--i;
			}
			return i;
		}
		else
		{
			return -1;
		}
	}
	catch(msgErr)
	{
		msgErr.description = "Erro na função textPos()\n" + msgErr.description;
		throw msgErr;
	}
}

// Valida as teclas de controle
function TeclaDeControle(tecla)
{
	try
	{
		var alt = window.event.altKey;
		//PERMITE TECLAS DE CONTROLE
		return (alt || tecla == 8 || tecla == 9 || tecla == 13 || tecla == 18 || tecla == 27 || tecla == 35 || tecla == 36 || tecla == 37 || tecla == 38 || tecla == 39 || tecla == 40 || tecla == 45);
	}
	catch(msgErr)
	{
		msgErr.description = "Erro na função TeclaDeControle()\n" + msgErr.description;
		throw msgErr;
	}
}

// Formata numero
function Textbox_KeyDown(e, pControle, pCasasDecimais)
{
	
	try
	{
		var shift = window.event.shiftKey;
		var tecla = window.event.keyCode;
		if(!TeclaDeControle(tecla))
		{
			if(shift || (!(tecla >= 48 && tecla <= 57) && !(tecla >= 96 && tecla <= 105)) && tecla != 188 && tecla != 110 && tecla != 46)
			{
				event.keyCode = 0;
				event.returnValue = false;
			}
			else
			{
				if (((tecla == 188) || (tecla == 110)) && (pCasasDecimais == 0))
				{
					event.keyCode = 0;
					event.returnValue = false;
				}
				else
				{
					pos = pControle.value.indexOf(',');
					if (pos != -1)
					{
						if ((tecla == 188) || (tecla == 110))
						{
							event.keyCode = 0;
							event.returnValue = false;
						}
						else
						{
							curPos = textPos(pControle);
							if (pos > -1 && pos < (curPos - pCasasDecimais - 1))
							{
								event.keyCode = 0;
								event.returnValue = false;
							}
						}
					}
				}
			}
		}
	}
	catch(msgErr)
	{
		// Ignora o erro de validacao das teclas
		if (msgErr.number != -2147024891)
		{
			msgErr.description = "Erro na função Textbox_KeyDown()\n" + msgErr.description;
			throw msgErr;
		}
	}
}

function desabilitarenter(e)
{
	var tecla = 0;
	
	if(!e) {
		if(window.event) { e = window.event; }
			else { return; }
	}
	
	if(typeof(e.keyCode) == 'number' && e.keyCode > 0) { tecla = e.keyCode; }									
	else if(typeof(e.which) == 'number') { tecla = e.which; }
	else if(typeof(e.charCode) == 'number') { tecla = e.charCode; }
	else { return; }
	
	if ((tecla == 13))
		return false;
}

// Move o foco para o primeiro controle do form
function firstFocus()
{
	try
	{
		if (document.forms.length > 0)
		{
			var TForm = document.forms[0];
			for (i=0;i<TForm.length;i++)
			{
				if ((TForm.elements[i].type=="text") || (TForm.elements[i].type=="textarea") || (TForm.elements[i].type.toString().charAt(0)=="s"))
				{
					if (!document.forms[0].elements[i].disabled)
					{
						try
						{
							document.forms[0].elements[i].focus();
							break;
						}
						catch(err) {} // Ignora o campo e procura o proximo
					}
				}
			}
		}
	}
	catch(msgErr)
	{
		msgErr.description = "Erro na função firstFocus()\n" + msgErr.description;
		throw msgErr;
	}
}

// Move o foco para o controle indicado
function setFocus(controle)
{
	try
	{
		if(document.getElementById(controle) != null)
		{
			if(!document.all(controle).disabled)
			{
				try
				{
					document.all(controle).focus();
				}
				catch(err) {} // Ignora o campo e procura o proximo
			}
		}
	}
	catch(msgErr)
	{
		msgErr.description = "Erro na função setFocus()\n" + msgErr.description;
		throw msgErr;
	}
}

// Valida CNPJ
function ValidaCNPJ(source, arguments)
{
	try
	{
		var cCPFCGC = source.value;
		if (cCPFCGC.length !=0)
		{
			for (aux = 0; aux < 11; aux++)
			{
				cCPFCGC = cCPFCGC.replace('.','');
				cCPFCGC = cCPFCGC.replace('-','');
				cCPFCGC = cCPFCGC.replace(',','');
				cCPFCGC = cCPFCGC.replace('/','');
			}

			if (cCPFCGC.length == 14)
			{
				var nMult1 = '543298765432', nMult2 = '6543298765432', nDig1 = 0, nDig2 = 0, lVal = false;
				for (i = 0; i < 12; i++)
				{
					nDig1 += parseInt(cCPFCGC.substring(i, i + 1)) * parseInt(nMult1.substring(i, i + 1));
				}
				for (i = 0; i < 13; i++)
				{
					nDig2 += parseInt(cCPFCGC.substring(i, i + 1)) * parseInt(nMult2.substring(i, i + 1));
				}

				nDig1 = (nDig1 * 10) % 11;
				nDig2 = (nDig2 * 10) % 11;
				if (nDig1 == 10)
				{
					nDig1 = 0;
				}
				if (nDig2 == 10)
				{
					nDig2 = 0;
				}
				if (nDig1 != cCPFCGC.substring(12, 13) || nDig2 != cCPFCGC.substring(13, 14))
				{
					alert('CNPJ inválido.');
					source.focus();
				}
			}
			else
			{
				if (cCPFCGC.length > 0)
				{
					alert('CNPJ inválido.');
					source.focus();
				}
			}
		}
	}
	catch(msgErr)
	{
		msgErr.description = "Erro na função ValidaCNPJ()\n" + msgErr.description;
		throw msgErr;
	}
}


// Valida CPF
function ValidaCPF(source, arguments)
{
	try
	{
		var cCPFCGC = source.value;
		for (aux = 0; aux < 11; aux++)
		{
			cCPFCGC = cCPFCGC.replace('.','');
			cCPFCGC = cCPFCGC.replace('-','');
			cCPFCGC = cCPFCGC.replace(',','');
			cCPFCGC = cCPFCGC.replace('/','');
		}

		if (cCPFCGC.length == 11)
		{
			var nDig1 = 0, nDig2 = 0, lVal = false;
			// verifica se não é repetição de números ( 11111111111, 22222222222, etc )
			for (i = 0; i < 11; i++)
			{
				if (cCPFCGC.substring(i, i + 1) != cCPFCGC.substring(0, 1))
				{
					lVal = true;
				}
			}
			for (i = 10; i > 1; i--)
			{
				nDig1 += parseInt(cCPFCGC.substring(10 - i, 11 - i)) * i;
			}
			for (i = 11; i > 1; i--)
			{
				nDig2 += parseInt(cCPFCGC.substring(11 - i, 12 - i)) * i;
			}

			nDig1 = (nDig1 * 10) % 11;
			nDig2 = (nDig2 * 10) % 11;
			if (nDig1 == 10)
			{
				nDig1 = 0;
			}
			if (nDig2 == 10)
			{
				nDig2 = 0;
			}
			if (nDig1 != cCPFCGC.substring(9, 10) || nDig2 != cCPFCGC.substring(10, 11) || !lVal)
			{
				alert('CPF inválido.');
				source.focus();
			}
		}
		else
		{
			if (cCPFCGC.length > 0)
			{
				alert('CPF inválido.');
				source.focus();
			}
		}
	}
	catch(msgErr)
	{
		msgErr.description = "Erro na função ValidaCPF()\n" + msgErr.description;
		throw msgErr;
	}
}

//Valida Controle CaixaData
function ValidaData(source, dt_min, dt_max, fl_required)
{
	try
	{
		var cData = source.value;
		var cDataMin = dt_min == null ? '' : dt_min;
		var cDataMax = dt_max == null ? '' : dt_max;
		var cRequired = fl_required == 1 ? true : false;
		var situacao = true;
		
		if (cData.length == 10)
		{
			dia = (cData.substring(0,2));
			mes = (cData.substring(3,5));
			ano = (cData.substring(6,10));
			
			// Valida Data Mínima
			if(cDataMin.length == 10)
			{
				diaMin = (cDataMin.substring(0,2));
				mesMin = (cDataMin.substring(3,5));
				anoMin = (cDataMin.substring(6,10));
				
				if(ano < anoMin)
				{
					situacao = false;
				}

				if(ano == anoMin && mes < mesMin)
				{
					situacao = false;
				}
				
				if(ano == anoMin && mes == mesMin && dia < diaMin)
				{
					situacao = false;
				}					
			}
			
			// Valida Data Máxima
			if(cDataMax.length == 10)
			{
				diaMax = (cDataMax.substring(0,2));
				mesMax = (cDataMax.substring(3,5));
				anoMax = (cDataMax.substring(6,10));
				
				if(ano > anoMax)
				{
					situacao = false;
				}

				if(ano == anoMax && mes > mesMax)
				{
					situacao = false;
				}
				
				if(ano == anoMax && mes == mesMax && dia > diaMax)
				{
					situacao = false;
				}					
			}

			if ((dia < 1)||(dia < 1 || dia > 30) && (  mes == '04' || mes == '06' || mes == '09' || mes == 11 ) || dia > 31)
			{
				situacao = false;
			}

			if (mes < 1 || mes > 12)
			{
				situacao = false;
			}

			if (mes == 2 && ( dia < 1 || dia > 29 || ( dia > 28 && (parseInt(ano / 4) != ano / 4))))
			{
				situacao = false;
			}

			if (parseInt(ano) < 1900)
			{
				situacao = false;
			}

		}

		if (cData == "" && cRequired)
		{
			situacao = false;
		}

		if (situacao == false)
		{
			alert("Data inválida!");
			source.focus();
		}

	}
	catch(msgErr)
	{
		msgErr.description = "Erro na função ValidaData()\n" + msgErr.description;
		throw msgErr;
	}
}

// Valida a mascara
function Textbox_Mask(e, obj, mascara)
{
	try
	{
		var key = 0;

		if(!e) {
			if(window.event) { e = window.event; }
				else { return; }
		}	
		if(typeof(e.keyCode) == 'number' && e.keyCode > 0) { key = e.keyCode; }									
		else if(typeof(e.which) == 'number') { key = e.which; }
		else if(typeof(e.charCode) == 'number') { key = e.charCode; }
		else { return; }
		
		var escapeKeys = '8,9,13,35,36,37,39,46';

		if ((!(key >= 48 && key <= 57)) && (! (key >= 96 && key <= 105)) && escapeKeys.indexOf(key) < 0)
		{
			e.returnValue = false;
			return false;
		}
		else if (obj.value.length >= mascara.length) 
		{
			obj.value = obj.value.substr(0, mascara.length);

			if(escapeKeys.indexOf(key) > -1)
			{
				return true;
			}

			e.returnValue = false;
			return false;
		} else if (mascara.charAt(obj.value.length)!='#' && escapeKeys.indexOf(key) < 0)
		{
			obj.value = obj.value + mascara.charAt(obj.value.length);
		}
		/*if (mascara.charAt(obj.value.length+1)!='#' && escapeKeys.indexOf(key) < 0)
		{
			obj.value = obj.value + mascara.charAt(obj.value.length+1);
		}*/
	}
	catch(msgErr)
	{
		// Ignora o erro de validacao das teclas
		if (msgErr.number != -2147024891)
		{
			msgErr.description = "Erro na função Textbox_Mask()\n" + msgErr.description;
			throw msgErr;
		}
	}
}

// Fixes para o janela Modal
function fixDialog()
{
	// just for dialogs, else quit
	try
	{
		if(dialogArguments==undefined)
		{
			return
		}
	}
	catch(e)
	{
		return
	}

	// name window, so we can fix targeting
	if(window.name=='')
	{
		window.name = "winDialog";
	}

	goToURL = function(p_strURL)
	{
		var oLink = document.createElement("A");
		document.body.insertAdjacentElement('beforeEnd', oLink);
		with(oLink)
		{
			href = p_strURL;
			target = window.name;
			click();
		}
	}

	// fix window.navigate()
	window.navigate = goToURL; 
	// fix window.location.assign()
	window.location.assign = goToURL; 
	// fix window.location.reload()
	window.location.reload = function(){window.navigate(window.location.href)}
	// fix window.location.replace() (SORTA!)
	window.location.replace = goToURL; 

	// if window object was passed to vArguments, hook up as window.opener
	// eg:  showModalDialog(sURL, window, sFeatures)
	var bWasPassedWindow = false;
	try
	{
		bWasPassedWindow = dialogArguments.location!=undefined;
	}
	catch(e){}

	if(bWasPassedWindow)
	{
		// fix opener
		window.opener = dialogArguments;

		// fix cookies (make available in dialog) <--- seems to work fine without this too?
		document.cookie = dialogArguments.document.cookie;
	}

	// fix document stuff
	attachEvent("onload", function()
	{
		// fix form submissions and link openings
		// insert base tag with target (should be faster & work on dynamically created links)
		var oHead = document.getElementsByTagName("HEAD")[0];
		var oBase = document.createElement("BASE");
		oBase.target = window.name;
		oHead.insertAdjacentElement('AfterBegin', oBase);

		// fix U accelerator
		var colUtags = document.all.tags("U");
		for(var u=0; u<colUtags.length; u++)
		{
			if(colUtags[u].style.accelerator)
			{
				colUtags[u].style.textDecoration = 'none';
			}
		}
	});

	// Exibe a ampulheta enquanto processando
	attachEvent("onbeforeunload", function() { document.body.style.cursor = 'wait'; });
	attachEvent("onunload", function() { document.body.style.cursor = 'wait'; });

	//document.attachEvent("onmouseup", function(){if (document.selection) alert(document.selection.createRange().boundingLeft);});
	/*document.attachEvent("onmouseup", function()
	{
		var range
		var x = window.event.clientX
		var y = window.event.clientY

		if (window.event.srcElement.parentTextEdit)
		{
			range = window.event.srcElement.parentTextEdit.createTextRange()
			range.collapse()
			range.moveToPoint(x, y)
			range.expand("word")
			range.select()
		}
	});*/

	copiar = function(x, y, isText)
	{
		if (!isText)
		{
			var range = document.body.createTextRange();
			range.collapse();
			range.moveToPoint(x, y);
			range.expand("word");
			range.select();
			range.execCommand("Copy");
			alert('Texto copiado.');
		}
	}

	//document.attachEvent("onMouseDrag", function() { alert('a'); });

	// enable basics of normal context (right-click) menu
	document.attachEvent("oncontextmenu", function()
	{
		var strMenuHTML =
			'<html><body>' +
			'<style type="text/css">\r\n' +
			'BODY {background:buttonface;  padding:2px; font:x-small Tahoma, sans-serif; font-size:80%;}\r\n' +
			'A {padding:0 4px 0 4px; text-decoration:none; color:buttontext; WIDTH:115%; display:block; cursor:default;}\r\n' +
			'A:hover {background:highlight; color:highlighttext;}\r\n' +
			'</style>\r\n' +
			'<script language="Javascript">\r\n' +
			'function reload(){parent.location=parent.location.href}\r\n' +
			'</script>\r\n' +
			'<a href="#" onclick="parent.print()">Imprimir...</a>\r\n' +
			'<a href="#" onclick="parent.location.reload()">Atualizar</a>\r\n' +
			'<a href="#" onclick="parent.copiar(' + event.clientX + ',' + event.clientY + ',' + event.srcElement.isTextEdit + ')">Copiar</a>\r\n' +
			'</body></html>';


		var oPop = window.createPopup();
		var oPopBody = oPop.document.body;
		oPopBody.style.cssText = 'border:2px threedhighlight outset;';
		oPopBody.innerHTML = strMenuHTML;
		oPop.show(event.clientX, event.clientY, 100, 60, document.body);
		return false;
	})
}

function Trim(cadeia){
	// Garante que os dados tratados estejam no formato de String
	cadeia = String( cadeia );
	
	while(cadeia.charAt(0) == " " )
		{
		cadeia = cadeia.substr(1); // Toda a string menos o caracter 0, que é branco.
		}
	while( cadeia.lastIndexOf(" ") == cadeia.length - 1 && cadeia.length > 0)
		{
		cadeia = cadeia.substring(0, cadeia.lastIndexOf(" ")); // do primeiro caracter até o penultimo, ver definição da .substring()
		}
	
	return cadeia;
	}
	