function FormataCpf(teclapres,campo) {
	var tecla = teclapres.keyCode;
	vr = campo.value;
		
	do { vr = vr.replace( "/", "" ); } while(vr.indexOf("/")>-1);
	do { vr = vr.replace( ",", "" ); } while(vr.indexOf(",")>-1);
	do { vr = vr.replace( ".", "" ); } while(vr.indexOf(".")>-1);
	do { vr = vr.replace( "-", "" ); } while(vr.indexOf("-")>-1);

	tam = vr.length;
	if (tecla == 8 ){	tam = tam - 1 ; }		
	if ( tecla == 8 || tecla >= 48 && tecla <= 57 || tecla >= 96 && tecla <= 105 ){
		if ( tam <= 2 ){ 
	 		campo.value = vr ; }		
	 	if ( (tam > 2) && (tam <= 5) ){
	 		campo.value = vr.substr( 0, tam - 2 ) + '-' + vr.substr( tam - 2, tam ) ; }
	 	if ( (tam >= 6) && (tam <= 8) ){
	 		campo.value = vr.substr( 0, tam - 5 ) + '.' + vr.substr( tam - 5, 3 ) + '-' + vr.substr( tam - 2, tam ) ; }
	 	if ( (tam >= 9) && (tam <= 11) ){
	 		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) ){
	 		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) ){
	 		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 valida_cpf(cpf){
	
	  if(cpf==""){return false;}			
		
	  do { cpf = cpf.replace(".",""); } while( cpf.indexOf(".")>-1 )
	  do { cpf = cpf.replace("-",""); } while( cpf.indexOf(".")>-1 )
      var numeros, digitos, soma, i, resultado, digitos_iguais;
      digitos_iguais = 1;
      if (cpf.length < 11) {alert("CPF invalido");return false;}
      for (i = 0; i < cpf.length - 1; i++)
            if (cpf.charAt(i) != cpf.charAt(i + 1))
            {
               digitos_iguais = 0;
               break;
            }	 
      if (!digitos_iguais)
      {
            numeros = cpf.substring(0,9);
            digitos = cpf.substring(9);
            soma = 0;
            for (i = 10; i > 1; i--)
                  soma += numeros.charAt(10 - i) * i;
            resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
            if (resultado != digitos.charAt(0))
			{
				  alert("CPF invalido");
                  return false;
			}
            numeros = cpf.substring(0,10);
            soma = 0;
            for (i = 11; i > 1; i--)
                  soma += numeros.charAt(11 - i) * i;
            resultado = soma % 11 < 2 ? 0 : 11 - soma % 11;
            if (resultado != digitos.charAt(1)) return true;
      }
      else {alert("CPF invalido");return false;} 
	  
	  return true;
}

function Upload(form,idcampo,funcao,iframe){
	
	_status           = document.getElementById(['status_webreporter']);
	_status.innerHTML = '<img src="/lib/2us/img/loading2_peq.gif" border="0" align="left">&nbsp;Aguarde...fazendo upload do arquivo';
	_idcampo          = idcampo;
	_idcampo2         = document.getElementById([idcampo+'2']);
	_div              = document.getElementById(['div_'+idcampo]);
	_form             = document.getElementById(form);
	_funcao           = funcao || "alert";	
	_iframe           = iframe;
	_display          = false;
	frames[iframe].document.body.innerHTML = 'uploading';
	_form.submit();
	setTimeout('UploadRetorno()',300);

}

function UploadRetorno(op,Retorno){
	
	if (op=='tamanho') {
		var tamanho=Retorno;
		_form.submit();
	}else if (op==undefined) {
		var resultiframe=frames[_iframe].document.body.innerHTML;
		resultiframe=resultiframe.replace(' ','');
				
		if (resultiframe!=''&&resultiframe!='uploading') {
			if (resultiframe!='ERRO'&&resultiframe!='ERRO files') {
				
				_status.innerHTML = 'Upload efetuado.';
				_form.reset();
				_idcampo2.value = resultiframe;
				if(typeof(_display ) != 'undefined')
				{
					if (_display) _div.style.display = 'none';
				}
				eval(_funcao+"('"+resultiframe+"')");
				
			}else{
				alert('Houve um erro no processamento do upload do arquivo.');
			}
		}else{
 		    setTimeout("UploadRetorno()",1000);
		}
	}
	
}


function MostraFoto(img){
	var foto = '';
	if(img&&img.substr(0,11)=='ERROtamanho') { 
	  tamanho=img.substr(11,50);
	  foto = '<div align="left" style="padding:5px;"><br><font color=#666666><img src="/lib/2us/icones/erro.png" border="0">&nbsp;<b>Este arquivo &eacute; muito grande para publica&ccedil;&atilde;o.<br>';
	  foto+= '<br>Por favor diminua o tamanho do arquivo, utilizando um software de edi&ccedil;&atilde;o de fotos ou servi&ccedil;os de edi&ccedil;&atilde;o online gratuitos como o <a href="http://www.picnik.com/" target="_blank">Picknik</a>, <a href="http://www.photoshop.com/express" target="_blank">Photoshop Express</a> ou <a href="http://www.splashup.com/" target="_blank">SlashUp</a>.';
	  foto+= '<br><br>Uma sugest&atilde;o &eacute; diminuir a largura da foto para 640px.';
	  foto+= '<br><br>O arquivo est&aacute; com '+tamanho+' bytes.';
	  foto+= '<br><br>O tamanho m&aacute;ximo do arquivo aceito &eacute; 500Kb.</font></b></div>'; 
	  document.getElementById('FotowebReporter').innerHTML=foto;   
	  return;
	}
	if(img) foto = '<img src="diminuator.php?arquivo=img/'+img+'&h=225" style="border: solid 3px #dadada;">';
	document.getElementById('FotowebReporter').style.border='';
	document.getElementById('FotowebReporter').style.height='';
	document.getElementById('FotowebReporter').style.width='';
	document.getElementById('FotowebReporter').innerHTML=foto;
}

function AjustaLarguraDiv(){
	document.getElementById('FotowebReporter').style.overflow='auto';
	document.getElementById('status_Foto').style.display='none';
}

function EnviarwebReporter(){
	var Nome = document.getElementById('Nome').value;
	var CPF = document.getElementById('CPF').value;
	var Email = document.getElementById('Email').value;
	var Titulo = document.getElementById('TituloFoto').value;
	var Texto = document.getElementById('Texto').value;
	var Foto = document.getElementById('Foto2').value;
	var Termos = document.getElementById('Termos').checked;
	if(!Nome||!CPF||!Titulo||!Texto||!Termos||!Foto||Email.indexOf('@')==-1||!valida_cpf(CPF)){
		document.getElementById('MsgNome').className='';
		document.getElementById('MsgCPF').className='';
		document.getElementById('MsgEmail').className='';
		document.getElementById('MsgTituloFoto').className='';
		document.getElementById('MsgLegenda').className='';
		document.getElementById('MsgTermos').className='';
		var retorna = '<b>O(s) seguinte(s) campo(s) deve(m) ser preenchido(s):</b><br>';
		if(!Nome)  {retorna+='<a class="Erro">Nome,</a> ';   document.getElementById('MsgNome').className='Alerta';}
		if(!CPF)   {retorna+='<a class="Erro">CPF,</a> ';    document.getElementById('MsgCPF').className='Alerta';}
		if(!Email) {retorna+='<a class="Erro">Email,</a> ';  document.getElementById('MsgEmail').className='Alerta';}
		if(!Titulo){retorna+='<a class="Erro">Titulo,</a> '; document.getElementById('MsgTituloFoto').className='Alerta';}
		if(!Texto) {retorna+='<a class="Erro">Legenda,</a> ';document.getElementById('MsgLegenda').className='Alerta';}
		if(!Termos){retorna+='<a class="Erro">Aceitar os termos,</a> ';document.getElementById('MsgTermos').className='Alerta';}
		if(!Foto)  {retorna+='<a class="Erro">Upload da Foto,</a> ';}
		if(!valida_cpf(CPF))      {retorna+='<a class="Erro">CPF inv&aacute;lido,</a> ';   document.getElementById('MsgCPF').className='Alerta';}
		if(Email.indexOf('@')==-1){retorna+='<a class="Erro">E-mail inv&aacute;lido.</a> ';document.getElementById('MsgEmail').className='Alerta';}
		retorna = retorna.substr(0,retorna.length-5);
		retorna+='<br>Os dados n&atilde;o foram enviados.';
		document.getElementById('status_webreporter').innerHTML = retorna;
	} else {
		var valores = 'Nome='+Nome+'&CPF='+CPF+'&Email='+Email+'&Titulo='+Titulo+'&Texto='+Texto+'&Foto='+Foto;
		document.getElementById('status_webreporter').innerHTML = '<img src="/lib/2us/img/loading2_peq.gif" align="left">&nbsp;Aguarde...';
		var objAjax = new AjaxLib();
		objAjax.processa("formulario.php",'grava_webreporter',valores,'TEXT',RetornawebReporter,'POST');		
	}
}

function RetornawebReporter(op,result){
	switch(op){
		case "grava_webreporter" :
			document.getElementById('status_webreporter').innerHTML = result;
			break;
	}
}		

function AjaxLib(){
	
	//var obj = new AjaxLib();
	//obj.processa(arquivo,op,valores,tiporetorno,funcao);
	
	req = null;
    if (window.XMLHttpRequest) { // Mozilla/Firefox/Safari
        req = new XMLHttpRequest();
    } else if (window.ActiveXObject) { // Internet Explorer
        req = new ActiveXObject("Microsoft.XMLHTTP");
    }
	if (req) {
		this.processa=function(arquivo,op,valores,tiporetorno,funcao,metodo){
		
			metodo      = metodo || 'GET';
			tiporetorno = tiporetorno || 'TEXT';
			valores     = valores || '';
			funcao      = funcao || ProcessaRetorno;
			var resultado = '';
			
			if(arquivo.indexOf("?op=")>-1){
				op = arquivo.substr(eval(arquivo.indexOf("?op=")+4),arquivo.length) || op;
				var arquivo = arquivo.substr(0,arquivo.indexOf("?op="));			
			}
						
			var variaveis = 'op='+encodeURI(op)+'&'+valores;
			for(xx=0;xx<variaveis.indexOf('&&');xx++){variaveis = variaveis.replace('&&','&');}
						
			req.onreadystatechange = function(){
				if (req.readyState == 4) {
			        if (req.status == 200 || req.status == 0) {	
						if (tiporetorno=='XML'){ resultado=req.responseXML; }else{ resultado=req.responseText; }
						if (req.responseText == '') return false; // nao tem retorno
						if (funcao) funcao(op,resultado);
	    			} else {
            			switch(req.status){
                                case 204: { alert("Erro Ajax: O servidor n&atilde;o respondeu ao chamado."); break }
                                case 400: { alert("Erro Ajax: Endere&ccedil;o inv&aacute;lido."); break }
                                case 403: { alert("Erro Ajax: Voc&ecirc; n&atilde;o possui permiss&atilde;o para acessar esse arquivo."); break }
                                case 404: { alert("Erro Ajax: Arquivo n&atilde;o encontrado."); break }
                                case 500: { alert("Erro Ajax: Erro interno do servidor."); break }
                                case 502: { alert("Erro Ajax: Servidor ocupado."); break }
                                case 503: { alert("Erro Ajax: O servidor n&atilde;o respondeu no tempo limite."); break }
                                 default: { alert("Erro Ajax: Algum erro ocorreu ao carregar este conte&uacute;do."); break }
                        }
        			}
    			}				
			}
			variaveis=this.antiCache(variaveis);
			
			if(metodo.toUpperCase()=='POST'){ var arquivofinal = arquivo; } else { var arquivofinal = arquivo+'?'+variaveis; var variaveis=null; }
			
			req.open(metodo, arquivofinal, true);
			req.setRequestHeader('Content-Type', "application/x-www-form-urlencoded; charset=iso-8859-1");
			req.send(variaveis);
			
		}
		this.antiCache = function(aurl){
    		var dt = new Date();
       		return aurl + "&" + encodeURI(Math.random() + "_" + dt.getTime());
	    } 
	}

}

