function show(element){
	if($(element).style.display=='none'){
		$(element).style.display='';
	} else {
		$(element).style.display='none';
	}
}
function popup(url, w, h) {
    var lado = (screen.width - w) / 2;
    var topo = (screen.height - h) / 2;
    janela = window.open(url, '', 'height='+h+', width='+w+', top='+topo+', left='+lado+', scrollbars=yes');		
	janela.focus();
}

function showNotificacao(pagina){
	var w = window.screen.availWidth-100;
	var h = window.screen.availHeight-250;
	var win = new Window({className: "alphacube", 
						  width:w, 
						  height:h, 
						  zIndex: 100, 
						  resizable: true, 
						  title: "Notifica&ccedil;&atilde;o", 
						  draggable:true, 
						  wiredDrag: true, 
						  url: pagina
						  }) 
	win.setConstraint(true, {left:0, right:20, top: 0, bottom:0});
	win.showCenter();
	return false;
}
function showConvite(pagina){
	var w = window.screen.availWidth-100;
	var h = window.screen.availHeight-250;
	var win = new Window({className: "alphacube", 
						  width:w, 
						  height:h, 
						  zIndex: 100, 
						  resizable: true, 
						  title: "Dados do Convite", 
						  draggable:true, 
						  wiredDrag: true, 
						  url: pagina
						  }) 
	win.setConstraint(true, {left:0, right:20, top: 0, bottom:0});
	win.showCenter();
	return false;
}
function exibirAviso(tipo, obj_id){
	var w = window.screen.availWidth-100;
	var h = window.screen.availHeight-250;
	var win = new Window({className: "alphacube", 
						  width:w, 
						  height:h, 
						  zIndex: 100, 
						  resizable: true, 
						  title: "Exibindo '"+tipo+"/"+obj_id+"'", 
						  draggable:true, 
						  wiredDrag: true, 
						  url: "admin/"+tipo+"/avisos/exibir/"+obj_id
						  }) 
	win.setConstraint(true, {left:0, right:20, top: 0, bottom:0});
	win.showCenter();
	return false;
}
function enviarParaCPN(tipo, id){
	Dialog.alert('<div id="teste">Enviando...<br /><img src="images/admin/loading.gif" alt="Carregando..." /></div>', 
             {className:"alphacube",width:300, height:150, okLabel: "Fechar"});
	
	var url = 'cpr.php/admin/functions/enviarParaCPN/'+tipo+'/'+id;
	var pars = '';
		
	var myAjax = new Ajax.Request( url, { method: 'get', parameters: pars, onComplete: confirmaEnvio });
}
function confirmaEnvio(r){
	$('teste').innerHTML = r.responseText;
	//Dialog.alert(r.responseText, 
    //         {className:"alphacube",width:300, height:150, okLabel: "Fechar"});
}

