﻿// Funcoes genericas do sistema BDM

// 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)
			{
				verificarTab(document.getElementById(controle), 1)
				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;
	}
}

// Verifica se o controle pertence a alguma tab
function verificarTab(controle, indice)
{
	try
	{
		if (getParent(controle, indice).id.toLowerCase().indexOf('tab_') == 0)
		{
			var i = tabPane.getIndexById(getParent(controle, indice).id);
			if (i != -1)
			{
				tabPane.setSelectedIndex(i);
			}
		}
		else if (getParent(controle, indice).tagName.toLowerCase() != "form")
		{
			verificarTab(controle, indice+1)
		}
	}
	catch(msgErr)
	{
		msgErr.description = "Erro na função verificarTab()\n" + msgErr.description;
		throw msgErr;
	}
}

// Move o foco para a TabPage
function tabPaneFocus(tabPaneId)
{
	try
	{
		var i = tabPane.getIndexById(tabPaneId);
		if (i != -1)
		{
			tabPane.setSelectedIndex(i);
		}
	}
		catch(msgErr)
	{
		msgErr.description = "Erro na função tabPaneFocus()\n" + msgErr.description;
		throw msgErr;
	}
}

// Obtem o pai de um controle, no nivel informado
function getParent(obj,level)
{
	try
	{
		return (level==0) ? obj : getParent(obj.parentElement,level-1);
	}
	catch(msgErr)
	{
		msgErr.description = "Erro na função getParent()\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;
	}
}

// Valida os caracteres (',",<,>)
function ValidarTecla()
{
	try
	{
		var tecla=window.event.keyCode;
		var shif=window.event.shiftKey
		if ((shif && tecla==188) ||(shif && tecla==190) || (shif && tecla==192) || (tecla==192))
		{
			event.keyCode=0;
			event.returnValue=false;
		}
	}
	catch(msgErr)
	{
		msgErr.description = "Erro na função ValidarTecla()\n" + msgErr.description;
		throw msgErr;
	}
}

// Implementa o AutoTab
function AutoTab(input, e, nextField)
{
	try
	{
		var keyCode = e.keyCode;
		var filter = [0,8,9,16,17,18,37,38,39,40,46];
		var len = input.maxLength;
		if(input.value.length >= len && !containsElement(filter,keyCode))
		{
			input.value = input.value.slice(0, len);
			var control = document.getElementById(nextField);
			if (control != null)
			{
				control.focus();
			}
		}
	}
	catch(msgErr)
	{
		msgErr.description = "Erro na função AutoTab()\n" + msgErr.description;
		throw msgErr;
	}
}

// Usada junto com a função AutoTab
function containsElement(arr, ele)
{
	try
	{
		var found = false, index = 0;
		while(!found && index < arr.length)
		{
			if(arr[index] == ele)
			{
				found = true;
			}
			else
			{
				index++;
			}
		}

		return found;
	}
	catch(msgErr)
	{
		msgErr.description = "Erro na função containsElement()\n" + msgErr.description;
		throw msgErr;
	}
}

// Valida CNPJ
function ValidaCNPJ(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 == 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;
	}
}

// Formata numero
function Textbox_KeyDown(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;
		}
	}
}

