/********************************************************************** 
Função para detectar o Browser
Objetivos :
	- Detectar o Browser
Parâmetros :
Exemplo : 
	OnClick:return DetectBrowser();
/**********************************************************************/ 

function DetectBrowser()

{

	if(window.navigator.appName == "NetScape")
	{
		return "NS";
	}
	
	else if (window.navigator.appName == "Microsoft Internet Explorer")
	{
		return "MS";
	}
	else
	{
		return "NS";
	}

}
/********************************************************************** 
Função para abrir janelas em Modal
Objetivos :
	- Abrir janelas em Modal
Parâmetros :
strURL = Arquivo ou URL da Net a ser aberta, intWidth e intHeight = Altura
e Largura da janela
Exemplo : 
	OnClick:javascript:openModalWindow('meuarquivo.htm', window, 500, 500);
/**********************************************************************/ 

function openModalWindow(strURL, strArgument, intWidth, intHeight)
{

	var intTop = ((screen.height - intHeight) / 2);
	var intLeft = ((screen.width - intWidth) / 2);

	var strEnderec=strURL;
	
	var strAjustesIE='status=0; help=0; center:yes; dialogWidth:'+intWidth+'px; dialogHeight:'+intHeight+'px';
	var strAjustesNS='width='+intWidth+', height='+intHeight+', status=0, scrollbars=1, menubar=0, dependent=1, left='+intLeft+', top='+intTop;

	with (window.navigator)
	{
		switch (appName)
		{
			case 'Microsoft Internet Explorer':
				var x = window.showModalDialog(strEnderec, strArgument ,strAjustesIE);
				break;

			case 'Netscape':
				var x = window.open(strEnderec, 'Default', strAjustesNS);
				break;
		}
	}
}


function openWindow(strURL, strArgument, intWidth, intHeight)
{

	var intTop = ((screen.height - intHeight) / 2);
	var intLeft = ((screen.width - intWidth) / 2);

	var strEnderec=strURL;
	
	var strAjustesIE='status=0; help=0; center:yes; dialogWidth:'+intWidth+'px; dialogHeight:'+intHeight+'px';
	var strAjustesNS='width='+intWidth+', height='+intHeight+', status=0, scrollbars=1, menubar=0, dependent=1, left='+intLeft+', top='+intTop;

	with (window.navigator)
	{
		switch (appName)
		{
			case 'Microsoft Internet Explorer':
				var x = window.open(strEnderec, 'Default', strAjustesNS);
				if (x)
				{
					//Funciona
				}
				else
				{
					alert("Libere o bloqueador de pop-ups para visualizar este site!");
				}
				break;

			case 'Netscape':
				var x = window.open(strEnderec, 'Default', strAjustesNS);
				if (x)
				{
					//Funciona
				}
				else
				{
					alert("Libere o bloqueador de pop-ups para visualizar este site!");
				}
				break;
		}
	}
}
/********************************************************************** 
Função de validação de campos do tipo Data
Objetivos :
	- Aceitar somente datas do tipo : dd/mm/aaaa
Parâmetros :
	objeto		-> Nome do campo de formulário (Usar this)
Exemplo : 
	OnChange    ValidaData(this);
/**********************************************************************/ 
function ValidaData(objeto) 
{

	var DataString	= objeto.value;
	var DataArray	= DataString.split("/");  
	var Flag=true; 

	if (DataArray.length != 3) 
		Flag=false; 
	else 
		{
			if (DataArray.length==3) 
			{
				var dia = DataArray[0], mes = DataArray[1], ano = DataArray[2]; 

				if (((Flag) && (ano<1000) || ano.length>4)) 
					Flag=false; 
				
				if (Flag) 
				{ 
					verifica_mes = new Date(mes+"/"+dia+"/"+ano); 
					if (verifica_mes.getMonth() != (mes - 1)) 
						Flag=false; 
				} 
			} 
			else 
				Flag=false; 
		} 
return Flag;
} 