function validaContato(form){
	var msg = '<h3 style="color:red;">Corrija os seguintes erros:</h3><br />';
	var erro = false;
	if(form.nome.value == ''){
		msg += "Preencha seu nome<br />";
		erro = true;
	}
	if(form.email.value == ''){
		msg += "Preencha seu email<br />";
		erro = true;
	}
	if(form.destinatario.value == ''){
		msg += "Selecione um destinat&aacute;rio<br />";
		erro = true;
	}
	if(form.comentario.value == ''){
		msg += "Preencha o campo coment&aacute;rio<br />";
		erro = true;
	}
	if(!erro)
		return true;
	else {
		//alert(msg);
		Dialog.alert(msg, 
             {className:"alphacube",width:300, height:150, okLabel: "Fechar"});
		return false;
	}
}
/* Abre uma janela para enviar para amigo */
function enviarAmigo(){
	var enviaAmigo = new Window({className: "alphacube", title: "Enviar para um amigo", constraint: {top: 30, bottom:10}, 
								top:70, left:100, width:300, height:200, 
	url: "/utilidades/enviarAmigo/"+window.location.href, showEffectOptions: {duration:1.5}})
	enviaAmigo.setConstraint(true, {left:5, right:25, top: 5, bottom:10})
	enviaAmigo.toFront();
	enviaAmigo.showCenter();
}
function validaEnviarAmigo(form){
	var msg = "Corrija os seguintes erros:\n";
	var erro = false;
	if(form.nome.value == ''){
		msg += "Preencha seu nome\n";
		erro = true;
	}
	if(form.email.value == ''){
		msg += "Preencha seu email\n";
		erro = true;
	}
	if(form.nomeAmigo.value == ''){
		msg += "Preencha o nome do seu amigo\n";
		erro = true;
	}
	if(form.emailAmigo.value == ''){
		msg += "Preencha o email do seu amigo\n";
		erro = true;
	}
	if(!erro)
		return true;
	else {
		alert(msg);
		return false;
	}
}
/* Abre uma janela para inserir comentários */
function addComment(form){
	/* Faz a validação dos campos */
	cpr = form.elements[0];
	arquivo = form.elements[1];
	message = '<h3 style="color:red">Ocorreram os seguintes erros:</h3>';
	message +='<p style="text-align:left;padding-left:20px;padding-top:5px;">';
	validou = true;
	if(cpr.options[cpr.selectedIndex].value == ''){
		message += "Preencha o campo CPR<br />";
		validou = false;
	}
	if(arquivo.value == ''){
		message += "Preencha o campo Arquivo<br />";
		validou = false;
	}
	message += '</p>';
	if(!validou){
		Dialog.alert(message, 
             {className:"alphacube",width:300, height:150, okLabel: "Fechar"});
		return false;
	}
	return true;
	
	/* se passar na validação envia o comentario 
	var cpr_id = cpr.options[cpr.selectedIndex].value;
	var proposta_id = form.elements[2].value;
	var url = 'http://www.cpn-nr18.com.br/propostas/addComment/'+proposta_id+'/'+cpr_id;
	var pars = 'proposta_id='+proposta_id+'&cpr_id='+cpr_id;
	var idRecebe = (numComment == '0') ? 'loadUp' : 'loadUp_'+numComment;
	micoxUpload(form, url, idRecebe, 'Enviando...', 'Erro ao carregar');
	//var myAjax = new Ajax.Request( url, { method: 'get', parameters: pars, onComplete: montaCkbcidades }); 
	*/
	
}

/* Popula o combo de cidades de acordo com o combo de estado */
function ckbCidades(){
	var uf = $('estado').value;
	var mun = $('municipio');
	var url = 'http://www.cpn-nr18.com.br/admin/functions/populaCidades/'+uf;
	var pars = '';
		
	var myAjax = new Ajax.Request( url, { method: 'get', parameters: pars, onComplete: montaCkbcidades }); 
}
function montaCkbcidades(request){
	cidades = request.responseXML.getElementsByTagName("cidades");
	cidades = request.responseXML.getElementsByTagName("cidade");
	if(cidades.length > 0){
		$('municipio').options.length = 0;
	    $('municipio').selectedIndex = 0;
		for(i=0; i<cidades.length; i++){
			var nome = pegaValor(cidades[i].getElementsByTagName('nome')[0]);
			var id = pegaValor(cidades[i].getElementsByTagName('id')[0]);
			if(id == '' || id == null || id == 'null'){
				id = '';
			}
			$('municipio').options[i] = new Option(nome, id);
		}
	}
}

function pegaValor(no){
    if(no.childNodes.length>0){
            return no.firstChild.nodeValue; //Tem filho
      } else {
            try{
                  return no.nodeValue;
            } catch (e) {
            return "";
        }
      }
}


/** 
 * Funo que formata um campo do formulrio de 
 * acordo com a mscara informada... 
 *
 * Parmetros: 
 *  => objForm (o Objeto Form);
 *  => strField (string contendo o nome do textbox); 
 *  => sMask (mascara que define o formato que o dado ser apresentado, 
 *            usando o algarismo "9" para definir nmeros e o smbolo "!" para 
 *            qualquer caracter... 
 *  => evtKeyPress (evento);
 *
 * Uso..: <input type="textbox" name="xxx" 
 * onkeypress="return txtBoxFormat(document.rcfDownload, 'str_cep', '99999-999', event);"> 
 * 
 * Observao: As mscaras podem ser representadas como os exemplos abaixo: 
 * CEP -> 99.999-999  
 * CPF -> 999.999.999-99 
 * RG -> 99.999.999-9
 * CNPJ -> 99.999.999/9999-99 
 * Data -> 99/99/9999 
 * Tel Resid -> (99) 999-9999 
 * Tel Cel -> (99) 9999-9999 
 * Processo -> 99.999999999/999-99 
 * Inscrio Estadual -> 999.999.999-9999
 * C/C -> 999999-! 
 * E por a vai... 
 **/
