/*
	Autor:	Marcelo Nozari / Liliane Silva
Descrição:	Scripts p/ soluções em ASP.NET, ASP
      Uso:	<script language="Javascript/javascript" src="scripts.js"></script>
*/

// -------------------------------------------------------------------- //
// ----------------- FUNÇÕES DE MANIPULAÇÃO DE TEXTO ------------------ //
// -------------------------------------------------------------------- //

/*
Descrição:	Função que bloqueia aspas simples e caracteres especiais
      Uso:	txt.Attributes.Add("onKeyPress","return BloqueiaAspaSimples(event)")
*/
function BloqueiaAspaSimples(event)
{
    Tecla = event.keyCode;
    
    
    /*
    if(Tecla == null)
        Tecla = event.keyCode;
    if((Tecla == 32) || (Tecla == 13) || (Tecla >= 65 && Tecla <= 90) || (Tecla >= 97 && Tecla <= 122) || (Tecla >= 48 && Tecla <= 57))
        return true;
	else
		return false;
	*/
	if(Tecla == null)
        Tecla = event.keyCode;
    if((Tecla != 39))
        return true;
	else
		return false;
}

/*
Descrição:	Utilizada apenas para fazer retornar os valore de "function Replace(valor,sub1,sub2)".
      Uso:	Replace(valor, sub1, sub2)
*/
function Botao(valor,sub1,sub2)
{
	var valor = Replace(valor,sub1,sub2);
	document.getElementById ('Text22').value = valor;
}

/*
Descrição:	Função p/ inibir o espaço no text e aspas simples
      Uso:	txt.Attributes.Add("onKeyPress", "return InibeEspaco()")
*/
function InibeEspaco()
{
	var Tecla = window.event.keyCode;
	event.cancelBubble = true;
	if((Tecla != 32) && (BloqueiaAspaSimples(event)))
		event.returnValue = true;
	else
		event.returnValue = false;
}

/*
Descrição:	Função que verificar se o email informado é válido
      Uso:	IsEmail('valor');
*/
function IsEmail(valor)
{
    if (valor.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) != -1)
        return true ;
    else
        return false ;
}

/*
Descrição:	Função p/ limitar o texto num campo TextArea
      Uso:	txt.Attributes.Add("onKeyUp", "limiteTextArea(this, 50)")	
*/
function limiteTextArea(campo, limite)
{	
	var valor = campo.value;
	
	if(valor.length > limite)
	{
		alert('Este campo tem limite de ' + limite + ' caracteres.');
		campo.value = valor.substr(0,limite);
	}
}

/*
Descrição:	Igual ao Replace do VBScript, substitui todos sub1 pelo sub2 que estão contidos em valor
      Uso:	Replace(valor, sub1, sub2)
*/
function Replace(valor,sub1,sub2)
{
	alert('Function Botao() não faz parte da function Replace(). Utilizei ela apenas com retorno da function Replace().');
	final = "";

	for (i=0;i<=valor.length-sub1.length;i++)
	{
		if (valor.substring(i,i+sub1.length) == sub1)
		{
			final = final + sub2;
			i = i + sub1.length-1;
		}
		else
			final = final + valor.substring(i,i+1);
	}
	final = final + valor.substring(i,i+(valor.length));
	return final;
}

/*
Descrição:	Função p/ substituir caracteres especiais num texto por um espaço em branco
      Uso:	txt.Attributes.Add("onBlur", "return SubstituiCaracteresEspecias(this)")
*/
function SubstituiCaracteresEspecias(Campo)
{
	tam = Campo.value.length;
	str = "";
	for(x = 0;x <= tam;x++)
	{
		if((Campo.value.substring(x,x+1) != '&')&&(Campo.value.substring(x,x+1) != '<')&&(Campo.value.substring(x,x+1) != '>')&&(Campo.value.substring(x,x+1) != '!')&&(Campo.value.substring(x,x+1) != '@')&&(Campo.value.substring(x,x+1) != '#')&&(Campo.value.substring(x,x+1) != '$')&&(Campo.value.substring(x,x+1) != '%')&&(Campo.value.substring(x,x+1) != '¨')&&(Campo.value.substring(x,x+1) != '*')&&(Campo.value.substring(x,x+1) != '\''))
		{
			str += Campo.value.substring(x,x+1);
		}
		else
		{
			str += '';
		}
	}
	Campo.value = str;
}

/*
Descrição:	Função que permite digitar apenas números e "-", ".", "(" e ")".
      Uso:	txt.Attributes.Add("onKeyPress", "return Telefone()")
*/
function Telefone()
{
  var Tecla = window.event.keyCode;
  event.cancelBubble = true;
  if((Tecla > 47 && Tecla < 58) || (Tecla == 45) || (Tecla == 40) || (Tecla == 41) || (Tecla == 32) || (Tecla == 46))
    event.returnValue = true;
  else
    event.returnValue = false;
}

/*
Descrição:	Função p/ substituir o "." por ","
      Uso:	txt.Attributes.Add("onKeyPress", "VerVirgula(event)")
*/
function VerVirgula(event)
{
	if (event.keyCode == 46)
	{
		event.keyCode = 44
	}
}

// ---------------------------------------------------------------------- //
// ------------------ FUNÇÕES DE MANIPULAÇÃO DE NÚMERO ------------------ //
// ---------------------------------------------------------------------- //

/*
Descrição:	Função que permite digitar apenas números e virgulas
      Uso:	txt.Attributes.Add("onKeyPress", "return CampoPorcentagem()")
*/
function CampoPorcentagem()
{
  var Tecla = window.event.keyCode;
  event.cancelBubble = true;
  if((Tecla > 47 && Tecla < 58) || (Tecla == 44))
    event.returnValue = true;
  else
    event.returnValue = false;
}

/*
Descrição:	Função para formatar a digitação monetária em um campo texto
      Uso:	botao.Attributes.Add("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;  // Enter
	
	key = String.fromCharCode(whichCode);  // Get key value from key code

	if (strCheck.indexOf(key) == -1) return false;  // Not a valid key

	len = fld.maxLength;

	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;
}

/*
Descrição:	Função que permite digitar apenas números hexadecimais
      Uso:	txt.Attributes.Add("onKeyPress", "return Hexadecimal(event)")
*/
function Hexadecimal(event)
{
    Tecla = event.which;
    if(Tecla == null)
        Tecla = event.keyCode;
    if((Tecla > 57 || Tecla < 48) && (Tecla > 70 || Tecla < 65) && (Tecla > 102 || Tecla < 97) && (Tecla != 35) && Tecla != 8)
        return false;
    return true;
}

/*
Descrição:	Função que verificar se um determinado valor é numerico inteiro
      Uso:	IsNumeric('valor');
*/
function IsNumeric(strString)
//  check for valid numeric strings	
{
	var strValidChars = "0123456789";
	var strChar;
	var blnResult = true;

	if (strString.length == 0) return false;

	//  test strString consists of valid characters listed above
	for (i = 0; i < strString.length && blnResult == true; i++)
	{
		strChar = strString.charAt(i);
		if (strValidChars.indexOf(strChar) == -1)
		{
			blnResult = false;
		}
	}
	return blnResult;
}

/*
Descrição:	Função que verificar se um determinado valor é numerico com ponto flutuante
      Uso:	IsNumericReal('valor');
*/
function IsNumericReal(strString)
//  check for valid numeric strings	
{
	var strValidChars = "0123456789.-,";
	var strChar;
	var blnResult = true;

	if (strString.length == 0) return false;

	//  test strString consists of valid characters listed above
	for (i = 0; i < strString.length && blnResult == true; i++)
	{
		strChar = strString.charAt(i);
		if (strValidChars.indexOf(strChar) == -1)
		{
			blnResult = false;
		}
	}
	return blnResult;
}

/*
Descrição:	Função para limpar zeros a esquerda
      Uso:	utilizada na função MaskCurrency e MaskCurrencyNegativo
*/
function limpaZerosEsquerda(inputString,tipo)
{
	// uso: limpaZerosAEsquerda('000123abc')
	// usar tipo = 1 para permitir zero
	var outputString  = '';
	var espacosAntes  = 0;
	if (tipo == 1){
		re = /^0*$/;
		res = inputString.match(re);
		if (inputString.substr(0,1) != "-" && res == null) inic = 0;
		else  inic = 1;
	}
	else inic = 0;
	for(var i = inic ; i < inputString.length ; i++){
		if(inputString.charAt(i) == '0'){ espacosAntes++; }
		else{ break; }
	}
	outputString =  String(inputString).substr(espacosAntes);
	return outputString;
}

