function VerificaJava()
{
	if (navigator.javaEnabled())
		return true;
	else
		return false;
}

function AbreJanela(szJanela, szUrl, intWidth, intHeight )
{
	var posx = (screen.width-intWidth)/2;
	var posy = (screen.height-intHeight)/2;

	win = window.open(szUrl,szJanela,'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,menubar=no,width='+intWidth+',height='+intHeight+',screenX='+posx+',screenY='+posy);
	win.moveTo(posx,posy);
	win.focus();
}

function AbreJanela2(szJanela, szUrl, intWidth, intHeight )
{
	var posx = (screen.width-intWidth)/2;
	var posy = (screen.height-intHeight)/2;

	win = window.open(szUrl,szJanela,'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,menubar=no,width='+intWidth+',height='+intHeight+',screenX='+posx+',screenY='+posy);
	win.moveTo(posx,posy);
	win.focus();
}

function AbreFotoZoom(szJanela, szUrl, intWidth, intHeight )
{
	var posx = (screen.width-intWidth)/2;
	var posy = (screen.height-intHeight)/2;

	win = window.open(szUrl,szJanela,'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,menubar=no,width='+intWidth+',height='+intHeight+',screenX='+posx+',screenY='+posy);
	win.moveTo(posx,posy);
	win.focus();
}

function abrePop(szJanela, szUrl, intWidth, intHeight, i )
{
	var posx = 30+i*80;
	var posy = 100+i*40;

	win = window.open(szUrl,szJanela,'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=no,resizable=no,menubar=no,width='+intWidth+',height='+intHeight+',screenX='+posx+',screenY='+posy);
	win.moveTo(posx,posy);
}

function FechaJanela( w )
{
	w.opener.location.reload();
	w.close();
}

function SetCheckBox( obj, str )
{
	var tam=obj.length;

	if( tam == undefined )
	{
		if( obj.value == str )
			obj.checked = true;
	}
	else
	{
		for( i=0; i < tam; i++ )
		{
			if( obj[i].value == str )
			{
				obj[i].checked = true;
				return;
			}
		}
	}
}

function UnsetCheckBox( obj, str )
{
	var tam=obj.length;

	if( tam == undefined )
	{
		if( obj.value == str )
			obj.checked = false;
	}
	else
	{
		for( i=0; i < tam; i++ )
		{
			if( obj[i].value == str )
			{
				obj[i].checked = false;
				return;
			}
		}
	}
}

function InsereJaca(valor,nome,ob)
{
	var i;
		
	if(ob.options.length)
	{
		for(i=0; i < ob.options.length ; i++)
		{
			if(ob.options[i].value == valor)
				return;
		}
	}
	
	ob.options[ob.options.length] = new Option(nome,valor);
}

function RemoveJaca(valor,list)
{
	for(i = list.options.length-1 ; i >= 0 ; i--)
	{
		if (list.options[i].value == valor)
		{
			list.options[i] = null;
		}
	}		
}

function ImplodeLista( objOrig, objDest )
{
	var strTemp="";
	
	if( objOrig.length < 1 )
	{
		return false;
	}
	else
	{
		for(i=0 ; i < objOrig.length ; i++)
			strTemp = strTemp + "," + objOrig.options[i].value;

		objDest.value = strTemp.replace(',','');
		return true;
	}
}

function ProcuraSel( o, szUrl )
{
	var valor=GetSelect(o);
	
	if( valor  == '-1') {
		alert("Você precisa especificar algum parâmetro de procura.");
		return;
	}

	if( szUrl != '' )
		AbreJanela( 'procSel',szUrl+'?key='+valor+"&campo="+o.name, 350, 200);
	else
		alert( "Tipo de procura inválida." );
}

function SetSelect( sel, strOpt )
{
	if( strOpt == "" ) return;

	for( var i=0; i < sel.length; i++ ) {
		if( sel.options[i].value == strOpt ) {
			sel.options[i].selected = true;
			return;
		}
	}
}

function SetRadio( o, strOpt )
{
	if( strOpt == "" ) return;
	
	var tam=o.length;
	
	if( tam > 1 ) {
		for( var i=0; i < tam; i++ )
			if( o[i].value == strOpt ) {
				o[i].click();
				return;
			}
	} else
		if( o.value == strOpt )
			o.click();
}

function GetSelect( o ) 
{
	return o.options[o.options.selectedIndex].value;
}

function GetRadio( o )
{
	var tam=o.length;
	
	if( tam > 1 ) {
		for (var i=0;i<tam;i++)
			if(o[i].checked=="1")
				return o[i].value;
	} else
		if(o.checked=="1")
			return o.value;

	return "";
}