/********************************************************************** 
Função de formatação de campos do tipo Data
Objetivos :
	- Mascarar a entrada de dados no formato : dd/mm/aaaa
Parâmetros :
	objeto		-> Nome do campo de formulário (Usar this)
	teclapress	-> Tecla pressionada (Usar event)
Exemplo : 
	OnKeyDown    FormataData(this,event);
Requirido :
	Função ValidaData
/**********************************************************************/ 
function FormataData(objeto,teclapress)
{
	var tecla = teclapress.keyCode;

	if(((window.event.keyCode == 13) || (window.event.keyCode == 9))&&objeto.value != "")
	{
		if(!(ValidaData(objeto)))
			{
				window.event.cancelBubble = true;
				window.event.returnValue = false;
				alert("Data Inválida");
				objeto.value = "";
				objeto.focus();
			}
	}

	if (( tecla == 8 || tecla == 88 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 )&& objeto.value.length < (10))
    {
		vr = objeto.value;
		vr = vr.replace( "/", "" );
		vr = vr.replace( "/", "" );
		tam = vr.length;

		if (tam < 8)
			{
				if (tecla != 8) {tam = vr.length + 1 ;}
			}
		else
			{
				window.event.cancelBubble = true;
				window.event.returnValue = false;
			}
		
		if ((tecla == 8) && (tam > 1))
			{
				tam = tam - 1 ;
				objeto.value = vr.substr(0,tam);
				window.event.cancelBubble = true;
				window.event.returnValue = false;
			}
				if ( tam <= 4 && tecla != 8){ 
			 		objeto.value = vr ; }

				if ( (tam >= 4) && (tam <= 6) ){
			 		objeto.value = vr.substr(0, tam - 4) + '/' + vr.substr( tam - 4, 4 ); }

				if ( (tam >= 6) && (tam <= 8) ){
					objeto.value = vr.substr(0, tam - 6 ) + '/' + vr.substr( tam - 6, 2 ) + '/' + vr.substr( tam - 4, 4 ); }

				if ((tam == (8)) && tecla != 8)
					{
						if(tecla >=96 && tecla <=105)
							{
								tecla = tecla - 48;
							}

						objeto.value = objeto.value + (String.fromCharCode(tecla));
						window.event.cancelBubble = true;
						window.event.returnValue = false;

						if (!(ValidaData(objeto)))
							{
								alert("Data Inválida");
								objeto.value = "";
								objeto.focus();
							}
					}
	}
	else if((window.event.keyCode != 8) && (window.event.keyCode != 9) && (window.event.keyCode != 13) && (window.event.keyCode != 35) && (window.event.keyCode != 36) && (window.event.keyCode != 46))
		{
			event.returnValue = false;
		}
}

/********************************************************************** 
Função de Trim em Todos os Campos
Objetivos :
	- Limpar espaços nos valores de todos os campos
Parâmetros :
	objeto		-> Nome do formulário 
Exemplo : 
	OnSubmit    allTrim(document.frmPost);
/**********************************************************************/ 
String.prototype.trim = function() 
{
  var x=this;
  x=x.replace(/^\s*(.*)/, "$1");
  x=x.replace(/(.*?)\s*$/, "$1");
  return x;
}

function allTrim(formName) 

{
	for (var i=0; i<formName.elements.length; i++)
	{
		var obj = formName.elements[i];
		if (obj.type == 'text') 
		{
			obj.value = obj.value.trim();
		}
	 }
}
//-->

/********************************************************************** 
Função de UpperCase em Todos os Campos
Objetivos :
	- Passar valor UpperCase para todos os campos
Parâmetros :
	objeto		-> Nome do formulário 
Exemplo : 
	OnSubmit    allUpper(document.frmPost);
/**********************************************************************/ 
function allUpper(formName) 
{
	for (var i=0; i<formName.elements.length; i++) 
	{
		var obj = formName.elements[i];
		if (obj.type == 'text')
		{
			obj.value = obj.value.toUpperCase();
		}
	}
}
//-->