/*
Descrição:	Função para criar mascara para nº com pontos flutuante
      Uso:	txt.Attributes.Add("onKeyPress", "MaskCurrency(this, 10, event)")
*/
function MaskCurrency(campo, digitos, event)
{

	if (!NumericoInteiro(event))
	{
		return false;		
	}

	var valor = campo.value;
	// se o usuário limpou o campo
	if(valor.length == 0) return;
	var strSinal="";
	var limite = 0;
	if(valor.substr(0,1)=="-"){
		strSinal = "-";
	}
	// elimina qualquer caracter não numérico
	valor = valor.replace(/[^0-9_]/gi,"");
	// se atingiu o tamanho máximo, retorna
	if(valor.length>digitos){
		valor = valor.substr(0,digitos+1);
		limite = 1;
		//alert("Limite do tamanho do campo atingido");
		//return false;
	} 
	// se o usuário só digitou zeros
	if(parseFloat(valor)==0.00) 
	valor = '00';
	// garante que há 2 dígitos
	while (valor.length < 2)
	valor = '0' + valor;
	// elimina zeros colocados no início do número.
	if(valor.length==4 && valor.substr(0,1) == "0")
		valor = valor.substr(1);
	else if((valor.length > 4))
		valor = limpaZerosEsquerda(valor,1);
		var novoVal = '';
		// pega primeiro as casas decimais
		if (limite==1)
		{
			novoVal = "," + valor.substr(valor.length-2, 2);
		}
		else
		{
			novoVal = "," + valor.substr(valor.length-1, 2);
		}
		// remonta valor sem os últimos dois números
		if(limite==1) {
			valor = valor.substr(0,valor.length-2);	
		}
		else {
			valor = valor.substr(0,valor.length-1);	
		}
		// percorre os digitos para formatação
		var i = 1;
		for(i=1; valor.length > 0; i++){
			novoVal = valor.substr(valor.length-1,1) + "" + novoVal;
			valor = valor.substr(0,valor.length-1);
			// se passou por três caracteres e ainda há mais dígitos, coloca um ponto agrupador
			//if((i%3==0) && (valor.length>0))
			//novoVal = "." + novoVal;
		}
		if (novoVal.substr(1,1)!=',')
		{
			novoVal = limpaZerosEsquerda(novoVal,1);
		}
		campo.value = strSinal + '' + novoVal;
} 

/*
Descrição:	Função para criar mascara para nº negativo com pontos flutuante
      Uso:	txt.Attributes.Add("onKeyPress", "MaskCurrencyNegativo(this, 10, event)")
*/
function MaskCurrencyNegativo(campo, digitos, event)
{
	var strSinal="";
	Tecla2 = event.keyCode;
    Tecla1 = event.which;
	Tecla1 = event.keyCode;

	if(((Tecla1 >= 0x30) && (Tecla1 <= 0x39))||(Tecla2 == 46)||(Tecla2 == 44)||(Tecla2 == 8)|| (event.keyCode == "45")){
	
	}else{
		return false;		
	}

	var valor = campo.value;

	if( (valor.length == 0)&&(event.keyCode == "45") ){
		strSinal = "-";
	}else{			
		if ((event.keyCode == "45")){
			strSinal = "-"
		}else{
			if (!NumericoInteiro(event))
			{
				return false;		
			}
		}
	}

	// se o usuário limpou o campo
	if(valor.length == 0) return;
	if(valor.substr(0,1) == "-") 
	{
		strSinal = "-";
	}

	var limite = 0;
//	if(valor.substr(0,1)=="-"){
//		strSinal = "-";
//	}
	// elimina qualquer caracter não numérico
	valor = valor.replace(/[^0-9_]/gi,"");
	// se atingiu o tamanho máximo, retorna
	if(valor.length>digitos){
		valor = valor.substr(0,digitos+1);
		limite = 1;
		//alert("Limite do tamanho do campo atingido");
		//return false;
	} 
	// se o usuário só digitou zeros
	if(parseFloat(valor)==0.00) 
	valor = '00';
	// garante que há 2 dígitos
	while (valor.length < 2)
	valor = '0' + valor;
	// elimina zeros colocados no início do número.
	if(valor.length==4 && valor.substr(0,1) == "0")
		valor = valor.substr(1);
	else if((valor.length > 4))
		valor = limpaZerosEsquerda(valor,1);
		var novoVal = '';
		// pega primeiro as casas decimais
		if (limite==1)
		{
			novoVal = "," + valor.substr(valor.length-2, 2);
		}
		else
		{
			novoVal = "," + valor.substr(valor.length-1, 2);
		}
		// remonta valor sem os últimos dois números
		if(limite==1) {
			valor = valor.substr(0,valor.length-2);	
		}
		else {
			valor = valor.substr(0,valor.length-1);	
		}
		// percorre os digitos para formatação
		var i = 1;
		for(i=1; valor.length > 0; i++){
			novoVal = valor.substr(valor.length-1,1) + "" + novoVal;
			valor = valor.substr(0,valor.length-1);
			// se passou por três caracteres e ainda há mais dígitos, coloca um ponto agrupador
			//if((i%3==0) && (valor.length>0))
			//novoVal = "." + novoVal;
		}
		if (novoVal.substr(1,1)!=',')
		{
			novoVal = limpaZerosEsquerda(novoVal,1);
		}

		campo.value = strSinal + '' + novoVal;

		if ((event.keyCode=="45") && (novoVal.length > 0 ))
		{
			return false
		}		
}

/*
Descrição:	Função p/ bloquear caracteres não numericos com ponto flutuante
      Uso:	txt.Attributes.Add("onKeyPress", "return Numerico(event)")
*/
function Numerico(event)
{
	Tecla2 = event.keyCode;
    Tecla1 = event.which;
	Tecla1 = event.keyCode;
	if(((Tecla1 >= 0x30) && (Tecla1 <= 0x39))||(Tecla2 == 46)||(Tecla2 == 44)||(Tecla2 == 8))
	{
		tecla_ok = true;
		return true;
	}
	return false;
}

/*
Descrição:	Função p/ bloquear caracteres não numericos inteiros
      Uso:	txt.Attributes.Add("onKeyPress", "return NumericoInteiro(event)")
*/
function NumericoInteiro(event)
{
	Tecla2 = event.keyCode;
    Tecla1 = event.which;
	Tecla1 = event.keyCode;
	if(((Tecla1 >= 0x30) && (Tecla1 <= 0x39))||(Tecla2 == 8)){
		tecla_ok = true;
		return true;
	}
    return false;
}

/*
Descrição:	Função que permite digitar apenas números e uma ",". Diferente da IsNumericReal(strString).
      Uso:	txt.Attributes.Add("onKeyPress", "return NumericoReal(event, this)")	
*/
function NumericoReal(event, Campo)
{
    Tecla = event.which;
    if(Tecla == null)
        Tecla = event.keyCode;
	if ((Tecla > 47 && Tecla < 58) || (Tecla == 44 && Campo.value.indexOf(",") == -1) || Tecla == 8)
		event.returnValue = true;
	else
		event.returnValue = false;
}

/*
Descrição:	Função que valida a digitação monetária de um campo
      Uso:	botao.Attributes.Add("onBlur", "return(validateDollar(this));")
*/
function validateDollar( fld ) 
{ 
   var temp_value = fld.value; 
   var achouPonto
   var achouVirgula

   if (temp_value == "") 
   { 
     fld.value = ""; 
     return; 
   } 
   var Chars = "0123456789.,"; 
   for (var i = 0; i < temp_value.length; i++) 
   { 
       if (Chars.indexOf(temp_value.charAt(i)) == -1) 
       { 
           alert("Valor incorreto!"); 
           fld.focus(); 
		   fld.select(); 
           return; 
       }
       
       if (temp_value.charAt(i) == ".")
       {
		  achouPonto = i
       }
       
       if (temp_value.charAt(i) == ",")
       {
		  achouVirgula = i
       }
       
       if (achouVirgula < achouPonto) 
       { 
           alert("Valor incorreto!"); 
           fld.focus(); 
		   fld.select(); 
           return; 
       }
   } 
}

/*
Descrição:	Função que valida a digitação monetária de um campo.
			Permite apenas que se digite inteiros, formata o campo(Ex.: "123.123,00")
      Uso:	txt.Attributes.Add("onBlur", "real(this,2);")
			txt.Attributes.Add("onKeyPress", "real(this,2);")
			txt.Attributes.Add("onKeyUp", "real(this,2);")
*/
function real(field,digitsAfterDecimal)
{
	try
	{
		var keyboardKey = window.event.which;
		if(keyboardKey == null) keyboardKey = window.event.keyCode;
		if((keyboardKey > 47 && keyboardKey < 58) || (keyboardKey == 13)) event.returnValue = true;
		else event.returnValue = false;		
						
		var value = filter(field.value,0,0,''); 
		var valueLength = value.length; 
		
		var returnValue = '';
		
		if (valueLength < field.maxLength)
		{		
			if (valueLength > digitsAfterDecimal)
			{
				var valueDec = value.substring(valueLength-digitsAfterDecimal,valueLength);
				value = value.substring(0,valueLength-digitsAfterDecimal);
				valueLength = value.length;
				
				if (valueLength > digitsAfterDecimal)
				{
					for (var i = 0;i <= valueLength;i++)
					{																
						if ((i != 0 ) && (i == valueLength % 3))
						{							
							returnValue += '.' + value.substring(i,i+1);
						}
						else if ((i != valueLength) && (i > valueLength % 3) && (i % 3 == valueLength % 3))
						{					
							returnValue += '.' + value.substring(i,i+1);			
						}						
						else
						{
							returnValue += value.substring(i,i+1);	
						}
					}
					
					field.value = returnValue + ',' + valueDec;
				}
				else
				{
					field.value = value + ',' + valueDec;
				}				
			}
			else
			{
				field.value = value;
			}
		}
	}
	catch(e){}									
}