function VerificaData( dia, mes, ano )
{
	if( dia.length != 2 || mes.length != 2 || ano.length != 4 )
		return false;
		
	if( dia <= 0 || dia > 31 )
		return false;
		
	if( mes <= 0 || mes > 12 )
		return false;
		
	if( mes == 2 && dia > 29 )
		return false;
		
	if( mes == 3 && dia > 31 )
		return false;

	if( mes == 4 && dia > 30 )
		return false;

	if( mes == 5 && dia > 31 )
		return false;

	if( mes == 6 && dia > 30 )
		return false;

	if( mes == 7 && dia > 31 )
		return false;

	if( mes == 8 && dia > 31 )
		return false;

	if( mes == 9 && dia > 30 )
		return false;

	if( mes == 10 && dia > 31 )
		return false;

	if( mes == 11 && dia > 30 )
		return false;

	if( mes == 12 && dia > 31 )
		return false;

	if( ano < 1900 || ano > 2100)
		return false;

	return true;
}

function DataAtual()
{
	var now = new Date();
	var mName = now.getMonth() + 1;
	var dName = now.getDay() + 1;
	var dayNr = now.getDate();
	var yearNr=now.getYear();

	if(mName == 1)  mName = "Janeiro"; 
	else if(mName == 2)  mName = "Fevereiro"; 
	else if(mName == 3)  mName = "Março"; 
	else if(mName == 4)  mName = "Abril"; 
	else if(mName == 5)  mName = "Maio"; 
	else if(mName == 6)  mName = "Junho"; 
	else if(mName == 7)  mName = "Julho"; 
	else if(mName == 8)  mName = "Agosto"; 
	else if(mName == 9)  mName = "Setembro"; 
	else if(mName == 10) mName = "Outubro"; 
	else if(mName == 11) mName = "Novembro"; 
	else mName = "Dezembro"; 

	if(dName==1) Day = "Domingo";
	else if(dName==2) Day = "Segunda-feira";
	else if(dName==3) Day = "Ter&ccedil;a-feira";
	else if(dName==4) Day = "Quarta-feira";
	else if(dName==5) Day = "Quinta-feira";
	else if(dName==6) Day = "Sexta-feira";
	else if(dName==7) Day = "S&aacute;bado";
	else if(yearNr < 2000) Year = 1900 + yearNr;
	else Year = yearNr;

	alert(" " + Day + ", " + dayNr + " de " + mName + " de " + Year);
}

function Limita(campo,tam) // Limitador de caracteres para objeto TextArea.
{ 
	if (campo.value.length >= tam) {
		campo.value = campo.value.substring(0,tam); 
		return false
	}
	return true;
}

function ContaCampo(campo, campotxt, tam) // Contador de caracteres restantes
{
	campo.value = tam - campotxt.value.length;
}

function ValidaHora(hora) // Verifica se a hora foi digitada corretamente. Formato= 24 hs
{
	hour = parseInt(hora.substring(0,3),10);
	minutes = parseInt(hora.substring(3,5),10);

	if(hour > 24 || hour < 0)
	{
		alert("Hora inválida!");
		return false;
	}
	if(minutes > 60 || minutes < 0)
	{
		alert("Minutos inválido!");
		return false;
	}
	
	return true;
}

function ValidaAno(ano) // só vai validar se ano tiver conteúdo senão retorna verdadeiro
{ 
	if (ano == '')
		return true;
		
	ano = "01/01/" + ano;
	
	if (validaData(ano))
		return true;
	else
		return false;
}