// Valida a mascara
function Textbox_Mask(pControle, pMascara)
{
	try
	{
		var shift = window.event.shiftKey;
		var tecla = window.event.keyCode;
		if(!TeclaDeControle(tecla))
		{
			curPos = textPos(pControle);
			if (tecla == 46)
			{
				pControle.value = pControle.value.substring(0, curPos -1);
			}
			else
			{
				if (!validChar(pControle, pMascara, curPos))
				{
					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_Mask()\n" + msgErr.description;
			throw msgErr;
		}
	}
}

// Valida se o caracter pertence a mascara
function validChar(pControle, pMascara, pPos)
{
	try
	{
		var shift = window.event.shiftKey;
		var tecla = window.event.keyCode;
		if (pControle.value.length >= pMascara.length)
		{
			return false
		}
		charMask = pMascara.substring(pPos - 1, pPos - 0);
		if (charMask == '#')
		{
			if(shift || (!(tecla >= 48 && tecla <= 57)) && (! (tecla >= 96 && tecla <= 105)))
			{
				return false;
			}
		}
		else if (charMask == 'X')
		{
			if(!(tecla >= 65 && tecla <= 90))
			{
				return false;
			}
			else
			{
				return true;
			}
		}
		else if (charMask == '@')
		{
			return true;
		}
		else
		{
			lastchar = pControle.value.substring(pControle.value.length-1,pControle.value.length)
			if (lastchar==charMask)
			{
				event.keyCode = 0;
				event.returnValue = false;
				return false;
			}

			pControle.value = pControle.value + charMask;
			if (!validChar(pControle, pMascara, pPos + 1))
			{
				event.keyCode = 0;
				event.returnValue = false;
			}
		}
		return true;
	}
	catch(msgErr)
	{
			// Ignora o erro de validacao das teclas
		if (msgErr.number != -2147024891)
		{
			msgErr.description = "Erro na função validChar()\n" + msgErr.description;
			throw msgErr;
		}
	}
}

// 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;
	}
}

// Desabilita a tecla Enter no campo
function handleEnter(field, event)
{
	try
	{
		var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
		if (keyCode == 13)
		{
			var i;
			for (i = 0; i < field.form.elements.length; i++)
			{
				if (field == field.form.elements[i])
				{
					break;
				}
			}

			for (i = i+1; i < field.form.elements.length; i++)
			{
				if (!field.form.elements[i].disabled)
				{
					try
					{
						field.form.elements[i].focus();
						break;
					}
					catch(err) {} // Ignora o campo e procura o proximo
				}
			}

			return false;
		}
		else
		{
			return true;
		}
	}
	catch(msgErr)
	{
		msgErr.description = "Erro na função handleEnter()\n" + msgErr.description;
		throw msgErr;
	}
}

// Abre Tela de Ajuda da aplicacao
function AbrePopupAjuda(Pagina)
{
	try
	{
		var retVal = window.showModalDialog(Pagina, window ,'dialogHeight=200px;dialogWidth=400px; dialogTop: px; dialogLeft: px; edge: Sunken; center: Yes; resizable: No; status: No; help: No; scroll: Yes');
	}
	catch (msgErr)
	{
		msgErr.description = "Erro na função AbrePopupAjuda()\n" + msgErr.description;
		throw msgErr;
	}
}

//Funcoes do Editor HTML WYSIWYG

var type;
var isHTMLMode = false
var intHCount  = 0;
var intNCount  = 0;

function button_over(eButton)
{
	try
	{
		eButton.style.backgroundColor  = "LightSlateGray";
		eButton.style.borderColor      = "darkblue darkblue darkblue darkblue";
	}
	catch (msgErr)
	{
		msgErr.description = "Erro na função button_over(eButton)\n" + msgErr.description;
		throw msgErr;
	}
}

function button_out(eButton)
{
	try
	{
		eButton.style.backgroundColor = "threedface";
		eButton.style.borderColor     = "threedface";
	}
	catch (msgErr)
	{
		msgErr.description = "Erro na função button_out(eButton)\n" + msgErr.description;
		throw msgErr;
	}
}

function button_down(eButton)
{
	try
	{
		eButton.style.backgroundColor = "#8494B5";
		eButton.style.borderColor     = "darkblue darkblue darkblue darkblue";
	}
	catch (msgErr)
	{
		msgErr.description = "Erro na função button_down(eButton)\n" + msgErr.description;
		throw msgErr;
	}
}

function button_up(eButton)
{
	try
	{
		eButton.style.backgroundColor = "#B5BDD6";
		eButton.style.borderColor     = "darkblue darkblue darkblue	darkblue";
		eButton                       = null;
	}
	catch (msgErr)
	{
		msgErr.description = "Erro na função button_up(eButton)\n" + msgErr.description;
		throw msgErr;
	}
}

/*function document.onreadystatechange()
{
	try
	{
		EditorCorpo.document.designMode = "On";
	}
	catch (msgErr)
	{
		msgErr.description = "Erro na função document.onreadystatechange()\n" + msgErr.description;
		throw msgErr;
	}
}*/