/*
Descrição:	Função utilizada na função real
      Uso:	
*/
function filter(value,filter,type,complement)
{										
	try
	{
		var characters = '';			
		var returnValue = '';

		switch(filter)
		{				
			case 0:
				characters = complement + '0123456789';
				break;
			case 1:
				characters = complement + 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
				break;
			case 2:
				characters = complement + '"' + "'";
				break;										
			default:
				characters = complement + '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
				break;					
		}
		
		if (type == 0)
		{
			for (var i = 0; i < value.length; i++) 
			{ 																								
				if (characters.indexOf(value.toUpperCase().substring(i,i+1)) > -1)
				{
					returnValue = returnValue + value.substring(i,i+1);
				}												
			}
		}
		else
		{
			for (var i = 0; i < value.length; i++) 
			{ 																								
				if (characters.indexOf(value.toUpperCase().substring(i,i+1)) == -1)
				{
					returnValue = returnValue + value.substring(i,i+1);
				}												
			}
		}

		return returnValue;
	}
	catch(e){}
}

/*
Descrição:	Função p/ bloquear caracteres não numericos, com excessão do "x" e "X".
      Uso:	txt.Attributes.Add("onKeyPress", "return FormatISBN(event)")
*/
function FormatISBN(event)
{
	Tecla2 = event.keyCode;
    Tecla1 = event.which;
	Tecla1 = event.keyCode;
	
	if(((Tecla1 >= 0x30) && (Tecla1 <= 0x39))||(Tecla2 == 8) || (Tecla2 == 120) || (Tecla2 == 88))
	{
		tecla_ok = true;
		return true;
	}
    return false;
}

// ----------------------------------------------------------------------- //
// ----------------- FUNÇÕES DE MANIPULAÇÃO DE DATA E HORA --------------- //
// ----------------------------------------------------------------------- //

/*
Descrição:	Função para adionar dias/mês/ano em uma data
      Uso:	var data = DateAdd(intervalo, numero, data);
*/
function DateAdd(intervalo, numero, data)	
{
	var i;
	if (data.value.length == 10)
	{	
		var d = parseInt(data.value.substring(0,2));
		var m = parseInt(data.value.substring(3,5));
		var y = parseInt(data.value.substring(6,10));
		
		if (numero != 0)
		{
			if (numero > 0) //nro positivo
			{
				for ( i = 1 ; i <= numero ; i++ ) 
				{
					if ((intervalo == 'd') || (intervalo == 'D')) //DIA
					{
						d = d + 1;
						if (d > UltimoDiaMes(m))
						{
							m = m + 1;
							d = 01;
							if (m > 12)
							{
								m = 01;
								y = y + 1;
							}
						}
					}
					if ((intervalo == 'm') || (intervalo == 'M')) //MÊS
					{
						m = m + 1;
						if (m > 12)
						{
							m = 01;
							y = y + 1;
						}
					}
					if ((intervalo == 'y') || (intervalo == 'Y')) //ANO
					{
						y = y + 1;
					}
				}
			}
			else //nro negativo
			{
				for ( i = numero ; i <= -1 ; i++ ) 
				{
					if ((intervalo == 'd') || (intervalo == 'D')) //DIA
					{
						d = d - 1;
						if (d == 0)
						{
							m = m - 1;
							if (m == 0)
							{
								m = 12;
								d = 31;
								y = y - 1;
							}
							else
							{
								d = UltimoDiaMes(m);
							}
						}
					}
					if ((intervalo == 'm') || (intervalo == 'M')) //MÊS
					{
						m = m - 1;
						if (m == 0)
						{
							m = 12;
							y = y - 1;
						}
					}
					if ((intervalo == 'y') || (intervalo == 'Y')) //ANO
					{
						y = y - 1;
					}
				}
			}
		}	
		return d + '/' + m + '/' + y
	}
	else
	{ return data.value }
}

/*
Descrição:	Função para validar se a data é valida
      Uso:	utilizada na função FormataData
*/
function fIsDate(strData) 
{
	var blnIsDate = true;
	var Dia = "";
	var Mes = "";
	var Ano = "";
	var Sep1 = "";
	var Sep2 = "";

	if (strData.length == 10) {
		Dia = strData.substring(0, 2);
		Mes = strData.substring(3, 5);
		Ano = strData.substring(6, 10);
		Sep1 = strData.substring(2, 3);
		Sep2 = strData.substring(5, 6);
		
		if (isNaN(parseFloat(Ano)) == true || parseFloat(Ano) < 1){
			blnIsDate = false;
		}
		else
		{
			if (Sep1 != "/" || Sep2 != "/") {
				blnIsDate = false;
			}
			else
			{
				if (isNaN(parseFloat(Mes)) == true || parseFloat(Mes) < 1 || parseFloat(Mes) > 12){
					blnIsDate = false;
				}
				else
				{
					if (parseFloat(Mes) == 2) {
						if ((parseFloat(Ano)) / 4 == parseInt(parseFloat(Ano) / 4)) {
							if (parseFloat(Dia) < 1 || parseFloat(Dia) > 29) {
								blnIsDate = false;
							}
						}
						else
						{
							if (parseFloat(Dia) < 1 || parseFloat(Dia) > 28) {
								blnIsDate = false;
							}
						}
					}
					else
					{
						if (parseFloat(Mes) == 4 || parseFloat(Mes) == 6 || parseFloat(Mes) == 9 || parseFloat(Mes) == 11) {
							if (parseFloat(Dia) < 1 || parseFloat(Dia) > 30) {
								blnIsDate = false;
							}
						}
						else
						{
							if (parseFloat(Mes) == 1 || parseFloat(Mes) == 3 || parseFloat(Mes) == 5 || parseFloat(Mes) == 7 || parseFloat(Mes) == 8 || parseFloat(Mes) == 10 || parseFloat(Mes) == 12) {
								if (parseFloat(Dia) < 1 || parseFloat(Dia) > 31) {
									blnIsDate = false;
								}
							}
						}
					}
				}
			}
		}
	}
	else
	{
		blnIsDate = false;
	}
	
	return blnIsDate;
}

/*
Descrição:	Função p/ que valida se o texto é do tipo hh:mm ou hh:mm:ss
      Uso:	função utilizada na function FormataHora e FormataHoraSegundos
*/
function fIsTime(valor)
{
	var x = 0;
	var tam = valor.length;
	var str = ""
	
	for(x = 0;x <= tam;x++)
	{
		if(valor.substring(x,x+1) != ':')
		{str += valor.substring(x,x+1);}
	}

	if(parseInt(str.substring(0,2)) > 23)
		return false;
	if(parseInt(str.substring(2,4)) > 59)
		return false;
	if(parseInt(str.substring(4,6)) > 59)
		return false;
	return true;
}

/*
Descrição:	Função p/ formatar a data ( DD/MM/YYYY )
      Uso:	txt.Attributes.Add("onKeyUp", "FormataData(this,event);")
*/
function FormataData(Campo)
{
		var Tecla = window.event.keyCode;
		event.cancelBubble = true;
		// Ctrl, Alt, Shift, Home, End, Insert, Delete, PageUp, PageDown, Left Arrow, Right Arrow, Up Arrow, Down Arrow, BackSpace
		if (Tecla != 8 && (Tecla < 33 || Tecla > 40) && Tecla != 45 && Tecla != 46 && (Tecla < 16 || Tecla > 18))
		{
			tam = Campo.value.length;
			str = "";
			for(x = 0;x <= tam;x++){
				if(Campo.value.substring(x,x+1) != '/'){
					str += Campo.value.substring(x,x+1);
				}
			}
			aux = "";
			s = str.substring(0,2);
			aux = aux + str.substring(0,2);
			if((s.length >= 2))
				aux = aux + "/";
			s = str.substring(2,4);
			aux = aux + s;
			if((s.length >= 2))
				aux = aux + "/";
			aux = aux + str.substring(4,8);
			if (Campo.value.length == 10)
				if (!fIsDate(Campo.value))
				{
					alert('Data Inv' + String.fromCharCode(225) + 'lida!')
					Campo.value = ""
				}
				else
				{
					if (!fValidaDataDoisCampos('01/01/1900',Campo.value))
					{
						alert('Data Inv' + String.fromCharCode(225) + 'lida!')
						Campo.value = ""
					}
					else
					{
						if (!fValidaDataDoisCampos(Campo.value,'31/12/2099'))
						{
							alert('Data Inv' + String.fromCharCode(225) + 'lida!')
							Campo.value = ""
						}
						else
							Campo.value = aux;
					}
				}
			else
				Campo.value = aux;
		}
}

