/*################################################################
       Funcao para ocultar/mostrar um item
	   Copiada da Internet e adaptada
################################################################*/
function ocultarMostrar(sId){
       var sDiv = document.getElementById(sId);
       if(sDiv.style.display=="none")
	   	  $("#"+sId).slideDown("slow");
       else
       	  $("#"+sId).slideUp("slow");
}
/*################################################################
       Funcao para abrir pagina sem atualizar todo o conteudo
	   Copiada da Internet e adaptada
################################################################*/
function abrirLink(url,campo){
	elem=campo;
	document.getElementById('carregando').style.visibility="visible";
	if(window.XMLHttpRequest){
		req=new XMLHttpRequest();
	}else if(window.ActiveXObject){
		req=new ActiveXObject("Microsoft.XMLHTTP");
	}else{
		alert("Seu navegador n&atilde;o suporta XMLHttpRequest.");
		return;
	}
	req.open("GET",url,true);
	req.onreadystatechange=processReqChange;
	req.send(null);
}

function processReqChange(){
	if(req.readyState==4){
		if(req.status==200){
			document.getElementById('carregando').style.visibility="hidden";
			var texto=unescape(req.responseText.replace(/\+/g ," "));
			document.getElementById(elem).innerHTML=texto;
		}
	}
}

/*Funcao para abrir pagina sem atualizar todo o conteudo Mostrando uma imagem de "loading" no
local onde vai ser inserido o conteúdo*/
function loadingLink(url,campo){
	elem=campo;
	document.getElementById(elem).innerHTML="carregando <img src='/co5/imagem/carregando.gif' />";
	if(window.XMLHttpRequest){
		reqisicao=new XMLHttpRequest();
	}else if(window.ActiveXObject){
		reqisicao=new ActiveXObject("Microsoft.XMLHTTP");
	}else{
		alert("Seu navegador n&atilde;o suporta XMLHttpRequest.");
		return;
	}
	reqisicao.open("GET",url,true);
	reqisicao.onreadystatechange=processReqChange2;
	reqisicao.send(null);
}