function ValidaData(data) // Verifica se a data digitada é correta
{
	if (data.length == 0)
	{
		return;
	}

	aux = data.split('/');
	var dia = parseInt(aux[0], 10);
	var mes = parseInt(aux[1], 10);
	var ano = parseInt(aux[2], 10);

	if (dia <= 31 && mes <=12 && ano >= 1000)
	{
		if (data.substring(0,1)=='0' && data.substring(1,2) != '0' || data.substring(0,1)!='0')
		{
			if (data.substring(2,3)=="/")
			{
				if (data.substring(3,4)=='0' && data.substring(4,5)!='0' || data.substring(3,4)!='0')
				{
					if (data.substring(5,6)=="/")
					{
						if (data.substring(6,7)== '0' || data.substring(6,7)=='' && data.substring(7,8)!='0')
						{
							window.alert('++ Erro\n\nO ano que você digitou não existe.');
							return false;
						} 
						else
						{
							if (mes == 2)
							{
								if ((dia > 0 ) && (dia <= 29))
								{
									if (dia == 29)
									{
										if ((ano % 4) == 0)
										{
											return true;
										}
										else
										{
											window.alert('++ Erro:\n\nO dia que você digitou não existe.');
											return false;
										}
									}
								} 
								else
								{
									window.alert('++ Erro:\n\nO dia que você digitou não existe.');
									return false;
								}
							}
							if ((mes == 4)||(mes == 6)||(mes == 9)||(mes == 11))
							{
								if ((dia > 0 ) && (dia <= 30))
								{
									return true;
								}
								else
								{
									window.alert('++ Erro:\n\nO dia que você digitou não existe.');
									return false;
								}
							}
							if ((mes == 1)||(mes == 3)||(mes == 5)||(mes ==7)||(mes == 8)||(mes == 10)||(mes == 12))
							{
								if ((dia > 0) && (dia <= 31))
								{
									return true;
								}
								else
								{
									window.alert('++ Erro:\n\nO dia que você digitou não existe.');
									return false;
								}
							}
						}
					}
					else
					{
						window.alert('++ Erro:\n\nA data foi digitada fora do padrão(dd/mm/aaaa).');
						return false;
					}
				}
				else
				{
					window.alert('++ Erro:\n\nVocê digitou um mês que não existe.');
					return false;
				}
			}
			else
			{
				window.alert('++ Erro:\n\nA data foi digitada fora do padrão(dd/mm/aaaa).');
				return false;
			}
		}
		else
		{
			window.alert('++ Erro:\n\nVocê digitou um dia que não existe.');
			return false;	
		}
	}
	else
	{
		window.alert('++ Erro:\n\nData inválida.');
		return false;
	}
	
	return true; 
}

function InterData(data1,data2, msg) // Função para verificar se a data final é superior à inicial
{
	di = parseInt(data1.substring(0,2),10);
	mi = parseInt(data1.substring(3,5),10);
	ai = parseInt(data1.substring(6,10),10);
		
	df = parseInt(data2.substring(0,2),10);
	mf = parseInt(data2.substring(3,5),10);
	af = parseInt(data2.substring(6,10),10);
			
	datai = new Date(ai, mi - 1, di);
	dataf = new Date(af, mf - 1, df);
	
	if(dataf.getTime() < datai.getTime())
	{
		alert(msg);
		return false;
	}
	
	return true;
}

function DiffData(data1,data2) // Função para verificar se a data final é superior à inicial
{
 	if(data1 == '' || data2 == '') return " ";
	
	di = parseInt(data1.substring(0,2),10);
	mi = parseInt(data1.substring(3,5),10);
	ai = parseInt(data1.substring(6,10),10);
		
	df = parseInt(data2.substring(0,2),10);
	mf = parseInt(data2.substring(3,5),10);
	af = parseInt(data2.substring(6,10),10);
			
	datai = di + (mi*30) + (ai*365);
	dataf = df + (mf*30) + (af*365);
		
	return Math.floor((dataf - datai)/365);
}

function OnlyNumber(campo)
{
	keynum=event.keyCode;
	
	if((keynum < 48 || keynum > 57) && (keynum !=144 && keynum !=13 && keynum !=32 && keynum !=9 && keynum !=35 && keynum !=36 && keynum !=45 && keynum !=46 && keynum !=8) && (keynum < 96 || keynum > 105) && (keynum < 37 || keynum > 40))
	{ 
		event.returnValue=false;
	}
	else 
		return true;
}

function OnlyText(campo)
{
	keynum=event.keyCode;
	
	if((keynum < 48 || keynum > 57 ) && (keynum < 96 || keynum > 105))
	{
		event.returnValue=true;
	}
	else
	{	
		event.returnValue=false;
	}
}

function OnlyNone(campo)
{
	event.returnValue=false;
}

function BuscaListView(campo,intWidth,intHeight) // Função usada pela ListView
{
	if(campo.value == "")
	{
		alert("Você precisa especificar um parâmetro para busca!");
		return;
	}
	
	document.listview.filterf.value = campo.name;
	document.listview.filter.value = campo.value;

	var posx = (screen.width-intWidth)/2;
	var posy = (screen.height-intHeight)/2;
	win = window.open('','popup','width='+intWidth+',height='+intHeight)
	win.moveTo(posx,posy);
	win.focus();

	document.listview.submit();
}

function BuscaJacaView(campo,valor,jcampo) // Função usada pela JacaView argumentos: nome do campo desejado, valor do campo, campo de destino
{
	if(campo == "")
	{
		alert("Você precisa especificar um parâmetro para busca!");
		return;
	}
	document.jacaview.jaca.value = jcampo;
	document.jacaview.filterf.value = campo;
	document.jacaview.filter.value = valor;
	window.open('','jacaview','width=640,height=300')
	document.jacaview.submit();
}