function cmdExec(cmd,opt)
{
	try
	{
		if (isHTMLMode)
		{
			alert("A Formatação ocorre somente no modo Normal");
			return;
		}

		EditorCorpo.focus();
		EditorCorpo.document.execCommand(cmd,"",opt);
		EditorCorpo.focus();
	}
	catch (msgErr)
	{
		msgErr.description = "Erro na função cmdExec(cmd,opt)\n" + msgErr.description;
		throw msgErr;
	}
}

function ChangeImage (ImageName,FileName)
{
	try
	{
		document[ImageName].src = FileName;
	}
	catch (msgErr)
	{
		msgErr.description = "Erro na função ChangeImage (ImageName,FileName)\n" + msgErr.description;
		throw msgErr;
	}
}

function setMode(Nbut, Hbut)
{
	try
	{
		var sTmp;
		isHTMLMode   = Hbut;
		isNormalMode = Nbut;

		if (Hbut == 1)
		{
			intHCount++;
			intNCount = 0;
		}

		if (Nbut == 1)
		{
			intNCount++;
			intHCount = 0;
		}

		if (isHTMLMode && intHCount == 1)
		{
			sTmp                                = EditorCorpo.document.body.innerHTML;
			EditorCorpo.document.body.innerText = sTmp;
			ChangeImage ('HTMLbut','images/HTML_on.jpg');
			ChangeImage ('Normalbut','images/Normal_off.jpg');
			return true;
		}

		if (isNormalMode && intNCount == 1)
		{
			sTmp                                = EditorCorpo.document.body.innerText;
			EditorCorpo.document.body.innerHTML = sTmp;
			ChangeImage ('HTMLbut','images/HTML_off.jpg');
			ChangeImage ('Normalbut','images/Normal_on.jpg');
			return true;
		}

		EditorCorpo.focus();
	}
	catch (msgErr)
	{
		msgErr.description = "Erro na função setMode(Nbut, Hbut)\n" + msgErr.description;
		throw msgErr;
	}
}

function createLink()
{
	try
	{
		if (isHTMLMode)
		{
			alert("Por Favor desmarque 'Editar HTML'");
			return;
		}

		cmdExec("CreateLink");

	}
	catch (msgErr)
	{
		msgErr.description = "Erro na função createLink()\n" + msgErr.description;
		throw msgErr;
	}
}

function foreColor()
{
	try
	{
		var arr = showModalDialog("PalhetaDeCores.htm", window ,"font-family:Verdana; font-size:12; dialogWidth:18; dialogHeight:18" );
		if (arr != null)
		{
			cmdExec("ForeColor",arr);
		}
	}
	catch (msgErr)
	{
		msgErr.description = "Erro na função foreColor()\n" + msgErr.description;
		throw msgErr;
	}
}

function setImage()
{
	try
	{
		var imgSrc = " ";
		var flag   = 0;

		while (imgSrc == " ")
		{
			imgSrc = prompt('Entre com o endereço da imagem com o nome do arquivo.', ''); 

			if (imgSrc == " ")
			{
				alert("Por Favor entre com o Endereco (URL)");
			}

			if (imgSrc != "")
			{
				cmdExec('insertimage', imgSrc);
			}
		}

	}
	catch (msgErr)
	{
		msgErr.description = "Erro na função setImage()\n" + msgErr.description;
		throw msgErr;
	}
}

function ShowCM(t,headerText)
{
	try
	{

		EditorCorpo.document.designMode = 'On';

		if (divContent.style.display == "block")
		{
			divContent.style.display = "none";
		}
		else
		{
			divContent.style.display = "block";
		}

		type                = t;
		spnHeader.innerText = headerText;

		if (document.getElementById(type).value != '')
		{
			EditorCorpo.document.body.innerHTML = document.getElementById(type).value;
		}

	}
	catch (msgErr)
	{
		msgErr.description = "Erro na função ShowCM(t,headerText)\n" + msgErr.description;
		throw msgErr;
	}
}