/*
Descrição:	Função que formata a Hora em hh:mm
      Uso:	txt.Attributes.Add("onKeyUp", "FormataHora(this,event)"). Utiliza a função fIsTime.
*/
function FormataHora(Campo,event)
{
	var Tecla = window.event.keyCode;
	event.cancelBubble = true;
	
	if (Tecla != 8)
	{
		tam = Campo.value.length;
		str = "";
		
		for(x = 0;x <= tam;x++)
		{
			if(Campo.value.substring(x,x+1) != ':')
			{str += Campo.value.substring(x,x+1);}
		}
		
		aux = "";
		s = str.substring(0,2);
		aux = aux + str.substring(0,2);
		
		if((s.length >= 2))
			aux = aux + ":";				
			s = str.substring(2,4);
			aux = aux + s;
		
		if((s.length > 2))
			aux = aux + ":";
		
		if (Campo.value.length == 5)
			if (!fIsTime(Campo.value))
			{
				alert('Hora Inv' + String.fromCharCode(225) + 'lida!')
				Campo.value = ""
			}
		else
			Campo.value = aux;
			
		
	else
		Campo.value = aux;
	}	
}

/*
Descrição:	Função que formata a Hora em hh:mm:ss
      Uso:	txt.Attributes.Add("onKeyUp", "FormataHoraSegundos(this,event)"). Utiliza a função fIsTime.
*/
function FormataHoraSegundos(Campo,event)
{
	var Tecla = window.event.keyCode;
	event.cancelBubble = true;
	if (Tecla != 8)
	{
		tam = Campo.value.length;
		str = "";
		
		for(x = 0;x <= tam;x++)
		{
			if(Campo.value.substring(x,x+1) != ':')
			{str += Campo.value.substring(x,x+1);}
		}
		
		aux = "";
		s = str.substring(0,2);
		aux = aux + str.substring(0,2);
		
		if((s.length >= 2))
			aux = aux + ":";				
			s = str.substring(2,4);
			aux = aux + str.substring(2,4);
			if((s.length >= 2))
			aux = aux + ":";
			s = str.substring(4,6);
			aux = aux + str.substring(4,6);
			
		
		if((s.length > 2))
			aux = aux + ":";
		
		if (Campo.value.length == 8)
			if (!fIsTime(Campo.value))
			{
				alert('Hora Inv' + String.fromCharCode(225) + 'lida!')
				Campo.value = ""
			}
		else
			Campo.value = aux;
	else
		Campo.value = aux;
	}
}

/*
Descrição:	Função p/ formatar a Mês/Ano ( MM/YYYY )
      Uso:	txt.Attributes.Add("onKeyUp", "FormataMesAno(" & txt.ID & ");")
*/
function FormataMesAno(Campo) 
{ 
	var Tecla = window.event.keyCode; 
	event.cancelBubble = true; 
	// Ctrl, Alt, Shift, Home, End, Insert, Delete, PageUp, PageDown, Left Arrow, Right Arrow, Up Arrow, Down Arrow, BackSpace 

	if (Tecla != 8 && (Tecla < 33 || Tecla > 40) && Tecla != 45 && Tecla != 46 && (Tecla < 16 || Tecla > 18)) 
	{ 
		tam = Campo.value.length; 
		str = ""; 
		for(x = 0;x <= tam;x++)
		{ 
			if(Campo.value.substring(x,x+1) != '/')
			{ 
				str += Campo.value.substring(x,x+1); 
			} 
		} 
		aux = ""; 
		s = str.substring(0,2); 
		aux = aux + str.substring(0,2); 

		if((s.length >= 2)) 
			aux = aux + "/"; 

		aux = aux + str.substring(2,6); 
		if (Campo.value.length == 7) 
		{
			if (!fIsDate('01/'+ Campo.value)) 
			{ 
				alert('Mês/Ano Inv' + String.fromCharCode(225) + 'lido!'); Campo.value = ""; 
			} 
			else 
			{
				Campo.value = aux;
				//else 
				//Campo.value = aux 
			} 
		} 
	}
}

/*
Descrição:	Função que formata a data no padrão americano MM/DD/YYYY
      Uso:	função utilizada na ValidaPeriodo
*/
function FormatoAmericano(pData)
{
	var arrData = pData.split("/");
	return arrData[1] + "/" + arrData[0] + "/" + arrData[2];
}

/*
Descrição:	Função para validar duas datas
      Uso:	utilizada na função FormataData
*/
function fValidaDataDoisCampos(campo1,campo2)
{
    var erro=0
	dia1 = campo1.substring(0, 2)
    mes1 = campo1.substring(3, 5)
	ano1 = campo1.substring(6, 10)
    dia2 = campo2.substring(0, 2)
    mes2 = campo2.substring(3, 5)
	ano2 = campo2.substring(6, 10)
    if (ano1>ano2) erro = 1
    else if (ano1==ano2 && mes1>mes2) erro = 1
    else if (ano1==ano2 && mes1==mes2 && dia1>dia2) erro = 1
    if (erro==1)
		{
			if (campo2.length == 0 || campo1.length == 0) return true
			else
			{
				return false
		    }
		}
	else return true	
}

/*
Descrição:	Retorna a string dd/mm/aaaa
	  Uso:	imprimeData()
*/
function imprimeData()
{
	// Today's Date
	var now = new Date();
	var mName = now.getMonth() + 1;
	var dName = now.getDay() + 1;
	var dayNr = now.getDate();
	var yearNr=now.getYear();
	if(dName==1) Day = "domingo";
	if(dName==2) Day = "segunda";
	if(dName==3) Day = "ter&ccedil;a";
	if(dName==4) Day = "quarta";
	if(dName==5) Day = "quinta";
	if(dName==6) Day = "sexta";
	if(dName==7) Day = "s&aacute;bado";
	if(yearNr < 2000) Year = 1900 + yearNr;
	else Year = yearNr;
	// String to display current date.
	var todaysDate =(" " + Day + ", " + dayNr + "/" + mName + "/" + Year);
	var todaysDate2 =(dayNr + "/" + mName + "/" + Year);
	var todaysDay = (" " + Day + " ");

	return todaysDate2
}

/*
Descrição:	Função que verificar se um determinado valor é do tipo date
      Uso:	isDate('valor');
*/
function isDate(DateToCheck)
{
	if(DateToCheck=="")
	{
		return true;
	}
	
	var m_strDate = FormatDate(DateToCheck);
	
	if(m_strDate=="")
	{
		return false;
	}
	
	var m_arrDate = m_strDate.split("/");
	var m_DAY = m_arrDate[0];
	var m_MONTH = m_arrDate[1];
	var m_YEAR = m_arrDate[2];
	
	if(m_YEAR.length > 4)
	{
		return false;
	}
	
	m_strDate = m_MONTH + "/" + m_DAY + "/" + m_YEAR;
	var testDate=new Date(m_strDate);
	
	if(testDate.getMonth()+1==m_MONTH)
	{
		return true;
	} 
	else
	{
		return false;
	}
}

/*
Descrição:	Função que verificar se um determinado valor é do tipo date
      Uso:	isDate_old('valor');
*/
function isDate_old(dateStr)
{
	var datePat = /^(\d{1,2})(\/|-)(\d{1,2})(\/|-)(\d{4})$/;
	var matchArray = dateStr.match(datePat); // is the format ok?

	if (matchArray == null)
	{
		alert("Please enter date as either mm/dd/yyyy or mm-dd-yyyy.");
		return false;
	}

	month = matchArray[1]; // p@rse date into variables
	day = matchArray[3];
	year = matchArray[5];

	if (month < 1 || month > 12)
	{ // check month range
		alert("Month must be between 1 and 12.");
		return false;
	}

	if (day < 1 || day > 31)
	{
		alert("Day must be between 1 and 31.");
		return false;
	}

	if ((month==4 || month==6 || month==9 || month==11) && day==31)
	{
		alert("Month "+month+" doesn`t have 31 days!")
		return false;
	}

	if (month == 2)
	{ // check for february 29th
		var isleap = (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0));
		
		if (day > 29 || (day==29 && !isleap))
		{
			alert("February " + year + " doesn`t have " + day + " days!");
			return false;
		}
	}
	return true; // date is valid
}

/*
Descrição:	Função para retornar o ultimo dia do mês
      Uso:	var dia = UltimoDiaMes(mes);
*/
function UltimoDiaMes(mes)
{
	switch(mes)
	{
		case '1', '3', '5', '7', '8', '10', '12': return 31;break;
		case '4', '6', '9', '11': return 30;break;
		case '2': return 29;break;
	}
}

/*
Descrição:	Função que valida se é uma data valida
      Uso:	txt.Attributes.Add("onBlur", "ValidaData_v2(this.value)")
*/
function ValidaData_v2(valor)
{
	if (!fIsDate(valor) || valor.length != 10)
	{
		return false;
	}
	else
		return true;	
}

/*
Descrição:	Função que valida se é uma data valida
      Uso:	txt.Attributes.Add("onBlur", "ValidaData(this)")
*/
function ValidaData(campo)
{
	if (campo.value != "")
	{
		if ((campo.value.length == 10) || (campo.value.length == 0))
		{
			return true;
		}
		else
		{
			campo.value = ""
			alert('Data inv' + String.fromCharCode(225) + 'lida!')
			return false;
		}
	}
}