// sintax: <input .... onkeydown="FormataCampo(this,event,'##/##:##-## ##:##')"> 
//exemplo: <input type="text" name="cpf" size="13" onkeydown="FormataCampo(this,event,'###.###.###-##')" maxlength="14">
function FormataCampo(Campo,teclapres,mascara)
{ 
	strtext = Campo.value 
	tamtext = strtext.length 
	tammask = mascara.length 
	arrmask = new Array(tammask)     
	
    for (var i = 0 ; i < tammask; i++)
        arrmask[i] = mascara.slice(i,i+1) 
    
    if (((((arrmask[tamtext] == "#") || (arrmask[tamtext] == "9"))) || (((arrmask[tamtext+1] != "#") || (arrmask[tamtext+1] != "9")))))
    { 
        if ((teclapres.keyCode >= 37 && teclapres.keyCode <= 40)||(teclapres.keyCode >= 48 && teclapres.keyCode <= 57)||(teclapres.keyCode >= 96 && teclapres.keyCode <= 105)||(teclapres.keyCode == 8)||(teclapres.keyCode == 9) ||(teclapres.keyCode == 46) ||(teclapres.keyCode == 13))
            OrganizaCasa(Campo,arrmask[tamtext],teclapres.keyCode,strtext)         
        else
            DetonaEvent(Campo,strtext) 
    } 
    else
    {
        if ((arrmask[tamtext] == "A"))
        { 
            charupper = event.valueOf() 
			DetonaEvent(Campo,strtext) 
            masktext = strtext + charupper 
            Campo.value = masktext 
        } 
    } 
}

function OrganizaCasa(Campo,arrpos,teclapres_key,strtext)
{ 
    if (((arrpos == "/") || (arrpos == "(") || (arrpos == ")") || (arrpos == ".") || (arrpos == ",") || (arrpos == ":") || (arrpos == " ") || (arrpos == "-")) && !(teclapres_key == 8))
    { 
        separador = arrpos 
        masktext = strtext + separador 
        Campo.value = masktext 
    } 
} 

function DetonaEvent(Campo,strtext)
{ 
    event.returnValue = false; 
    
    if (strtext != "")
        Campo.value = strtext 
} 

function LimpaList(list)
{
	for(i = list.options.length-1 ; i >= 0 ; i--)
			list.options[i] = null;
}

function SwapItem(i,obj) // Função que permite que um item de um listbox seja deslocado para cima(i = -1) ou para baixo(i = 1) 
{
	if((i == -1 &&  obj.selectedIndex == 0) || (i == 1 && obj.selectedIndex == (obj.length - 1)) || (obj.selectedIndex == 0 && i == 1 && distribuido == true))//|| (obj.selectedIndex == 1 && i == -1 && distribuido == true))
		return;
	
	label = obj.options[obj.selectedIndex + i].text;
	value = obj.options[obj.selectedIndex + i].value;
	
	obj.options[obj.selectedIndex + i].text = obj.options[obj.selectedIndex].text;
	obj.options[obj.selectedIndex + i].value = obj.options[obj.selectedIndex].value;
	
	obj.options[obj.selectedIndex].text = label;
	obj.options[obj.selectedIndex].value = value;
	
	obj.options[obj.selectedIndex + i].selected = true;	
}

function Capital(strInput,words) // Função que coloca as letras iniciais em maiuscula, e desconsidera as strings passadas como parâmetro
{
    var theString = strInput.value;
    var strOutput = ""; 
    var sp = " ";
    var small = false;
    var smallWords = words.split(",")
    theString = theString.replace(/(\s*)([^\s])/,"$2")
    theString = theString.toLowerCase();  
    var inputArray = theString.split(sp);
    strOutput = inputArray[0].slice(0,1).toUpperCase()+inputArray[0].slice(1);
    
    for (i = 1; i < inputArray.length; i++)
    { 
        small=false;
        
        for (ii=0;ii<smallWords.length;ii++)
        {
           if(inputArray[i] == smallWords[ii])
           		small = true;
        }
        
        if(!small) 
        	inputArray[i] = inputArray[i].slice(0,1).toUpperCase()+inputArray[i].slice(1);
        	
        strOutput = strOutput + sp + inputArray[i];  
    }
    
    strInput.value = strOutput;
}