function processReqChange2(){
	if(reqisicao.readyState==4){
		if(reqisicao.status==200){
			var texto=unescape(reqisicao.responseText.replace(/\+/g ," "));
			document.getElementById(elem).innerHTML=texto;
		}
	}
}
/*################################################################
       Funcao para texto em um campo de formulario
	   Copiada da Internet e adaptada
################################################################*/
function $(x){
	return document.getElementById(x);
}
function copyClipboard(elt){
	var id = 'flash';
	var url = '/co5/2s/clipboard.swf';	
	if(!$(id)){
		var div = document.createElement('div');
		div.id = id;document.body.appendChild(div);
	}
	$(id).innerHTML = '';
	var d = '<embed src="' + url + '" FlashVars="clipboard='+escape(elt.value)+'" width="0" height="0" type="application/x-shockwave-flash"></embed>';
	$(id).innerHTML = d;
	elt.select();
}
/*#############################################################################################################
                                  Campos Obrigatorios
	  			Copiada da Internet e adaptada
//############################################################################################################*/
function checkrequired(which){
  var pass=true;
  if (document.images){
  	for (i=0;i<which.length;i++){
  		var tempobj=which.elements[i];
  		if(tempobj.title.substring(0,11)=="Obrigatorio"){
  			if(!(((tempobj.type=="text"||tempobj.type=="textarea"||tempobj.type=="password")&&tempobj.value=='')||(tempobj.type.toString().charAt(0)=="s"&&tempobj.selectedIndex==0))){
  				document.getElementById(tempobj.id).style.background="white";
        	}
  			if(((tempobj.type=="text"||tempobj.type=="textarea"||tempobj.type=="password")&&tempobj.value=='')||(tempobj.type.toString().charAt(0)=="s"&&tempobj.selectedIndex==0)){
  				pass=false;
 				break;
        	}
    	}
     }
  }
  if(!pass){
	shortFieldName=tempobj.name.substring(0,30).toUpperCase();
	document.getElementById('alerta_required').innerHTML="Os campos em VERMELHO devem ser preenchidos!";
	document.getElementById(tempobj.id).style.background="red";
	document.getElementById(tempobj.id).focus();
	return false;
  }else{
	document.getElementById('alerta_required').innerHTML="";
	document.getElementById(tempobj.id).style.background="white";
	return true;
  }
}
/*#############################################################################################################
                                  Validacao de formulario
Adaptado de:
			JavaScript Document
			@Validador Universal
			@copyleft (cc) 2008 UNIFACS - Desenvolvimento Web Sites - Turma 04. Alguns direitos reservados
			@licence http://www.gnu.org/licence/lgpl.html LGPL Licence
			@author Lucas Figueiredo - lukas.figueiredo@hotmail.com
			@author Gustavo Ramalho - gustavo@xisweb.com.br
			@author Elton Augusto - elton18augusto@hotmail.com
			@author Anderson Andrade - andrades23@gmail.com
//############################################################################################################*/
function valida_digitos(Ncampo,Tcampo){
		 //caracteres permitidos
		 if(Tcampo=="nome")
		 er=/[0-9]/; 
		 if(Tcampo=="cep" || Tcampo=="cpf" || Tcampo=="rg" || Tcampo=="data" || Tcampo=="telefone" || Tcampo=="numero")
		 er=/[a-z]/;		 
		 digito=document.getElementById(Ncampo).value;
		 var tempor;
		 
		  for (var i=0;i<digito.length; i++) {
			tempor=digito.substring(i,i+1); 
			//se digitos não igual aos caracteres informado na variavel digitos, então é deletado
			  if (er.test(digito)) {
			  document.getElementById(Ncampo).value=digito.substring(0,digito.length-1);
			 
			 return false;
			  break;
    		}
   		}
 }

function erro(Ncampo){
	document.getElementById(Ncampo).style.background="red";
	document.getElementById('resposta'+Ncampo).innerHTML="Por favor informe o(a) "+Ncampo+"!";
	document.getElementById(Ncampo).focus();
	return false;
}