/*
Descrição:	Função que valida se a data inicial é maior q a data final
      Uso:	btn.Attributes.Add("onBlur", "return ValidaPeriodo('pDataInicial', 'pDataFinal')")
*/
function ValidaPeriodo(pDataInicial, pDataFinal)
{
	pDataInicial = FormatoAmericano(pDataInicial);
	pDataFinal = FormatoAmericano(pDataFinal);
	
	var DataInicial = new Date(pDataInicial);
	var DataFinal   = new Date(pDataFinal)
	
	if (DataFinal.valueOf() < DataInicial.valueOf())
	{
		return false;
	}
	else
	{
		return true;
	}
}

/*
Descrição:	Função que valida se a data inicial é maior q a data final
      Uso:	btn.Attributes.Add("onBlur", "return ValidaPeriodoAlert ValidaPeriodo('pDataInicial', 'pDataFinal')")
*/
function ValidaPeriodoAlert(pDataInicial, pDataFinal, campo)
{
	pDataInicial = FormatoAmericano(pDataInicial);
	pDataFinal = FormatoAmericano(pDataFinal);
	
	var DataInicial = new Date(pDataInicial);
	var DataFinal   = new Date(pDataFinal);
	
	if (DataFinal.valueOf() < DataInicial.valueOf())
	{
		alert('Per' + String.fromCharCode(237) + 'odo inv' + String.fromCharCode(225) + 'lido!');
		campo.value = "";
		return false;
	}
	else
	{
		return true;
	}
}

// ------------------------------------------------------------------- //
// ----------------- FUNÇÕES P/ BLOQUEAR O CRTL + V ------------------ //
// ------------------------------------------------------------------- //
/*
Descrição:	Função para bloquear o evento de CRTL + V
      Uso:	txt.Attributes.Add("onKeyDown", "return BloqueiaPaste(event, this)")
*/
function BloqueiaPaste(event, campo)
{
	if(event.keyCode==17) //valida Ctrl
	{
		campo.tag = 1;
	}

	if(((event.keyCode==86)||(event.keyCode==118))&&(campo.tag==1))
	{
		//campo.tag = 0;
		return false;
	}
	else
		return true;
}

// ----------------------------------------------------------------- //
// ----------------- FUNÇÕES P/ VALIDAR CNPJ/CPF ------------------ //
// ---------------------------------------------------------------- //

/*
Descrição:	Função que permite digitar apenas caracteres validos para um CEP (números e "-"). Igual a função "CPF()".
      Uso:	txt.Attributes.Add("onKeyPress", "return CEP()")
*/
function CEP()
{
  var Tecla = window.event.keyCode;
  event.cancelBubble = true;
  if((Tecla > 47 && Tecla < 58) || (Tecla == 45))
    event.returnValue = true;
  else
    event.returnValue = false;
}

/*
Descrição:	Função para validar cnpj
      Uso:	utiliza na função ValidaCNPJ
*/
function checkCNPJ(cnpj) 
{ 
	cnpj = cnpj.replace(".","")
	cnpj = cnpj.replace(".","")
	cnpj = cnpj.replace("-","")
	cnpj = cnpj.replace("/","")
	
    var cnpjCalc; 
    var cnpjAdd; 
    var i; 
    var cnpjDigit; 
    
    cnpj = getNumber( cnpj , 14 );

    // Get only numeric digits
    cnpjCalc = cnpj.substring( 0 , 12 );
    
    // First part of digit verification
    cnpjAdd = 0; 
    for( i = 0 ; i < 4 ; i++ ) 
    { 
        cnpjAdd += parseInt( cnpjCalc.substring( i , i + 1 ) ) * (5 - i); 
    } 

    for( i = 0 ; i < 8 ; i++ ) 
    { 
        cnpjAdd += parseInt( cnpjCalc.substring( i + 4 , i + 4 + 1 ) ) * (9 - i); 
    } 
    
    // Fisrt digit
    cnpjDigit = 11 - (cnpjAdd % 11); 
    
    if ( cnpjDigit == 10 || cnpjDigit == 11 ) 
    { 
        cnpjCalc += '0'; 
    } 
    else 
    { 
        cnpjCalc += cnpjDigit; 
    } 
    
    // Second part of digit verification
    cnpjAdd = 0; 
    
    for ( i = 0 ; i < 5 ; i++ ) 
    { 
        cnpjAdd += parseInt( cnpjCalc.substring( i , i + 1 ) ) * (6 - i); 
    } 
    for ( i = 0 ; i < 8 ; i++ ) 
    { 
        cnpjAdd += parseInt( cnpjCalc.substring( i + 5, i + 5 + 1 ) ) * (9 - i); 
    } 
    
    // Second digit
    cnpjDigit = 11 - (cnpjAdd % 11); 
    
    if ( cnpjDigit == 10 || cnpjDigit == 11 ) 
    { 
        cnpjCalc += '0'; 
    } 
    else 
    { 
        cnpjCalc += cnpjDigit; 
    } 
    
    return ( cnpj == cnpjCalc ); 
}

/*
Descrição:	Função para validar CPF
      Uso:	função utilizada na ValidaCPF
*/
function checkCPF(valor)
{
	var retorno = true
	var posicao, i, soma, dv, dv_informado;
	var digito = new Array(10);
	
	valor = valor.replace(".", "");
	valor = valor.replace(".", "");
	valor = valor.replace("-", "");
	
	dv_informado = valor.substr(valor.length-2, 2);
	// Desmembra o valor no array "digito"
	for (i=0; i<=8; i++)
	{
		digito[i] = valor.substr(i, 1);
	}
	
	// Calcula o valor do 10º dígito da verificação
	posicao = 10;
	soma = 0;
	for (i=0; i<=8; i++)
	{
		soma = soma + digito[i] * posicao;
		posicao = posicao - 1;
	}
	
	digito[9] = soma % 11;
	
	if (digito[9] < 2)
		digito[9] = 0;
	else
		digito[9] = 11 - digito[9];
		
	// Calcula o valor do 11º dígito da verificação
	posicao = 11;
	soma = 0;
	for (i=0; i<=9; i++)
	{
		soma = soma + digito[i] * posicao;
		posicao = posicao - 1;
	}
	
	digito[10] = soma % 11;
	if (digito[10] < 2)
		digito[10] = 0;
	else
		digito[10] = 11 - digito[10];
		
	// Verifica se os valores dos dígitos verificadores conferem
	dv = digito[9] * 10 + digito[10];
	
	if (dv != dv_informado)
		retorno = false;
	return retorno
}

/*
Descrição:	Função que permite digitar caracteres validos na formatação de um CNPJ (números e "-" e "/")
      Uso:	txt.Attributes.Add("onKeyPress", "return CNPJ()")
*/
function CNPJ()
{
  var Tecla = window.event.keyCode;
  event.cancelBubble = true;
  if((Tecla > 47 && Tecla < 58) || (Tecla == 45) || (Tecla == 47) || (Tecla == 46))
    event.returnValue = true;
  else
    event.returnValue = false;
}

/*
Descrição:	Função que permite digitar apenas caracteres validos na formatação de um CPF (números e "-")
      Uso:	txt.Attributes.Add("onKeyPress", "return CPF()")
*/
function CPF()
{
  var Tecla = window.event.keyCode;
  event.cancelBubble = true;
  if((Tecla > 47 && Tecla < 58) || (Tecla == 45))
    event.returnValue = true;
  else
    event.returnValue = false;
}

/*
Descrição:	Formata a digitação de um CNPJ
      Uso:	button.Attributes.Add("onKeyPress", "return FormataCNPJ(this, event)")
*/
function FormataCNPJ(Formulario, Campo, TeclaPres) 
{
	var tecla = TeclaPres.keyCode; 
    var strCampo; 
    var vr; 
    var tam; 
    var TamanhoMaximo = 14; 
	
    eval("strCampo = document." + Formulario + "." + Campo); 
	
    vr = strCampo.value; 
    vr = vr.replace("/", ""); 
    vr = vr.replace("/", ""); 
    vr = vr.replace("/", ""); 
    vr = vr.replace(",", ""); 
    vr = vr.replace(".", ""); 
    vr = vr.replace(".", ""); 
    vr = vr.replace(".", ""); 
    vr = vr.replace(".", ""); 
    vr = vr.replace(".", ""); 
    vr = vr.replace(".", ""); 
    vr = vr.replace(".", ""); 
    vr = vr.replace("-", ""); 
    vr = vr.replace("-", ""); 
    vr = vr.replace("-", ""); 
    vr = vr.replace("-", ""); 
    vr = vr.replace("-", ""); 
    tam = vr.length; 
	
    if (tam < TamanhoMaximo && tecla != 8)
    {
		tam = vr.length + 1;
    }
	
    if (tecla == 8)
    {
		tam = tam - 1;
    }
	
    if (tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105)
    {
		if (tam <= 2)
		{
			strCampo.value = vr;
		}
		
		if ((tam > 2) && (tam <= 6))
		{
			strCampo.value = vr.substr(0, tam - 2) + '-' + vr.substr(tam - 2, tam);
		}
		
		if ((tam >= 7) && (tam <= 9))
		{
			strCampo.value = vr.substr(0, tam - 6) + '/' + vr.substr(tam - 6, 4) + '-' + vr.substr(tam - 2, tam);
		}
		
		if ((tam >= 10) && (tam <= 12))
		{
			strCampo.value = vr.substr(0, tam - 9) + '.' + vr.substr(tam - 9, 3) + '/' + vr.substr(tam - 6, 4) + '-' + vr.substr(tam - 2, tam);
		}
		
		if ((tam >= 13) && (tam <= 14))
		{
			strCampo.value = vr.substr(0, tam - 12) + '.' + vr.substr(tam - 12, 3) + '.' + vr.substr(tam - 9, 3) + '/' + vr.substr(tam - 6, 4) + '-' + vr.substr(tam - 2, tam);
		}
		
		if ((tam >= 15) && (tam <= 17))
		{
			strCampo.value = vr.substr(0, tam - 14) + '.' + vr.substr(tam - 14, 3) + '.' + vr.substr(tam - 11, 3) + '.' + vr.substr(tam - 8, 3) + '.' + vr.substr(tam - 5, 3) + '-' + vr.substr(tam - 2, tam);
		}
	}
}