function Calculadora(obj)
{
	if(obj.value.length > 0 && obj.value.indexOf('*') != -1)
		obj.value = obj.value.substring(0,obj.value.indexOf('*')) * obj.value.substring(obj.value.indexOf('*')+1); 
	else
		return;
	
	if(obj.value == 'NaN')
		obj.value = '';
}

function JumpField(obj,key)
{
	if(String.fromCharCode(event.keyCode) == key)
	{		
		obj.focus();
		return false;
	}
	return true;
}

function LimpaAcento(campo)
{
	tam = campo.length;
	aux = '';
	for (i = 0; i < tam; i++)
	{ 
		switch (campo.charAt(i))
		{
			case 'á':
			case 'à':
			case 'â':
			case 'ã': aux2 = 'a'; break;
			case 'Á':
			case 'À':
			case 'Â':
			case 'Ã': aux2 = 'A'; break;
			case 'é':
			case 'è':
			case 'ê': aux2 = 'e'; break;
			case 'É':
			case 'È':
			case 'Ê': aux2 = 'E'; break;
			case 'í':
			case 'ì':
			case 'î': aux2 = 'i'; break;
			case 'Í':
			case 'Ì':
			case 'Î': aux2 = 'I'; break;
			case 'ó':
			case 'ò':
			case 'ô':
			case 'õ': aux2 = 'o'; break;
			case 'Ó':
			case 'Ò':
			case 'Ô':
			case 'Õ': aux2 = 'O'; break;
			case 'ú':
			case 'ù':
			case 'û': aux2 = 'u'; break;
			case 'Ú':
			case 'Ù':
			case 'Û': aux2 = 'U'; break;
			case 'ç': aux2 = 'c'; break;
			case 'ñ': aux2 = 'n'; break;
			case 'Ñ': aux2 = 'N'; break;						
			case 'Ç': aux2 = 'C'; break;				
			default: aux2 = campo.charAt(i); break;
		}
		aux = aux + aux2;
	}
	return aux;
}

function TiraAcento(campo)
{ // além de tirar acentos já faz com que seja digitado somente letras maiúsculas
	//Aqui coloque ou retire caracteres, de acôrdo com sua utilização. 
	//Aqui coloque caracteres válidos 
	var CARACT = new RegExp(/^[A-Z ]+$/i); 
	var caract = new RegExp(/^[a-z ]+$/i); 	
	var nuloC  = new RegExp(/^[Ç]+$/i);
	var nuloc  = new RegExp(/^[ç]+$/i);
	var nuloA  = new RegExp(/^[ÁÀÃÂ]+$/i);
	var nuloa  = new RegExp(/^[áàãâ]+$/i);
	var nuloE  = new RegExp(/^[ÉÈÊ]+$/i);
	var nuloe  = new RegExp(/^[éèê]+$/i);
	var nuloI  = new RegExp(/^[ÍÌÎ]+$/i);
	var nuloi  = new RegExp(/^[íìî]+$/i);
	var nuloO  = new RegExp(/^[ÓÒÕÔ]+$/i);
	var nuloo  = new RegExp(/^[óòõô]+$/i);
	var nuloU  = new RegExp(/^[ÚÙÛ]+$/i);
	var nulou  = new RegExp(/^[úùû]+$/i);

	if (nuloC.test(String.fromCharCode(event.keyCode))) {event.keyCode=67;return;}
	if (nuloc.test(String.fromCharCode(event.keyCode))) {event.keyCode=99;return;}
	if (nuloA.test(String.fromCharCode(event.keyCode))) {event.keyCode=65;return;}
	if (nuloa.test(String.fromCharCode(event.keyCode))) {event.keyCode=97;return;}
	if (nuloE.test(String.fromCharCode(event.keyCode))) {event.keyCode=69;return;}
	if (nuloe.test(String.fromCharCode(event.keyCode))) {event.keyCode=101;return;}
	if (nuloI.test(String.fromCharCode(event.keyCode))) {event.keyCode=73;return;}
	if (nuloi.test(String.fromCharCode(event.keyCode))) {event.keyCode=105;return;}
	if (nuloO.test(String.fromCharCode(event.keyCode))) {event.keyCode=79;return;}
	if (nuloo.test(String.fromCharCode(event.keyCode))) {event.keyCode=111;return;}
	if (nuloU.test(String.fromCharCode(event.keyCode))) {event.keyCode=85;return;}
	if (nulou.test(String.fromCharCode(event.keyCode))) {event.keyCode=117;return;}

	var CARACT = CARACT.test(String.fromCharCode(event.keyCode)); 
	var caract = caract.test(String.fromCharCode(event.keyCode)); 	
}