/********************************************************************** 
Função de Valor Zero em Todos os Campos
Objetivos :
	- Passar valor Zero para todos os campos
Parâmetros :
	objeto		-> Nome do formulário 
Exemplo : 
	OnSubmit    allZeroCurrency(frmPost);
/**********************************************************************/ 
function allZeroCurrency(formName) 
{
	for (var i=0; i<formName.elements.length; i++) 
	{
		var obj = formName.elements[i];
		if (obj.type == 'text')
		{
			if (obj.value == '')
			{
				obj.value = '0.00';
			}
		}
	}
}
//-->

/********************************************************************** 
Função de limpar em Todos os Campos
Objetivos :
	- Passar vazio para todos os campos
Parâmetros :
	objeto		-> Nome do formulário 
Exemplo : 
	OnSubmit    allEmpty(frmPost);
/**********************************************************************/ 
function allEmpty(formName) 
{
	for (var i=0; i<formName.elements.length; i++) 
	{
		var obj = formName.elements[i];
		if (obj.type == 'text')
		{
			if (obj.value == '')
			{
				obj.value = '';
			}
		}
	}
}
//-->


/********************************************************************** 
Função de Formato em Moeda
Objetivos :
	- Passar valor de moeda para os campos
Parâmetros :
	fld é o campo a ser formatado, milSep é o separador de milhar 
	e decSep é o separador decimal
Exemplo : 
	OnSubmit    onKeyPress="return(currencyFormat(this,'.',',',event))";
/**********************************************************************/ 
function currencyFormat(fld, milSep, decSep, e) {
	var sep = 0;
	var key = '';
	var i = j = 0;
	var len = len2 = 0;
	var strCheck = '0123456789';
	var aux = aux2 = '';
	var whichCode = (window.Event) ? e.which : e.keyCode;
	if (whichCode == 13) return true; 
	key = String.fromCharCode(whichCode);  
	if (strCheck.indexOf(key) == -1) return false; 
	len = fld.value.length;
	for(i = 0; i < len; i++)
	if ((fld.value.charAt(i) != '0') && (fld.value.charAt(i) != decSep)) break;
	aux = '';
	for(; i < len; i++)
	if (strCheck.indexOf(fld.value.charAt(i))!=-1) aux += fld.value.charAt(i);
	aux += key;
	len = aux.length;
	if (len == 0) fld.value = '';
	if (len == 1) fld.value = '0'+ decSep + '0' + aux;
	if (len == 2) fld.value = '0'+ decSep + aux;
	if (len > 2) 
	{
		aux2 = '';
		for (j = 0, i = len - 3; i >= 0; i--) 
		{
			if (j == 3) 
			{
				aux2 += milSep;
				j = 0;
			}
			aux2 += aux.charAt(i);
			j++;
		}
		fld.value = '';
		len2 = aux2.length;
		for (i = len2 - 1; i >= 0; i--)
		fld.value += aux2.charAt(i);
		fld.value += decSep + aux.substr(len - 2, len);
	}
	return false;
}
//-->

function onlyNumber(e)
{
	if (document.all) 
		var tecla = event.keyCode;
	else if(document.layers) // Nestcape
	var tecla = e.which;
	if (tecla > 47 && tecla < 58) // numeros de 0 a 9
		return true;
	else
	{
		if (tecla != 8) // backspace
			event.keyCode = 0;
			//return false;
		else
			return true;
	}
}


// #########################FUNÇÕES DE TOOLTIPTEXT #####################################
//<<------------------Costumized Tooltip----------->>

	//--this line creates the Tooltip Layer-->>
	document.write("<div id='tip' style='position:absolute;visibility:hidden;left:100;top:100' ><table borderstyle=outset border=1 bgcolor=#FFFFCC bordercolor=#000000><td id=message><br></td></table></div>"); 

	function TipShow(msg)
	{
		document.all.message.innerHTML="<font color=#000000 size=2 face=tahoma>"+msg+"</font>";
		twnd=document.all.tip;
		twnd.style.visibility="visible";
		twnd.style.top=event.y+19+document.body.scrollTop;
		twnd.style.left=event.x-2+document.body.scrollLeft;
	}

	function TipHide(){twnd.style.visibility="hidden";}