function format(field, sMask, evtKeyPress) {

   var i;
   var nCount;
   var sValue;
   var fldLen;
   var mskLen;
   var bolMask;
   var sCod;
   var nTecla;

   if(document.all) { // Internet Explorer
      nTecla = evtKeyPress.keyCode; 
   }
   else 
   if(document.layers) { // Nestcape
      nTecla = evtKeyPress.which;
   }

   sValue = field.value;

   // Limpa todos os caracteres de formatao que
   // j estiverem no campo.
   sValue = sValue.toString().replace( "-", "" );
   sValue = sValue.toString().replace( "-", "" );
   sValue = sValue.toString().replace( ".", "" );
   sValue = sValue.toString().replace( ".", "" );
   sValue = sValue.toString().replace( "/", "" );
   sValue = sValue.toString().replace( "/", "" );
   sValue = sValue.toString().replace( "(", "" );
   sValue = sValue.toString().replace( "(", "" );
   sValue = sValue.toString().replace( ")", "" );
   sValue = sValue.toString().replace( ")", "" );
   sValue = sValue.toString().replace( " ", "" );
   sValue = sValue.toString().replace( " ", "" );
  
   fldLen = sValue.length;
   mskLen = sMask.length;

   i = 0;
   nCount = 0;
   sCod = "";
   mskLen = fldLen;

   while (i <= mskLen) 
   {
       bolMask = ((sMask.charAt(i) == "-") || (sMask.charAt(i) == ".") || (sMask.charAt(i) == "/"))
       bolMask = bolMask || ((sMask.charAt(i) == "(") || (sMask.charAt(i) == ")") || (sMask.charAt(i) == " "))

       if (bolMask) 
	   {  sCod += sMask.charAt(i);
          mskLen++; 
	   }
       else {
         sCod += sValue.charAt(nCount);
         nCount++;
       }
       i++;
   }

   field.value = sCod;
   if (nTecla != 9 && nTecla != 8 && nTecla != 46)  {
       if (sMask.charAt(i-1) == "9")  // apenas nmeros...
	   {   return ((nTecla > 47) && (nTecla < 58)); // nmeros de 0 a 9
	   } 
       else { // qualquer caracter...
         return true;
       } 
   }
   else {
       return true;
   }
}

/**
 *
 */
function loadError(titulo) {
  $('error').style.display = "none";
  win = new Window({className:"alphacube",maximizable:false,width:350,height:'auto',title:titulo}); 
  win.setConstraint(true,{left:10,right:10});
  win.getContent().innerHTML = $('error').innerHTML;
  win.showCenter();	
}

/**
 *
 */
function loadMessage(message) { 
 $('message').style.display = "none";
 Dialog.alert(message,{className:"alphacube",buttonClass:"btn",onOk:function(win){window.close();}});
}

/**
 * 
 */
function soNumero(event){
	var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode;
	var caract = new RegExp(/^[0-9]+$/i);
	var caract = caract.test(String.fromCharCode(keyCode));

    if (keyCode != 9 && keyCode != 8 && keyCode != 46) // backspace
	if(!caract){
		keyCode=0;
		return false;
	}
}

/**
 * 
 */