function HideForm(nome_form){	
	document.forms[nome_form].style.visibility = "hidden";
}

function ShowForm(nome_form){
	document.forms[nome_form].style.visibility = "visible";
}

function ResizeImage(img, tmax) // recebe a imagem e a largura maxima
{
	var width = img.width;   // pega a largura da imagem
	var height = img.height; // pega a altura da imagem

	if(width > tmax)
	{
		fator = (width - tmax) / width;           // O fator representa o quanto a largura da imagem deve ser diminuida	
		width = tmax;                             // em porcentagem, para alcançar a largura máxima permitida
		height =  height - (height * fator);      // Depois usamos o fator para diminuir proporcionalmente a altura				 
	}

	img.width = parseInt(width);   // parseInt para arredondar o valor
	img.height = parseInt(height); // parseInt para arredondar o valor
}

function FormataMoeda(nome_form,campo,tammax,teclapres)
{
	var tecla = teclapres.keyCode;
	vr = document.forms[nome_form].elements[campo].value;
	
	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 < tammax && 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 ){ 
	 		document.forms[nome_form].elements[campo].value = vr ; }
	 	if ( (tam > 2) && (tam <= 5) ){
	 		document.forms[nome_form].elements[campo].value = vr.substr( 0, tam - 2 ) + ',' + vr.substr( tam - 2, tam ) ; }
	 	if ( (tam >= 6) && (tam <= 8) ){
	 		document.forms[nome_form].elements[campo].value = vr.substr( 0, tam - 5 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ; }
	 	if ( (tam >= 9) && (tam <= 11) ){
	 		document.forms[nome_form].elements[campo].value = vr.substr( 0, tam - 8 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ; }
	 	if ( (tam >= 12) && (tam <= 14) ){
	 		document.forms[nome_form].elements[campo].value = vr.substr( 0, tam - 11 ) + '.' + vr.substr( tam - 11, 3 ) + '.' + vr.substr( tam - 8, 3 ) + '.' + vr.substr( tam - 5, 3 ) + ',' + vr.substr( tam - 2, tam ) ; }
	 	if ( (tam >= 15) && (tam <= 17) ){
	 		document.forms[nome_form].elements[campo].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 ) ;}
	}	
}

function SaltaCampo (nome_form,campo,prox,tammax,teclapres)
{
	var tecla = teclapres.keyCode;
	vr = document.forms[nome_form].elements[campo].value;
	
 	tam = vr.length;
 	
 	if (tecla != 8 && tecla != 46 && tecla != 110 && tecla != 37 && tecla != 39 )
	{
		if ( tam == tammax )
		{
			document.forms[nome_form].elements[prox].focus();
		}
	}
}

function FormataTelefone(nome_form,campo,tammax,teclapres)
{
	var tecla = teclapres.keyCode;
	vr = document.forms[nome_form].elements[campo].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( "-", "" );
	tam = vr.length;

	if (tam < tammax && 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 ){ 
	 		document.forms[nome_form].elements[campo].value = vr ; }
	 	if ( (tam > 4) ){
	 		document.forms[nome_form].elements[campo].value = vr.substr( 0, tam - 4 ) + '-' + vr.substr( tam - 4, tam ) ; }
	}		
}

function MudaFoco(nome_form,campo)
{
	document.forms[nome_form].elements[campo].focus();
}

function CancelaEnterForm()
{
	return !(window.event && window.event.keyCode == 13);
}

function VerificaTamanho(campo_texto,campo_contador,maximo) 
{
	var StrLen;
	var corte;
	var nome;
	var adicional; 	
	adicional = 0;  // Caracteres que serão adicionados para formatar a mensagem.
	StrLen = adicional;
				
	corte = StrLen;
		
	if (document.form[campo_texto].value.length != "" )
	{
		StrLen = StrLen + document.form[campo_texto].value.length;
	}
	if (StrLen == 1 && document.form[campo_texto].value.substring(0,1) == " ")
    { 
       	document.form[campo_texto].value = "";
		StrLen = StrLen - 1;
    }
    if (StrLen > maximo) 
	{
		document.form[campo_texto].value = document.form[campo_texto].value.substring(0,maximo-corte);
		StrLen = StrLen - 1;
	}

    document.form[campo_contador].value = maximo - StrLen;
}

/////////////////////////////////////////////////
// Inicio das funcoes para formatar valor moeda
/////////////////////////////////////////////////

documentall = document.all;
/*
* função para formatação de valores monetários retirada de
* http://jonasgalvez.com/br/blog/2003-08/egocentrismo
*/