function valida_campos(Ncampo){   
		//de acorodo com o campo a var er recebe uma expressão regular que vai vlaidar o campo exceto  CPF,CEP e Data que valida atrave da função
		//validar_CPF()		
			if(Ncampo=="senha")
				var er =/^\w{3,6}$/;
			if(Ncampo=="rg")
				var er =/^[0-9]{8}-[0-9]{2}$/;		
			if(Ncampo=="nome")
				var er=/[a-zA-Z]{3,}/;
			if(Ncampo=="email")
				var er=/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,4})+$/
				
			b=document.getElementById(Ncampo).value;
			if(b != "")
			{ 
				if(!er.test(b))
					return erro(Ncampo);			
				//se Ncampo passar na ER, então é feita a formatação do campo CEP = xxxxx-xxx
				else
					return ok(Ncampo);					
			}
			document.getElementById(Ncampo).style.background="#FFFFFF";
	 		document.getElementById('resposta'+Ncampo).innerHTML="";
			
}
//função que formata os campos - auto completa os campos cep,cpf,rg e data
function formata(Ncampo,Tcampo)
{
	var campo=document.getElementById(Ncampo).value;
	var str;
	var str2;
	var str3;

	if(Tcampo=='cep')
	{	
		if(campo.length==5)
		{	
			var str=campo.substring(0,5);
			document.getElementById(Ncampo).value=str+"-";
		}
	}

        if(Tcampo=='data')
	{	
		if(document.getElementById(Ncampo).value.length==2)
		{	
			var str=document.getElementById(Ncampo).value.substring(0,2);
			pt1=document.getElementById(Ncampo).value=str+"/";
		}
		if(document.getElementById(Ncampo).value.length==5)
		{	
			var str2=document.getElementById(Ncampo).value.substring(3,5);
			pt2=document.getElementById(Ncampo).value=pt1+str2+"/";
		}
	}
	
	if(Tcampo=='telefone')
	{	
		if(document.getElementById(Ncampo).value.length==2)
		{	
			var str=document.getElementById(Ncampo).value.substring(0,2);
			pt1=document.getElementById(Ncampo).value=str+"-";
		}
		if(document.getElementById(Ncampo).value.length==7)
		{	
			var str2=document.getElementById(Ncampo).value.substring(3,7);
			pt2=document.getElementById(Ncampo).value=pt1+str2+"-";
		}
	}
	
	if(Tcampo=="rg")
	{
		if(document.getElementById(Ncampo).value.length==2)
		{	
			var str=document.getElementById(Ncampo).value.substring(0,2);
			pt1=document.getElementById(Ncampo).value=str+".";
		}
		if(document.getElementById(Ncampo).value.length==6)
		{	
			var str2=document.getElementById(Ncampo).value.substring(3,6);
			pt2=document.getElementById(Ncampo).value=pt1+str2+".";
		}
		if(document.getElementById(Ncampo).value.length==10)
		{	
			var str3=document.getElementById(Ncampo).value.substring(7,12);
			pt3=document.getElementById(Ncampo).value=pt2+str3+"-";
		}
	}
	
	
	if(Tcampo=="cpf")
	{
		if(document.getElementById(Ncampo).value.length==3)
			{
				
				valor=document.getElementById(Ncampo).value;
				str=document.getElementById(Ncampo).value.substring(0,3);
				result=valor.replace(valor,str+'.');
				document.getElementById(Ncampo).value=result;
			}
		if(document.getElementById(Ncampo).value.length==7)
			{
				valor1=document.getElementById(Ncampo).value;
				str2=document.getElementById(Ncampo).value.substring(4,8);
				result2=valor1.replace(valor1,str2+'.');
				document.getElementById(Ncampo).value=result + result2;
			}
		if(document.getElementById(Ncampo).value.length==11)
			{
				valor2=document.getElementById(Ncampo).value;
				str3=document.getElementById(Ncampo).value.substring(8,11);

				result3=document.getElementById(Ncampo).value=result + result2 + str3 + "-";
			}
		if(document.getElementById(Ncampo).value.length==15)
			{
				valor3=document.getElementById(Ncampo).value;
				str3=document.getElementById(Ncampo).value.substring(12,15);
				result4=valor3.replace(valor3,str3);
				document.getElementById(Ncampo).value=result + result2 + result3 + result4;
			}
					
	}
	
}
//function que valida, data pelo formato xx/xx/xxxx e verifica se a data existe
function validar_Data(Ncampo,Tcampo){

var er=/^(([0-2]\d|[3][0-1])\/([0]\d|[1][0-2])\/[1-2][0-9]\d{2})$/;
b=document.getElementById(Ncampo).value;
document.getElementById(Ncampo).style.background="#98EE84";
document.getElementById('resposta'+Ncampo).innerHTML="";
if(b!=""){
if(er.test(b)){

var dia=b.substring(0,2);
var mes=b.substring(3,5);
var ano=b.substring(6,10);
	
	if(ano < 1940)
	{
		alert("O ano especificado não é valido");
		document.getElementById(Ncampo).style.background="red";
		//document.getElementById('resposta'+Ncampo).innerHTML="O ano especificado não é válido";
		document.getElementById(Ncampo).focus();
		return false;
	}
	
		if((mes==04 || mes==06 || mes==09 || mes==11) && (dia > 30)){
			document.getElementById(Ncampo).style.background="red";
			alert("O mês especificado contém no máximo 30 dias");
			//document.getElementById('resposta'+Ncampo).innerHTML="O mês especificado contém no máximo 30 dias";
			document.getElementById(Ncampo).focus();
			return false;
		} else
		{
		if(ano%4!=0 && mes==02 && dia>28){
			document.getElementById(Ncampo).style.background="red";
			alert("Data incorreta!! O mês especificado contém no máximo 28 dias.");
			//document.getElementById('resposta'+Ncampo).innerHTML="Data incorreta!! O mês especificado contém no máximo 28 dias.";
			document.getElementById(Ncampo).focus();
			return false;
		} else{
		if(ano%4==0 && mes==02 && dia>29){
			document.getElementById(Ncampo).style.background="red";
			alert("Data incorreta!! O mês especificado contém no máximo 29 dias");
			//document.getElementById('resposta'+Ncampo).innerHTML="Data incorreta!! O mês especificado contém no máximo 29 dias";
			document.getElementById(Ncampo).focus();
			return false;
		} else{ 
		//alert ("Data correta!");
		return ok(Ncampo);
		}}}} else {
			document.getElementById(Ncampo).style.background="red";
			//alert("Formato inválido de data");
			document.getElementById('resposta'+Ncampo).innerHTML="Formato inválido de data";
			document.getElementById(Ncampo).focus();
			return false;
		}
		}
		document.getElementById(Ncampo).style.background="#FFFFFF";
		document.getElementById('resposta'+Ncampo).innerHTML="";
}
//função que restringe caracteres digitados. Números ou letras
function valida_digitos(Ncampo,Tcampo)
{
		 //caracteres permitidos
		 if(Tcampo=="nome")
		 er=/[0-9]/; 
		 if(Tcampo=="cep" || Tcampo=="cpf" || Tcampo=="rg" || Tcampo=="data" || Tcampo=="telefone" || Tcampo=="numero")
		 er=/[a-z]/;		 
		 digito=document.getElementById(Ncampo).value;
		 var tempor;
		 
		  for (var i=0;i<digito.length; i++) {
			tempor=digito.substring(i,i+1); 
			//se digitos não igual aos caracteres informado na variavel digitos, então é deletado
			  if (er.test(digito)) {
			  document.getElementById(Ncampo).value=digito.substring(0,digito.length-1);
			 
			 return false;
			  break;
    		}
   		}
 }