/*
Descrição:	Formata a digitação de um CPF
      Uso:	button.Attributes.Add("onKeyPress", "return FormataCPF('form', this, event)")
*/
function FormataCPF(Formulario, Campo, TeclaPres)
{ 
	var tecla = TeclaPres.keyCode; 
	var strCampo; 
	var vr; 
	var tam; 
	var TamanhoMaximo = 14; 
	
    eval("strCampo = document." + Formulario + "." + Campo); 
	
    vr = strCampo.value; 
    vr = vr.replace("/", ""); 
    vr = vr.replace("/", ""); 
    vr = vr.replace("/", ""); 
    vr = vr.replace(",", ""); 
    vr = vr.replace(".", ""); 
    vr = vr.replace(".", ""); 
    vr = vr.replace(".", ""); 
    vr = vr.replace(".", ""); 
    vr = vr.replace(".", ""); 
    vr = vr.replace(".", ""); 
    vr = vr.replace(".", ""); 
    vr = vr.replace("-", ""); 
    vr = vr.replace("-", ""); 
    vr = vr.replace("-", ""); 
    vr = vr.replace("-", ""); 
    vr = vr.replace("-", ""); 
    tam = vr.length;
	
	if (tam < TamanhoMaximo && tecla != 8) 
	{ 
		tam = vr.length + 1; 
	} 

	if (tecla == 8) 
	{ 
		tam = tam - 1; 
	} 
	
	if (tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105) 
	{ 
		if (tam <= 2)
		{
			strCampo.value = vr;
		}
		
		if ((tam > 3) && (tam <= 6))
		{
			strCampo.value = vr.substr(0, tam - 3) + '-' + vr.substr(tam - 3, tam);
		}
		
		if ((tam >= 7) && (tam <= 10))
		{
			strCampo.value = vr.substr(0, tam - 6) + '.' + vr.substr(tam - 6, 3) + '-' + vr.substr(tam - 3, tam);
		}
	    
		if ((tam >= 11) && (tam <= 15))
		{
			strCampo.value = vr.substr(0, tam - 9) + '.' + vr.substr(tam - 9, 3) + '.' + vr.substr(tam - 6, 3) + '-' + vr.substr(tam - 3, tam);
		}
	}
}

/*
Descrição:	Função p/ adicionar zeros a direita
      Uso:	utilizada na função checkCNPJ
*/
function getNumber( number , len )
{
    var result = '';
    var num, i;

    for ( i = 0 ; i < number.length ; i++ )
    {
        try
        {
        num = parseInt( number.substring( i, i + 1 ) );
        result += num;
        }
        catch (exception)
        { }
    }
    if ( result.length != len )
    {
        // Complet with zeros
        result = '000000000000000' + result;
        var newLen = result.length;
        result = result.substring ( newLen - len , newLen );
    }
    return result;
}

/*
Descrição:	Função para validar CNPJ
      Uso:	botao.Attributes.Add("onClick", "return ValidaCNPJ(txtCNPJ)")
*/
function ValidaCNPJ(Campo)
{
	if (Campo.value == "")
	{
		return;
	}
	
	if( (checkCNPJ(Campo.value)) && (Campo.value != 0) )
	{
		return true
	}
	else
	{
		Campo.focus();
		alert('CNPJ inv' + String.fromCharCode(225) + 'lido!');
		return false
	}			
}



/*V
Descrição:	Função para validar CNPJ
      Uso:	botao.Attributes.Add("onClick", "return ValidaCPF(txtCPF)")
*/
function ValidaCPF(Campo)
{
	if (Campo.value == "")
	{
		return;
	}
	
	if( (checkCPF(Campo.value)) && (Campo.value != 0) )
	{
		return true
	}
	else
	{
		Campo.focus();
		alert('CPF inv'+ String.fromCharCode(225) + 'lido!');
		return false
	}			
}

// ---------------------------------------------------------------------- //
// ----------------- FUNÇÕES P/ MANIPULAÇÃO DE OBJETOS ------------------ //
// ---------------------------------------------------------------------- //

/*
Descrição:	Função para abrir um popup
      Uso:	btn.Attributes.Add("onClick", "AbrePopUp('pagina.aspx', 200, 500)
*/
function AbrePopUp(link,largura, altura)
{
	window.open(link,'janelapopup','toolbar=no,scrollbars=yes,location=no,resizable=no,menubar=yes,statusbar=no,width='+largura+',height='+altura+',left='+(window.screen.width/2-largura/2)+',top='+(window.screen.height/2-altura/2 ));
}

/*
Descrição:	Função p/ bloquear caracteres especiais 
      Uso:	txt.Attributes.Add("onKeyPress", "return BloqueiaCaracteresEspeciais(event)")
*/
function BloqueiaCaracteresEspeciais(event)
{
    Tecla = event.keyCode;    
    if(Tecla == null)
        Tecla = event.keyCode;        
    if((Tecla >= 65 && Tecla <= 90) || (Tecla >= 97 && Tecla <= 122) || (Tecla >= 48 && Tecla <= 57) || (Tecla == 32) || (Tecla == 13))
        return true;
    else
		return false;
}

/*
Descrição:	Função para colocar focus no primeiro elemento do formulario
      Uso:	<body onLoad="focus_elemento()">
*/
function focus_elemento()
{
	var cont = 0;
	var nome_ele;
	for(cont=0; document.forms[0].length-1; cont++){
		elemento = document.forms[0].elements[cont].type;
		elemento = elemento.toLowerCase();			 
		if ((elemento != 'hidden') && (elemento!='') && (elemento!='submit') && (elemento!='button')&& (elemento!='reset')&& (elemento!='image')){
			document.forms[0].elements[cont].focus();
			break;
		}
	}  
}

/*
Descrição:	Funcão que verifica se há alguma checkbox selecionada, e emite um aviso caso não exista
      Uso:	botao.Attributes.Add("onClick", "HaveOneChecked(pNomeCampo, objToWrite, pMsg)")
*/
function HaveOneChecked(pNomeCampo, objToWrite, pMsg)
{
	var Campo;
	var isChecked;
	var obj
	
	for (cont=0; cont<document.forms[0].elements.length; cont++)
	{
		var Campo = document.forms[0].elements[cont];
		if ((Campo.name.indexOf(pNomeCampo) >= 0) && (Campo.checked))
		{			
			isChecked = true;
			cont = document.forms[0].elements.length + 1;
		}	
	}
		
	
	
	if (isChecked)
	{		
		return true					
	}
	else
	{
							
		if (objToWrite != "")
		{
			WriteSummary(objToWrite,pMsg);
		}else
		{
			if (pMsg != "") alert(pMsg)
		}
		return false;
	}
}

/*
Descrição:	Função para esconder um tooltip na tela
      Uso:	btn.Attributes.Add("onFocus", "hideToolTip();")
*/
function hideToolTip()
{
	if (typeof document.all.ToolTip != "undefined" && document.all.ToolTip.style.visibility != "hidden")
	{
		document.all['ToolTip'].innerHTML = "";
		document.all['ToolTip'].outerHTML = "";
	}
	overM = true;
}

/*
Descrição:	Função p/ mudar o focus do objeto p/ o proximo ao clicar ENTER
      Uso:	txt.Attributes.Add("onKeyDown", "ident_onkeydown()")
*/
function ident_onkeydown() 
{
	if(event.keyCode == 13)
	{
		event.keyCode = 9;
	}
}

/*
Descrição:	Função que limita o tamanho de um textarea e escreve o tamanho atual num text
      Uso:	txt.Attributes.Add("onKeyUp", "LimitaTamanho(this.id, '" & txtTamanhoCampo.ID & "', 100)")
*/
function LimitaTamanho(descricao, campotamanho, total)
{
	eval('a = document.forms[0].'+descricao+'.value');
	if (a.length > total)
		eval('document.forms[0].'+descricao+'.value = document.forms[0].'+descricao+'.value.substring(0,'+total+')');
	eval('a = document.forms[0].'+descricao+'.value');
	eval('document.forms[0].'+campotamanho+'.value = total - a.length');
}