function fillIframe(CampoOculto)
{
	try
	{
		EditorCorpo.document.body.innerHTML = document.getElementById(CampoOculto).value;
	}
	catch (msgErr)
	{
		msgErr.description = "Erro na função fillIframe()\n" + msgErr.description;
		throw msgErr;
	}
}

function ClearIFrame()
{
	try
	{
		EditorCorpo.document.body.innerHTML = '';
	}
	catch (msgErr)
	{
		msgErr.description = "Erro na função ClearIFrame()\n" + msgErr.description;
		throw msgErr;
	}
}

//Abrir Modal
function AbrirJanelaModal(pag, pAltura, pLargura)
{
	var m_caracteristicas = 'dialogHeight=' + pAltura + 'px;dialogWidth=' + pLargura + 'px; dialogTop: px; dialogLeft: px; edge: Sunken; center: Yes; resizable: No; status: No; help: No; scroll: Yes';
	window.showModalDialog(pag,window, m_caracteristicas)
}

//Abrir Popup
function AbrirJanela(pag, pAltura, pLargura)
{
	var CoordY = ((screen.height - pAltura)/2);
	var CoordX = ((screen.width - pLargura)/2);
	
	var m_caracteristicas = 'height=' + pAltura + ',width=' + pLargura + ',menubar=no,resizable=yes,scrollbars=no,status=no,toolbar=no,top=' + CoordY + ',left=' + CoordX;
	
	window.open(pag,'', m_caracteristicas);
}

// Cursor do mouse como ampulheta
function doHourglass()
{
	try
	{
		document.body.style.cursor = 'wait';
	}
	catch (msgErr)
	{
		msgErr.description = "Erro na função doHourglass()\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;
	})
}

var ModalDialogWindow;
var ModalDialogInterval;
var ModalDialog = new Object;

ModalDialog.value = '';
ModalDialog.eventhandler = '';

function ModalDialogMaintainFocus()
{
	try
	{
		if (ModalDialogWindow.closed)
		{
			window.clearInterval(ModalDialogInterval);
			eval(ModalDialog.eventhandler);
			return;
		}
		ModalDialogWindow.focus();
	}
	catch (everything) {}
}

function ModalDialogRemoveWatch()
{
	ModalDialog.value = '';
	ModalDialog.eventhandler = '';
}

var skipcycle = false

function fcsOnMe()
{
	if (!skipcycle)
	{
		window.focus();
	}
	mytimer = setTimeout('fcsOnMe()', 5);
}

function MenuGrid(colIndex)
{
	var strMenuHTML =
		'<html><body>' +
		'<style type="text/css">' +
		'BODY {background:buttonface; padding:2px; font:x-small Tahoma, sans-serif; font-size:80%;}' +
		'a {padding:0px 0 0px 0; text-decoration:none; color:buttontext; WIDTH:100%; display:block; cursor:default;}' +
		'a:hover {background:highlight; color:highlighttext;}' +
		'</style>' +
		'<a href="#" onclick="parent.location.hideColumn(colIndex)">Ocultar</a>\r\n' +
		'<a href="#" onclick="parent.">Reexibir</a>\r\n' +
		'</body></html>';


	var oPop = window.createPopup();
	var oPopBody = oPop.document.body;
	//oPopBody.style.cssText = 'border-width:thin;';
	oPopBody.innerHTML = strMenuHTML;
	oPop.show(event.clientX, event.clientY, 70, 40, document.body);
	return false;
}

function setupHeader(dataGrid)
{
	alert(dataGrid);
	var navRoot = document.getElementById(dataGrid);
	if (navRoot)
	{
		var tbody = navRoot.childNodes[0];
		var node = tbody.childNodes[0];

		for (j = 0; j < node.childNodes.length; j++)
		{
			column = node.childNodes[j];
			if (column.nodeName == "TD")
			{
				/*column.attachEvent("oncontextmenu", function()
				{
					var strMenuHTML = 
						'<html><body>' +
						'<style type="text/css">' +
						'BODY {background:buttonface;  padding:2px; font:x-small Tahoma, sans-serif; font-size:80%;}' +
						'a {padding:0 4px 0 4px; text-decoration:none; color:buttontext; WIDTH:115%; display:block; cursor:default;}' +
						'a:hover {background:highlight; color:highlighttext;}' +
						'</style>' +
						'<a href="#" onclick="parent.hideColumn(' + column.Index + ')">Ocultar</a>' +
						'<a href="#" onclick="parent.location.reload()">Reexibir</a>' +
						'</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, 70, 40, document.body);

					return false;
				})*/
			}
		}
	}
}