function formatamoney(c) {
    var t = this; if(c == undefined) c = 2;		
    var p, d = (t=t.split("."))[1].substr(0, c);
    for(p = (t=t[0]).length; (p-=3) >= 1;) {
	        t = t.substr(0,p) + "." + t.substr(p);
    }
    return t+","+d+Array(c+1-d.length).join(0);
}

String.prototype.formatCurrency=formatamoney

function demaskvalue(valor, currency){
/*
* Se currency é false, retorna o valor sem apenas com os números. Se é true, os dois últimos caracteres são considerados as 
* casas decimais
*/
var val2 = '';
var strCheck = '0123456789';
var len = valor.length;
	if (len== 0){
		return 0.00;
	}

	if (currency ==true){	
		/* Elimina os zeros à esquerda 
		* a variável  <i> passa a ser a localização do primeiro caractere após os zeros e 
		* val2 contém os caracteres (descontando os zeros à esquerda)
		*/
		
		for(var i = 0; i < len; i++)
			if ((valor.charAt(i) != '0') && (valor.charAt(i) != ',')) break;
		
		for(; i < len; i++){
			if (strCheck.indexOf(valor.charAt(i))!=-1) val2+= valor.charAt(i);
		}

		if(val2.length==0) return "0.00";
		if (val2.length==1)return "0.0" + val2;
		if (val2.length==2)return "0." + val2;
		
		var parte1 = val2.substring(0,val2.length-2);
		var parte2 = val2.substring(val2.length-2);
		var returnvalue = parte1 + "." + parte2;
		return returnvalue;
		
	}
	else{
			/* currency é false: retornamos os valores COM os zeros à esquerda, 
			* sem considerar os últimos 2 algarismos como casas decimais 
			*/
			val3 ="";
			for(var k=0; k < len; k++){
				if (strCheck.indexOf(valor.charAt(k))!=-1) val3+= valor.charAt(k);
			}			
	return val3;
	}
}

function reais(obj,event)
{
	var whichCode = (window.Event) ? event.which : event.keyCode;
	/*
	Executa a formatação após o backspace nos navegadores !document.all
	*/
	if (whichCode == 8 && !documentall) {	
	/*
	Previne a ação padrão nos navegadores
	*/
		if (event.preventDefault){ //standart browsers
				event.preventDefault();
			}else{ // internet explorer
				event.returnValue = false;
		}
		var valor = obj.value;
		var x = valor.substring(0,valor.length-1);
		obj.value= demaskvalue(x,true).formatCurrency();
		return false;
	}
	/*
	Executa o Formata Reais e faz o format currency novamente após o backspace
	*/
	FormataReais(obj,'.',',',event);
} // end reais


function backspace(obj,event)
{
	/*
	Essa função basicamente altera o  backspace nos input com máscara reais para os navegadores IE e opera.
	O IE não detecta o keycode 8 no evento keypress, por isso, tratamos no keydown.
	Como o opera suporta o infame document.all, tratamos dele na mesma parte do código.
	*/
	
	var whichCode = (window.Event) ? event.which : event.keyCode;
	if (whichCode == 8 && documentall) {	
		var valor = obj.value;
		var x = valor.substring(0,valor.length-1);
		var y = demaskvalue(x,true).formatCurrency();
	
		obj.value =""; //necessário para o opera
		obj.value += y;
		
		if (event.preventDefault){ //standart browsers
				event.preventDefault();
			}else{ // internet explorer
				event.returnValue = false;
		}
		return false;
	
	}// end if		
}// end backspace

function FormataReais(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 == 8 ) return true; //backspace - estamos tratando disso em outra função no keydown
if (whichCode == 0 ) return true;
if (whichCode == 9 ) return true; //tecla tab
if (whichCode == 13) return true; //tecla enter
if (whichCode == 16) return true; //shift internet explorer
if (whichCode == 17) return true; //control no internet explorer
if (whichCode == 27 ) return true; //tecla esc
if (whichCode == 34 ) return true; //tecla end
if (whichCode == 35 ) return true;//tecla end
if (whichCode == 36 ) return true; //tecla home

/*
O trecho abaixo previne a ação padrão nos navegadores. Não estamos inserindo o caractere normalmente, mas via script
*/

if (e.preventDefault){ //standart browsers
		e.preventDefault()
	}else{ // internet explorer
		e.returnValue = false
}

var key = String.fromCharCode(whichCode);  // Valor para o código da Chave
if (strCheck.indexOf(key) == -1) return false;  // Chave inválida

/*
Concatenamos ao value o keycode de key, se esse for um número
*/
fld.value += key;