/*
Descrição:	Função que limita o tamanho de um textarea 
      Uso:	txt.Attributes.Add("onKeyUp", "LimitaTamanhoArea(this.id, 5)")
*/
function LimitaTamanhoArea(descricao,total)
{
//	var a;
	eval('a = document.forms[0].'+descricao+'.value');
	if (a.length > total)
		eval('document.forms[0].'+descricao+'.value = document.forms[0].'+descricao+'.value.substring(0,'+total+')');
	eval('a = document.forms[0].'+descricao+'.value');	
}

/*
Descrição:	Simula tecla TAB no click da tecla enter durante a troca de foco dos campos.
	  Uso:	button.Attributes.Add("onKeyPress", "MudaCampoEnter(event)")
*/
function MudaCampoEnter(event)
{
    Tecla = event.which;
    if(Tecla == null)
        Tecla = event.keyCode;

    if (Tecla == 13)
    {
		objPrimeiro = null
		objAtual = null
		objProximo = null
		
		for (x=0 ; x<=document.forms[0].elements.length - 1; x++) 
		{
			if ((document.forms[0].elements[x].type == "text" && document.forms[0].elements[x].readOnly == false) || document.forms[0].elements[x].type == "password" || (document.forms[0].elements[x].type == "select-one" && document.forms[0].elements[x].disabled == false) || document.forms[0].elements[x].type == "textarea" || document.forms[0].elements[x].type == "checkbox" || document.forms[0].elements[x].type == "button") {
				if (objPrimeiro == null) {
					objPrimeiro = document.forms[0].elements[x];
				}
						
				if (objAtual != null) {
					objProximo = document.forms[0].elements[x];
					break;
				}
				if (event.srcElement.name == document.forms[0].elements[x].name) {
					objAtual = document.forms[0].elements[x];
				}
			}
		}
        event.keyCode = 0;
		if (objProximo != null) {
	        objProximo.focus();
	    }
	    else
	    {
	        objPrimeiro.focus();
	    }
    }
}

/*
Descrição:	Função para abrir um popup dentro da pagina
      Uso:	btn.Attributes.Add("onFocus", "openPopup('teste',10,25,50)")
*/
function openPopUp(par,x,y,tam)
{
	var oPopup = window.createPopup();
    var oPopBody = oPopup.document.body;
    oPopBody.innerHTML = "<div  style='position:absolute; top:" + 0 + "; left:" + 0 + "; " + 
    "width:150px; height:" + tam + "px; padding:10px; color:#586781; font-family:arial; " +
     "font-size:11px;background-color:#CED5DE;BORDER-LEFT: #74839B 1px solid;BORDER-RIGHT: #74839B 1px solid;" +
     "BORDER-TOP: #74839B 1px solid;BORDER-BOTTOM: #74839B 1px solid;'> " +
     par + "</div>"
    oPopup.show(x+10, y, 150, tam, document.body);
}

/*
Descrição:	Função p/ retira acentos
      Uso:	var txt = RetiraAcentos(txt)
*/
function RetiraAcentos(Campo)
{
   var Acentos = "áàãââÁÀÃÂéêÉÊíÍóõôÓÔÕúüÚÜçÇabcdefghijklmnopqrstuvxwyz";
   var Traducao ="AAAAAAAAAEEEEIIOOOOOOUUUUCCABCDEFGHIJKLMNOPQRSTUVXWYZ";
   var Posic, Carac;
   var TempLog = "";
   for (var i=0; i < Campo.value.length; i++)
   {
   Carac = Campo.value.charAt (i);
   Posic  = Acentos.indexOf (Carac);

   if (Posic > -1)
	  TempLog += Traducao.charAt (Posic);
   else
      TempLog += Campo.value.charAt (i);
   }
return (TempLog);
}

/*
Descrição:	Função que seleciona a check box pai de um determinado grupo qdo todos os membros do grupo estão selecionados
      Uso:	check_filho.Attributes.Add("onClick", "SelecionaPai('check_pai', check_filho)")
*/
function SelecionaPai(campoDestino, campoOrigem)
{
	var x = campoOrigem
	var blnMarcar = true
	for (var i=0;i<x.length;i++)
	{
		if (x[i].checked == false) {
			blnMarcar = false; }
	}
	document.getElementById(campoDestino).checked = blnMarcar
}

/*
Descrição:	Função que seleciona todas checkboxs de um determinado datalist/grid
      Uso:	botao.Attributes.Add("onClick", "SelecionaTodosByName('campoDestino')")
*/
var ok;
function SelecionaTodosByName(campoDestino)
{
	if (!ok)
	{
	for (var i=0;i<document.forms[0].elements.length;i++)
  	{ 
		var x = document.forms[0].elements[i];
		if (x.name.indexOf(campoDestino) >= 0)
	  	{x.checked = true;}
  	}
		ok = true;
	}
	else
	{
	for (var i=0;i<document.forms[0].elements.length;i++)
  	{
		var x = document.forms[0].elements[i];
		if (x.name.indexOf(campoDestino) >= 0)
	  	{x.checked = false;}
  	}
		ok = false;
	}
}		

/*
Descrição:	Função que seleciona todas checkboxs de um determinado datalist/grid
      Uso:	botao.Attributes.Add("onClick", "SelecionaTodosByObj(campoDestino)")
*/
function SelecionaTodosByObj(campoDestino)
{
	
	if (!ok)
	{
		var x = campoDestino
		for (var i=0;i<x.length;i++)
		{
			x[i].checked = true;
		}
		ok = true;
	}
	else
	{
		
		var x = campoDestino
		for (var i=0;i<x.length;i++)
		{
			x[i].checked = false;
		}
		ok = false;
	}
	
	
}

/*
Descrição:	Função que marca todos os checkbox que estão cpm o estado disabled "false" checkbox na tela.
      Uso:	btn.Attributes.Add("onClick", "SelecionaTodosEnable(campoDestino);")
*/
var ok;
function SelecionaTodosEnable(campoDestino)
{
	if (!ok)
	{
		alert(ok); 
		for (var i=0;i<document.forms[0].elements.length;i++)
  		{
			var x = document.forms[0].elements[i];
			if (x.name.indexOf(campoDestino) >= 0 && x.disabled == false)
	  		{x.checked = true;}
  		}
			ok = true;
	}
	else
	{
		alert(ok);
		for (var i=0;i<document.forms[0].elements.length;i++)
  		{
			var x = document.forms[0].elements[i];
			if (x.name.indexOf(campoDestino) >= 0 && x.disabled == false)
	  		{x.checked = false;}
  		}
		ok = false;
	}
}

/*
Descrição:	Função que seleciona todas checkboxs de um determinado grupo
      Uso:	check_pai.Attributes.Add("onClick", "SelecionaTodosFilhos(check_filho, 'check_pai')")
*/
function SelecionaTodosFilhos(campoDestino, campoOrigem)
{			
	var x = campoDestino
	for (var i=0;i<x.length;i++)
	{
		x[i].checked = document.getElementById(campoOrigem).checked;
	}
}

/*
Descrição:	Função p/ mostrar e esconder um objeto
      Uso:	botao.Attributes.Add("onClick", "ShowDetalhes(objForm)")
*/
function ShowDetalhes(objForm) {
	if (eval(objForm + ".style.display") == "none") { 
		eval(objForm + ".style.display = 'block';");
		}
	else
		eval(objForm + ".style.display = 'none'");
}