//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;
		
		var expReg = /^(([0-2]\d|[3][0-1])\/([0]\d|[1][0-2])\/[1-2][0-9]\d{2})$/;
	
        if (cData != '')
        {       
		
		    if (!(source.value.match(expReg)))
            {  
                    alert('Data inválida. Verifique o formato ou o dia informado. A data tem que estar neste formato dd/mm/aaaa');
			        source.focus();
			        return; 
            }
            
		    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 < 01)||(dia < 01 || dia > 30) && (  mes == 04 || mes == 06 || mes == 09 || mes == 11 ) || dia > 31)
			    {
				    situacao = false;
			    }

			    if (mes < 01 || mes > 12)
			    {
				    situacao = false;
			    }

			    if (mes == 2 && ( dia < 01 || 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;
	}
}

//AplicarMascara
function AplicarMascara(controle, mascara)
{
	var valor = controle.value;
	var tecla = window.event.keyCode;
	var letra = '';
	var letradig = valor.substring((valor.length - 1), valor.length);
	valor = valor.substring(0, (valor.length - 1));

  //Formatar Valor
	if (!(tecla == 8 || tecla == 37 || tecla == 39 || tecla == 46))
	{
		 letra = mascara.substring(valor.length, (valor.length + 1));
	
	   while(letra != "#")
	   {
		    valor += letra;
		    letra = mascara.substring(valor.length, (valor.length + 1));	
	   }
	
	   valor += letradig;

     if (mascara.length > valor.length)
     {
		   letra = mascara.substring(valor.length, (valor.length + 1));
		   while(letra != "#")
		   {
			   valor += letra;
		     letra = mascara.substring(valor.length, (valor.length + 1));	
		   }
	   }
	   controle.value = valor;
	}
}

function psaObjetoOnFocusCSS(oHtmlObj)
{
	oHtmlObj.className = "psaObjetoOnFocusCSS"
}

function psaObjetoOnBlurCSS(oHtmlObj,CSSName)
{
	oHtmlObj.className = CSSName
}

function showHide(vThis, vTabela)
{
	vSibling = document.getElementById(vTabela);
	
	if(vSibling.style.display == "none")
	{
		vThis.src="../../Images/ico_page/ico_minus.gif";
		vThis.alt = "Esconder";	
		vSibling.style.display = "block";
	}
	else 
	{
		vThis.src="../../Images/ico_page/ico_plus.gif";
		vThis.alt = "Mostrar";
		vSibling.style.display = "none";
	}
}

function ConsistirTecla()
{ 
	var tecla = window.event.keyCode;
	if (tecla == 39 || tecla == 34)
	{ 
			event.KeyCode = 0;
			event.returnValue = false;
	} 
} 
			
function ValidarNumero()
{ 
	var tecla = window.event.keyCode;
	if (48 > tecla || tecla > 57)
	{ 
			event.KeyCode = 0;
			event.returnValue = false;
	} 
} 

//Verifica o Tamanho da Tela
function ClassTopo()
{
    
   if (screen.width > 800)
   {
        return "resolucaoTopMaior";
   }
   else
   {
        return "resolucaoTopMedio"; 
   }
}

function ExecutarRetorno(Campo, Valor, Botao)
{
    var Controle = window.opener.document.getElementById(Campo);
    var btnSelecionar = window.opener.document.getElementById(Botao); 
     
    if (Controle != null)
    { 
        Controle.value = Valor;
          
        if (btnSelecionar != null)
        {
           window.close();
           btnSelecionar.click();
        }
        
         
    }
}

function FecharSecaoUpdatePanel()
{
     var prm = null;
        
     if (typeof(Sys) != undefined)
     { 
           prm = Sys.WebForms.PageRequestManager.getInstance();
           prm.abortPostBack();
     }
}