//<<------------------Draggable Window---------->>

	var on=0;

	function dragw()
	{
		drg=document.all.aa;
		ondown1=drg.style.pixelTop-document.body.scrollTop;
		ondown2=drg.style.pixelLeft-document.body.scrollLeft;
		x=event.x;
		y=event.y;
		on=1;
		document.onmousemove=drgg;
	}


	function drgg()
	{
		if(on==1)
		{
			drg.style.pixelTop=ondown1+event.y-y+document.body.scrollTop;
			drg.style.pixelLeft=ondown2+event.x-x+document.body.scrollLeft;
			
		}
	}

	function closeit(){document.all.aa.style.visibility="hidden";}

//<<------------------Ticker Tape----------->>

	speed=1;
	
	function ticker()
	{

		wnd1=document.all.bb;
		wnd2=document.all.bb2;
		wnd1.style.left=parseInt(wnd1.style.left)-speed;
		
		if(parseInt(wnd1.style.left)<"-"+document.all.tmsg.width)
		{
			wnd1.style.left=document.all.bb2.offsetWidth;
		}

		setTimeout("ticker();",10);

	}
// #########################FUNÇÕES DE TOOLTIPTEXT #####################################

	// Função Right do VB em JavaScript
	function Right(str, n)
	{
		if (n <= 0)
		{
		   return "";
		}
		else if (n > String(str).length)
		{
		   return str;
		}
		else 
		{
		   var iLen = String(str).length;
		   return String(str).substring(iLen, iLen - n);
		}
	}

	// Função Left do VB em JavaScript
	function Left(str, n)
	{
		if (n <= 0)
		{
			return "";
		}
		else if (n > String(str).length)
		{
			return str;
		}
		else
		{
			return String(str).substring(0,n);
		}
	}

    function move_i(what) 
	{ 
		what.style.background='#FFFFC6';
	}
    function move_o(what) 
	{ 
		what.style.background='none'; 
	}

	function validaCPF(strCPF) 
	{
		cpf = strCPF;
		erro = new String;
		if (cpf.length < 11) erro += "Sao necessarios 11 digitos para verificacao do CPF! \n\n"; 
		var nonNumbers = /\D/;
		if (nonNumbers.test(cpf)) erro += "A verificacao de CPF suporta apenas numeros! \n\n"; 
		if (cpf == "00000000000" || cpf == "11111111111" || cpf == "22222222222" || cpf == "33333333333" || cpf == "44444444444" || cpf == "55555555555" || cpf == "66666666666" || cpf == "77777777777" || cpf == "88888888888" || cpf == "99999999999")
		{
			erro += "Numero de CPF invalido!"
		}
		var a = [];
		var b = new Number;
		var c = 11;
		for (i=0; i<11; i++)
		{
			a[i] = cpf.charAt(i);
			if (i < 9) b += (a[i] * --c);
		}
		if ((x = b % 11) < 2) 
		{ 
			a[9] = 0 
		} 
		else 
		{ 
			a[9] = 11-x 
		}
		b = 0;
		c = 11;
		for (y=0; y<10; y++) b += (a[y] * c--); 
		if ((x = b % 11) < 2) 
		{ 
			a[10] = 0; 
		} 
		else 
		{ 
			a[10] = 11-x; 
		}
		if ((cpf.charAt(9) != a[9]) || (cpf.charAt(10) != a[10]))
		{
			erro +="Digito verificador com problema!";
		}
		if (erro.length > 0)
		{
			//alert(erro);
			return false;
		}
		return true;
	}
	
	function validaCNPJ(strCNPJ) {
			CNPJ = strCNPJ;
			erro = new String;
			if (CNPJ.length < 14) erro += "É necessario preencher corretamente o número do CNPJ! \n\n"; 
			//if ((CNPJ.charAt(2) != ".") || (CNPJ.charAt(6) != ".") || (CNPJ.charAt(10) != "/") || (CNPJ.charAt(15) != "-"))
			//{
			//if (erro.length == 0) erro += "É necessário preencher corretamente o número do CNPJ! \n\n";
			//}
			//substituir os caracteres que não são números
		  if(document.layers && parseInt(navigator.appVersion) == 4){
				  //x = CNPJ.substring(0,2);
				  //x += CNPJ. substring (3,6);
				  //x += CNPJ. substring (7,10);
				  //x += CNPJ. substring (11,15);
				  //x += CNPJ. substring (16,18);
				  CNPJ = CNPJ; 
		  } else {
				//  CNPJ = CNPJ. replace (".","");
				//  CNPJ = CNPJ. replace (".","");
				//  CNPJ = CNPJ. replace ("-","");
				//  CNPJ = CNPJ. replace ("/","");
				CNPJ = CNPJ;
		  }
		  var nonNumbers = /\D/;
		  if (nonNumbers.test(CNPJ)) erro += "A verificação de CNPJ suporta apenas números! \n\n"; 
		  var a = [];
		  var b = new Number;
		  var c = [6,5,4,3,2,9,8,7,6,5,4,3,2];
		  for (i=0; i<12; i++){
				  a[i] = CNPJ.charAt(i);
				  b += a[i] * c[i+1];
			}
		  if ((x = b % 11) < 2) { a[12] = 0 } else { a[12] = 11-x }
		  b = 0;
		  for (y=0; y<13; y++) {
				  b += (a[y] * c[y]); 
		  }
		  if ((x = b % 11) < 2) { a[13] = 0; } else { a[13] = 11-x; }
		  if ((CNPJ.charAt(12) != a[12]) || (CNPJ.charAt(13) != a[13])){
				  erro +="Dígito verificador com problema!";
		  }
		  if (erro.length > 0){
				  //alert(erro);
				  return false;
		  } else {
				  //alert("CNPJ valido!");
		  }
		  return true;
	}
	
    function move_i(what) 
	{ 
		what.style.background='#FFFFC6';
	}
    function move_o(what) 
	{ 
		what.style.background='none'; 
	}