var len = fld.value.length;
var bodeaux = demaskvalue(fld.value,true).formatCurrency();
fld.value=bodeaux;

/*
Essa parte da função tão somente move o cursor para o final no opera. Atualmente não existe como movê-lo no konqueror.
*/
  if (fld.createTextRange) {
    var range = fld.createTextRange();
    range.collapse(false);
    range.select();
  }
  else if (fld.setSelectionRange) {
    fld.focus();
    var length = fld.value.length;
    fld.setSelectionRange(length, length);
  }
  return false;

}

/////////////////////////////////////////////////
// Fim das funcoes para formatar valor moeda
/////////////////////////////////////////////////

String.prototype.extenso = function(c){
    var ex = [
        ["zero", "um", "dois", "três", "quatro", "cinco", "seis", "sete", "oito", "nove", "dez", "onze", "doze", "treze", "quatorze", "quinze", "dezesseis", "dezessete", "dezoito", "dezenove"],
        ["dez", "vinte", "trinta", "quarenta", "cinqüenta", "sessenta", "setenta", "oitenta", "noventa"],
        ["cem", "cento", "duzentos", "trezentos", "quatrocentos", "quinhentos", "seiscentos", "setecentos", "oitocentos", "novecentos"],
        ["mil", "milhão", "bilhão", "trilhão", "quadrilhão", "quintilhão", "sextilhão", "setilhão", "octilhão", "nonilhão", "decilhão", "undecilhão", "dodecilhão", "tredecilhão", "quatrodecilhão", "quindecilhão", "sedecilhão", "septendecilhão", "octencilhão", "nonencilhão"]
    ];
    var a, n, v, i, n = this.replace(c ? /[^,\d]/g : /\D/g, "").split(","), e = " e ", $ = "real", d = "centavo";
    for(var f = n.length - 1, l, j = -1, r = [], s = [], t = ""; ++j <= f; s = []){
        j && (n[j] = (("." + n[j]) * 1).toFixed(2).slice(2));
        if(!(a = (v = n[j]).slice((l = v.length) % 3).match(/\d{3}/g), v = l % 3 ? [v.slice(0, l % 3)] : [], v = a ? v.concat(a) : v).length) continue;
        for(a = -1, l = v.length; ++a < l; t = ""){
            if(!(i = v[a] * 1)) continue;
            i % 100 < 20 && (t += ex[0][i % 100]) ||
            i % 100 + 1 && (t += ex[1][(i % 100 / 10 >> 0) - 1] + (i % 10 ? e + ex[0][i % 10] : ""));
            s.push((i < 100 ? t : !(i % 100) ? ex[2][i == 100 ? 0 : i / 100 >> 0] : (ex[2][i / 100 >> 0] + e + t)) +
            ((t = l - a - 2) > -1 ? " " + (i > 1 && t > 0 ? ex[3][t].replace("ão", "ões") : ex[3][t]) : ""));
        }
        a = (s.length > 1 ? (a = s.pop(), s.join(" ") + " e " + a) : s.join("") || ((!j && (n[j + 1] * 1 > 0) || r.length) ? "" : ex[0][0]));
        a && r.push(a + (c ? (" " + (v.join("") * 1 > 1 ? j ? d + "s" : $.replace("l", "is") : j ? d : $)) : ""));
    }
    return r.join(e);
}

function checaCPF (CPF)
{
 	CPF = CPF.replace('.','');
 	CPF = CPF.replace('.','');
 	CPF = CPF.replace('-','');

	if (CPF.length != 11 || CPF == "00000000000" || CPF == "11111111111" ||
		CPF == "22222222222" ||	CPF == "33333333333" || CPF == "44444444444" ||
		CPF == "55555555555" || CPF == "66666666666" || CPF == "77777777777" ||
		CPF == "88888888888" || CPF == "99999999999")
		return false;
	soma = 0;
	for (i=0; i < 9; i ++)
		soma += parseInt(CPF.charAt(i)) * (10 - i);
	resto = 11 - (soma % 11);
	if (resto == 10 || resto == 11)
		resto = 0;
	if (resto != parseInt(CPF.charAt(9)))
		return false;
	soma = 0;
	for (i = 0; i < 10; i ++)
		soma += parseInt(CPF.charAt(i)) * (11 - i);
	resto = 11 - (soma % 11);
	if (resto == 10 || resto == 11)
		resto = 0;
	if (resto != parseInt(CPF.charAt(10)))
		return false;
	return true;
}

function validaEmail(email)
{ 
	if(email.indexOf("@")==-1 || email.indexOf(".")==-1)
		return false; 
	else
		return true;
}