/*#############################################################################################################
                                  Upload de arquivos
//############################################################################################################*/
function startUpload(){
      document.getElementById('carregandoUpload').style.visibility = 'visible';
      document.getElementById('upload').style.visibility = 'hidden';
      return true;
}

function stopUpload(resp){

      document.getElementById('carregandoUpload').style.visibility = 'hidden';
      document.getElementById('respostaUpload').innerHTML = resp;
      document.getElementById('upload').style.visibility = 'visible';      
      return true;   
}

// Script adaptado da internet
function verificaExtensao(formulario, arquivo, resposta) {
   extensoes_permitidas = new Array(".jpg", ".jpeg");
   msgResp = "";
   if (!arquivo){
      //Se não tenho arquivo, é porque não se selecionou um arquivo no formulário.
       msgResp = "Não foi selecionado nenhum arquivo";
   }else{
      //recupero a extensão deste nome de arquivo
      extensao=(arquivo.substring(arquivo.lastIndexOf("."))).toLowerCase();
      //alert (extensao);
      //comprovo se a extensão está entre as permitidas
      permitida = false;
      for (var i = 0; i < extensoes_permitidas.length; i++) {
         if (extensoes_permitidas[i] == extensao) {
         	permitida = true;
         	break;
         }
      }
      if (!permitida) {
         msgResp = "Extensão na suportada, favor envie apenas imagens JPG.";
      }else{
          //submeto!
		   document.getElementById(resposta).innerHTML="Enviando seu arquivo...";
         formulario.submit();
         return true;
      }
   }
   //se estou aqui é porque não se pode submeter
   document.getElementById(resposta).innerHTML=msgResp;
   return false;
}