/********************************************************************** 
Função para remover elementos da tela
Objetivos :
	- Remover Elementos
Parâmetros :
Exemplo : 
	window.onbeforeprint=RemoveElements; (O objeto deve ter o id como idRemove
/**********************************************************************/ 

function RemoveElements()
{
	document.getElementById('idRemove').style.display='none';
	alert("Para imprimir este documento, clique no item 'Imprimir Busca', na tela anterior.");
	window.close();
}

/********************************************************************** 
Função para remover elementos da tela
Objetivos :
	- Remover Elementos
Parâmetros :
Exemplo : 
	window.onbeforeprint=RemoveElementsAll; Qualquer objeto na tela
/**********************************************************************/ 

function RemoveElementsAll()
{
	for(i=0;i<document.all.length;i++)
	{
		if(document.all[i].style.visibility!="hidden")
		{
			document.all[i].style.visibility="hidden";document.all[i].id="hp_id"
		}
	}
}


/********************************************************************** 
Função para Desabilitar o botão direito do mouse
Objetivos :
	- Desabilitar o botão direito do mouse
Parâmetros :
Exemplo : 
	disableRightClick();
/**********************************************************************/ 
function disableRightClick(e)
{
  var message = "Resultado da busca emitido automaticamente.";
  
  if(!document.rightClickDisabled) // initialize
  {
	if(document.layers) 
	{
	  document.captureEvents(Event.MOUSEDOWN);
	  document.onmousedown = disableRightClick;
	}
	else document.oncontextmenu = disableRightClick;
	return document.rightClickDisabled = true;
  }
  if(document.layers || (document.getElementById && !document.all))
  {
	if (e.which==2||e.which==3)
	{
	  alert(message);
	  return false;
	}
  }
  else
  {
	alert(message);
	return false;
  }
}