function mascaraMoeda(cur,len) {
	n='__0123456789';
	d=cur.value;
	l=d.length;
	r='';

	if (l > 0)
	{   z = d.substr(0,l-1);
		s = '';
		a = 2;

		for (i=0; i < l; i++)
		{
			c = d.charAt(i);
			if (n.indexOf(c) > a)
			{   a=1;
				s+=c;
			}
		}

		l = s.length;
		t = len-1;

		if (l > t)
		{   l = t;
			s = s.substr(0,t);
		}

		if (l > 2)
		{   r = s.substr(0,l-2)+','+s.substr(l-2,2);
		}
		else	
		{   if (l == 2)
			{	 r='0, '+s;
			}
			else
			{  if (l == 1)
				{   r = '0,0'+s;
				}
			}
		}

		if (r == '')
		{   r = '0,00';
		}
		else
		{   l = r.length;
			if (l > 6)
			{   j  = l%3;
				w  = r.substr(0,j);
				wa = r.substr(j,l-j-6);
				wb = r.substr(l-6,6);
				if (j > 0)
				{   w += '.';
				}
				k = (l-j)/3-2;

				for (i=0; i < k; i++)
				{	w += wa.substr(i*3,3)+'.';
				}

				r = w+wb;
			}
		}
	}

	if (r.length <= len)
	{   cur.value=r;
	}
	else
	{   cur.value=z;
	}

	return 'ok';
}

function popitup(url) {
                locationx=(screen.height - 300)/2
                locationy=(screen.width - 400)/2
	newwindow=window.open(url,'','height=400,width=620,top='+locationx+',left='+locationy);
	if (window.focus) {newwindow.focus()}
	return false;
}

/*	-------------------------------------------------
	VALIDACAO EMAIL
	-------------------------------------------------*/
	function isEmail(str)
	{
		var supported = 0;
		if (window.RegExp)
		{
			var tempStr = "a";
			var tempReg = new RegExp(tempStr);
			if (tempReg.test(tempStr)) supported = 1;
		}
		if (!supported) 
		return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);
		var r1 = new RegExp("(@.*@)|(\\.\\.)|(@\\.)|(^\\.)|( )|(\\.@)");
		var r2 = new RegExp("^.[a-zA-Z0-9\\-\\.\\_]+\\@(\\[?)[a-zA-Z0-9\\-\\.]+\\.([a-zA-Z]{2,3}|[0-9]{1,3})(\\]?)$");
		return (!r1.test(str) && r2.test(str));
	}




/*	-------------------------------------------------
	VALIDACAO DO CAMPOS DO FORMULARIO
	-------------------------------------------------*/
	function valida_campo(tipo, campo, event){
//		form = campo.form.name;
//		cp = campo.name;
//		alert(document.getElementById(campo.id));
//		alert(form);
		switch(tipo)
		{
			case 0: //RETIRA ASPAS SIMPLES E DUPLAS - EVENTO: onKeyPress
			{
				if(event.keyCode == 39 || event.keyCode == 34)
					event.returnValue = false;
				break;
			}
			case 1: //CAMPO ACEITA SOMENTE NUMERO - EVENTO: onKeyPress
			//alert(event.keyCode);
			{
				if(event.keyCode <= 44 || event.keyCode == 45|| event.keyCode > 57 || event.keyCode == 46 || event.keyCode == 47 || event.keyCode == 42 || event.keyCode == 39 || event.keyCode == 34 )
					event.returnValue = false;
				break;
			}
			case 2: //CAMPO ACEITA SOMENTE TEXTO - EVENTO: onKeyPress
			{
				if (event.keyCode > 47 && event.keyCode < 58 || event.keyCode == 39 || event.keyCode == 34)
					event.returnValue = false;
				break;
			}
			case 3: //CAMPO ACEITA SOMENTE EMAIL - EVENTO: onChange
			{
				if (campo.value!=''){
					if(!isEmail(campo.value)){
						//alert(campo);
						alert('Digite o seu E-MAIL corretamente');
						event.returnValue = false;
						document.getElementById(campo.id).focus();
					}
				}
				break;		
			}
			case 4: //CAMPO ACEITA SOMENTE DATA - EVENTO: onChange
			{
				if (campo.value!=''){
					if(!validaData(campo.value)){
						event.returnValue = false;
						campo.select();
					}
				}
				break;		
			}
			case 5: //CAMPO ACEITA SOMENTE CPF - EVENTO: onChange
			{
				if (campo.value!=''){
					if(!isCpf(campo.value)){
						alert('Digite o seu CPF corretamente');
						event.returnValue = false;
						campo.select();
					}
				}
				break;
			}
		}
	}