/*
Descrição:	Função para exibir um ToolTip na tela
      Uso:	btn.Attributes.Add("onfocus", "showToolTip('preencha correto este campo',10,10, 25)")
*/
var overM = true;
function showToolTip(texto,x,y, largura)
{
	alert('Ocampo que est' + String.fromCharCode(225) + ' abaixo desse esconde a Tool Tip que este campo exibe.');
	var x1, y1;
	if (x > (window.screen.width - 200))
	{
		x1 = x + 250;
	}
	else
	{
		x1 = x;
	}
	if (y > (window.screen.height - 150))
	{
		y1 = y - 50;
	}
	else
	{
		y1 = y;
	}
	x1 = x1 + document.body.scrollLeft;
	y1 = y1 + document.body.scrollTop;
	if (overM)
	{
		if (typeof document.all.ToolTip == "undefined")
		{
			document.body.innerHTML = document.body.innerHTML + '<div id="ToolTip" style="Z-INDEX: 1; LEFT: ' + x1 + ' px; VISIBILITY: visible; WIDTH: ' + largura + 'px; POSITION: absolute; TOP: ' + y1 + 'px; HEIGHT: 48px" onMouseOver="hideToolTip();"></div>'
/*			document.all['ToolTip'].innerHTML = '<table cellspacing="0" cellpadding="0" border="0">' +
			'	<tr>' +
			'		<td colspan="2"><img height="1" src="images/pix.gif" width="10" border="0"></td>' +
			'		<td bgcolor="#000000" colspan="2"><img height="1" src="images/pix.gif" width="1" border="0"></td>' +
			'	</tr>' +
			'	<tr height="9">' +
			'		<td valign="top" align="right" colspan="2"><table cellpadding="0" cellspacing="0" width="10" height="100%" border="0">' +
			'			<tr>' +
			'				<td height="5"><img height="1" src="images/pix.gif" width=9 border="0"></td>' +
			'				<td bgcolor="#000000" height="5"><img height="5" src="images/pix.gif" width="1" border="0"></td>' +
			'			</tr>' +
			'			<tr>' +
			'			<td valign="top" align="right" colspan="2" height="9"><img height="9" src="images/bico_layer.gif" width="10" border="0"></td>' +
			'			</tr>' +
			'			<tr>' +
			'				<td><img height="1" src="images/pix.gif" width=9 border="0"></td>' +
			'				<td bgcolor="#000000"><img src="images/pix.gif" width="1" border="0"></td>' +
			'			</tr>' +
			'			</table></td>' +
			'		<td bgcolor="#CCCCCC" height="100%">' +
			'			<table cellspacing="0" cellpadding="0" border="0">' +
			'				<tr>' +
			'					<td bgcolor="#CCCCCC"><img height="1" src="images/pix.gif" width="10" border="0"></td>' +
			'					<td class=texto"2" valign="center" width="250" bgcolor="#CCCCCC">' +
			'					<span class="textoToolTip" style="FONT-SIZE: 8pt;COLOR: #000000;FONT-FAMILY: verdana, helvetica;TEXT-DECORATION: none">' +
			'						' + texto +	
			'					<br></span><img height="10" src="images/pix.gif" width="1" border="0"></td>' +
			'					<td bgcolor="#CCCCCC"><img height="1" src="images/pix.gif" width="10" border="0"></td>' +
			'				</tr>' +
			'			</table>' +
			'		</td>' +
			'		<td bgcolor="#000000"><img height="1" src="images/pix.gif" width="1" border="0"></td>' +
			'	</tr>' +
			'	<tr height="1">' +
			'		<td colspan="2"><img height="1" src="images/pix.gif" width="10" border="0"></td>' +
			'		<td bgcolor="#000000" colspan="2"><img height="1" src="images/pix.gif" width="1" border="0"></td>' +
			'	</tr>' +
			'</table>';
*/
			document.all['ToolTip'].innerHTML = '<table cellspacing="0" cellpadding="0" border="0">' +
			'	<tr>' +
			'		<td bgcolor="#000000" colspan="3"><img height="1" src="images/pix.gif" width="1" border="0"></td>' +
			'	</tr>' +
			'	<tr height="9">' +
			'		<td bgcolor="#000000"><img height="1" src="images/pix.gif" width="1" border="0"></td>' +
			'		<td bgcolor="#CCCCCC" height="100%">' +
			'			<table cellspacing="0" cellpadding="0" border="0">' +
			'				<tr>' +
			'					<td bgcolor="#CCCCCC"><img height="1" src="images/pix.gif" width="10" border="0"></td>' +
			'					<td class=texto"2" valign="center" width="250" bgcolor="#CCCCCC">' +
			'					<span class="textoToolTip" style="FONT-SIZE: 8pt;COLOR: #000000;FONT-FAMILY: verdana, helvetica;TEXT-DECORATION: none">' +
			'						' + texto +	
			'					<br></span><img height="10" src="images/pix.gif" width="1" border="0"></td>' +
			'					<td bgcolor="#CCCCCC"><img height="1" src="images/pix.gif" width="10" border="0"></td>' +
			'				</tr>' +
			'			</table>' +
			'		</td>' +
			'		<td bgcolor="#000000"><img height="1" src="images/pix.gif" width="1" border="0"></td>' +
			'	</tr>' +
			'	<tr height="1">' +
			'		<td bgcolor="#000000" colspan="3"><img height="1" src="images/pix.gif" width="1" border="0"></td>' +
			'	</tr>' +
			'</table>';

		}
		else
		{
			document.all['ToolTip'].style.visibility = "visible";
			document.all['ToolTip'].style.left = x1;
			document.all['ToolTip'].style.top = y1;
		}
	}
}

/*
Descrição:	Função que transfere todos os itens de uma cbo para outra cbo
      Uso:	btn.Attributes.Add("onClick", "TransferList('cbo', 'cboDestino')
*/
function TransferList(SourceList, DestinyList)
{
	//Cleaning the list before insert new options;
	document.getElementById(DestinyList).length = 0;

	var lenSource = document.getElementById(SourceList).options.length;

	for (var x=0; x<lenSource; x++)
	{
		// Adicionando novo option à lista de destino
		document.getElementById(DestinyList).options[x] = new Option(
		document.getElementById(SourceList).options[x].text,
		document.getElementById(SourceList).options[x].value);
	}
}

/*
Descrição:	Função p/ mudar o focus do objeto quando o o maxlenght do campo for atingido
      Uso:	txt.Attributes.Add("onKeyUp", "TrocaCampo(this, '" & txtProximoCampo.ID & "')")
*/
function TrocaCampo(campoatual, proximocampo)
{
    if (campoatual.value.length >= campoatual.maxLength) document.forms[0].elements[proximocampo].focus()
}

/*
Descrição:	Função para escrever em um objeto uma msg
      Uso:	utilizada na função HaveOneChecked
*/
function WriteSummary(objToWrite, pMsg)
{
	var obj;
	obj = document.getElementById(objToWrite);
	obj.innerHTML += "<br>" + "<li>" + pMsg  + "</li>";
	obj.style.display="inline"; 
}

/*
Descrição:	Função para bloquear tecla ctrl
      Uso:	txtCampo.Attributes.Add("onKeyUp", "SetCrtlFalso(event," & txtValor.ID + ");")
*/
function SetCrtlFalso(event, campo)
{
	if(event.keyCode==17) //valida Ctrl
	{
		campo.tag = 0;
	}
}

// ----------------------------------------------------------------- //
// ----------------- FUNÇÕES P/ MENSAGENS PADRÕES ------------------ //
// ----------------------------------------------------------------- //

/*
Descrição:	Mensagem de confirmação de exclusão de registro que recebe um parâmetro com mensagem a ser exibida
      Uso:	btnExcluir.Attributes.Add("onClick", "confirma('Mensagem')")
*/
function confirma(msg)
{ 
	if (confirm(msg)==true) 
		return true
	else
		return false
}

/*
Descrição:	Mensagem de confirmação de exclusão de registro
      Uso:	btnExcluir.Attributes.Add("onClick", "confirmaExclusao()")
*/
function confirmaExclusao()
{
	if (confirm('Confirma a Exclus' + String.fromCharCode(227) + 'o deste registro?')==true) 
		return true
    else
		return false
}

// ----------------------------------------------------------------- //
// ----------------- FUNÇÕES P/ TRATAMENTO COOKIES ----------------- //
// ----------------------------------------------------------------- //

/*
Descrição:	Seta um cookie na máquina do cliente
      Uso:	_SetCookie( name, value )
*/
function _SetCookie( name, value )
{  
	var argv = _SetCookie.arguments;  
	var argc = _SetCookie.arguments.length;  
	var path = (argc > 2) ? argv[2] : null;  
	var expires = (argc > 3) ? argv[3] : null;  
	var domain = (argc > 4) ? argv[4] : null;  
	var secure = (argc > 5) ? argv[5] : false;  
	document.cookie = name + "=" + escape (value) + 
	//((expires == null) ? "" : ("; expires=" + expires.toGMTString())) + 
	((expires == null) ? "" : ("; expires=" + (expires.getTime() + 5 * (24 * 60 * 60 * 1000) )    )) + 
	((path == null) ? "" : ("; path=" + path)) +  
	((domain == null) ? "" : ("; domain=" + domain)) +    
	((secure == true) ? "; secure" : "");
}

/*
Descrição:	Captura um cookie na maquina do cliente
      Uso:	__GetCookie( name )
*/
function __GetCookie( name )
{  
	var arg = name + "=";  
	var alen = arg.length;  
	var clen = document.cookie.length;  
	var i = 0;  
	while (i < clen)
	{    
		var j = i + alen;    
		if( document.cookie.substring(i, j) == arg )      
			return __GetCookieVal (j);    
		i = document.cookie.indexOf( " ", i ) + 1;    
		if( i == 0 ) break;   
	}  
	return null;
}

/*
Descrição:	Captura um cookie na maquina do cliente
			Opera juntamente a __GetCookie
      Uso:	__GetCookie( name )
*/
function __GetCookieVal( offset )
{  
	var endstr = document.cookie.indexOf( ";", offset );  
	if( endstr == -1 )    
		endstr = document.cookie.length;  
	return unescape( document.cookie.substring(offset, endstr) );
}

/*
Descrição:	Exclui um cookie da máquina do cliente
      Uso:	_DeleteCookie( name )
*/
function _DeleteCookie( name )
{  
	var exp = new Date();  
	exp.setTime (exp.getTime() - 1);  
	var cval = __GetCookie( name );  
	document.cookie = name + "=" + cval + "; expires=" + exp.toGMTString();
}

function MM_swapImage() { //v3.0
  var i,j=0,x,a=MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}

function MM_findObj(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
}

function Foco(form,campo)
{
	try
	{
		if (eval("document."+form+".elements['"+campo+"'].type != undefined"))
			eval("document."+form+".elements['"+campo+"'].focus()")
		else
			eval("document."+form+"."+campo+"[0].focus()")
	}
	catch(e)
	{}
}