function onClickMostrarDivPlanos(div){
   if ($("#"+div).is(':visible')){
	  HideContent(div);
   }else{
	ShowContent(div,1);
   }
}

function showDivNovoUsuario(){

  $("#divNovoUsuarioContent").load("frmNovoUsuario.php");
  ShowContent('divNovoUsuario',1);
  
}

function showDivEsquecimentoSenha(){

  $("#divEsquecimentoSenhaContent").load("frmEsquecimentoSenha.php");
  ShowContent('divEsquecimentoSenha',1);
  
}

function showDivReenvioChaveAtivacao(){

  $("#divReenvioChaveAtivacaoContent").load("frmReenvioChaveAtivacao.php");
  ShowContent('divReenvioChaveAtivacao',1);
  
}

function showDivLogin(){

  $("#divLoginContent").load("frmLogin.php");
  ShowContent('divLogin',1);
  
}

function onClickVerTemosDeUso(){
    
  $("#divTermosDeUsoContent").load("termosDeUso.php");
  ShowContent('divTermosDeUso',1);
    
    
}

function onClickChkTermosDeUso(obj){
    
	if(obj.checked == true){
          obj.value = 1; 
	} else {
	   obj.value = 0;
	}
}

function onClickChkIsAvisarResumoAtivo(obj){
    
	if(obj.checked == true){
          obj.value = 1;
            $("#cbQuantDiasResumo").removeAttr('disabled');

	} else {
	   obj.value = 0;
          $("#cbQuantDiasResumo").attr({'disabled' : 'true'});
       
	}
}

function getValidarEmailNovoUsuario(e){

        //stop the form from being submitted  
        cancelarSubmit(e);
        $('#statusEmail').hide(); 
  
        /* declare the variables, var error is the variable that we use on the end 
        to determine if there was an error or not */  
        var txEmail        = $('#txEmailNovoUsuario').val();  
		var isEmailValido  = false;
        var error = false;
        
        errorMessage = "";
        if (txEmail.length <= 0){  
            error = true;  
            errorMessage = trataMensagemErro(errorMessage, "e-mail não informado" )
        }
		
        if (!validarEmail(txEmail) && txEmail.length > 0){  
            error = true;  
            errorMessage = trataMensagemErro(errorMessage, "e-mail inválido" )
        }
        
		//Valida se o email informado pode ser utilizado
        result = getResultadoSincrono("controle.php?module=usuario&acao=getVerificarEmailNovoUsuario", $('#frmNovoUsuario').serialize());

        if (result == 1)
			isEmailValido = true
		else
			isEmailValido =  false
		
        if (!isEmailValido){
            var error = true;
            errorMessage = trataMensagemErro(errorMessage, result);
		}			
		
       if (error)
			errorMessage = trataMensagemErro(errorMessage,"");
			
        //now when the validation is done we check if the error variable is false (no errors)  
        if(error == false){  
            $('#statusEmail').attr({'src' : 'images/check.png'}); 
            $('#statusEmail').show();
			return true;
        }else{
            $('#statusEmail').attr({'src' : 'images/l_alerta.gif'});
            $('#statusEmail').show();
			$.prompt(errorMessage,{timeout: 4000});
            return false;			
         }  
}

function onClickBtnEntrar(e){
    
        //stop the form from being submitted  
        cancelarSubmit(e);
  
        /* declare the variables, var error is the variable that we use on the end 
        to determine if there was an error or not */  
        var error = false;  
        var txEmail    = $('#txEmail').val();  
        var txSenha    = $('#txSenha').val();  
        
        errorMessage = "";
        if(txEmail.length == 0){  
            var error = true;
            errorMessage = trataMensagemErro(errorMessage,"e-mail não informado");
        }else       
            if (!validarEmail(txEmail)){  
                var error = true;  
                errorMessage = trataMensagemErro(errorMessage,"e-mail inválido" );
            }
        
        if(txSenha.length == 0){  
            var error = true; 
            $("#txSenha").focus(); 
             errorMessage = trataMensagemErro(errorMessage,"Senha não informada");
        }
       
        //now when the validation is done we check if the error variable is false (no errors)  
        if(error == false){  
            //disable the submit button to avoid spamming  
            //and change the button text to Sending...  
            $('#btnEntrar').attr({'disabled' : 'true', 'value' : 'Aguarde...' });  

            $.post("controle.php?module=usuario&acao=getRealizarLogin", $('#frmLogin').serialize(),function(result){  
                //and after the ajax request ends we check the text returned  
                if(result == 'OK'){
                     top.location.href = "desktop.php";
                }else{ 
                    //show the mail failed div
					//mostrarMensagemValidacao("Não foi Possível realizar o login.\nMotivo["+result+"]", 'divErrorMessage');
					$.prompt("Não foi Possível realizar o login.<br/>Motivo["+result+"]", {timeout: 8000});
                    $('#btnEntrar').removeAttr('disabled').attr('value', 'Entrar');  
                }  
            });  
        }else{
			//mostrarMensagemValidacao(errorMessage, 'divValidationMessage');
			$.prompt(errorMessage,{timeout: 4000});
         }      
    
}


function onClickBtnConfirmarNovoUsuario(e){
    
        //stop the form from being submitted  
        cancelarSubmit(e);
  
        /* declare the variables, var error is the variable that we use on the end 
        to determine if there was an error or not */  
        var error            = false;  
		var txNome           = $('#txNome').val();  
        var txEmail          = $('#txEmailNovoUsuario').val();  
		var txSenha          = $('#txSenhaNovoUsuario').val(); 
        var txSenhaConfirma  = $('#txSenhaConfirma').val();  
		var txDataNascimento = $('#txDataNascimento').val();
        var chkTermosDeUso   = $('#chkTermosDeUso').val();  
		var isCaptchaValido  = false;
        
        errorMessage = "";
		
        if (getValidarEmailNovoUsuario(e) == false){
		   return false;
		}		
		
        if(txNome.length <= 0){  
            var error = true;
            $("#txNome").focus();  
			errorMessage = trataMensagemErro(errorMessage, "Nome não informado");
        }		
		
        if(txSenha.length <= 0){  
            var error = true; 
            $("#txSenhaNovoUsuario").focus(); 
             errorMessage = trataMensagemErro(errorMessage, "Senha não informada");
        }
		
        if(txSenha != txSenhaConfirma){  
            var error = true; 
            $("#txSenhaConfirma").focus(); 
             errorMessage = trataMensagemErro(errorMessage, "A confirmação da senha não confere");
        }

        if(chkTermosDeUso == 0){  
            var error = true; 
            $("#chkTermosDeUso").focus(); 
             errorMessage = trataMensagemErro(errorMessage, "Você deve aceitar os termos de uso");
        }     
        
		
		//Valida se o captcha informado é valido
        result = getResultadoSincrono("controle.php?module=usuario&acao=getValidarCaptcha", $('#frmNovoUsuario').serialize());

        if (result == 1)
			isCaptchaValido = true
		else
			isCaptchaValido =  false
		
        if (!isCaptchaValido){
            var error = true;
            $("#txCaptcha").focus();  
            errorMessage = trataMensagemErro(errorMessage, "Código de confirmação inválido");
		}			
		
        //now when the validation is done we check if the error variable is false (no errors)  
        if(error == false){  
            //disable the submit button to avoid spamming  
            //and change the button text to Sending...  
		//	if (!confirm("Confirma solicitação de novo usuário?"))
		//		return false;	
                
		 $.prompt("Confirma solicitação de novo usuário?.",
			{buttons: {Sim: true, Não: false },
			  callback: function(resposta,m,f){
                //Se a resposta foi afirmativa, efetuar a inclusão do novo usuário.
				if (resposta){
                        $('#btnConfirmarNovoUsuario').attr({'disabled' : 'true', 'value' : 'Aguarde...' });  
            
                        $.post("controle.php?module=usuario&acao=setIncluirUsuario", $('#frmNovoUsuario').serialize(),function(result){  
                            //and after the ajax request ends we check the text returned  
                            if(result == 'OK'){
            					 $.prompt("Parabéns, seu cadastro foi efetuado.<br/>Você receberá um e-mail de confirmação.",
            						{   buttons: {Fechar: true },
            							callback: function(v,m,f){
            							
            							top.location.href = "index.php";
            						}
            					});
                            }else{ 
                                //show the mail failed div
            					getNewCaptcha('divCaptchaNovoUsuario');
            					$.prompt("Não foi Possível incluir o usuário.<br/>Motivo["+result+"]", {timeout: 8000});
                                $('#btnConfirmarNovoUsuario').removeAttr('disabled').attr('value', 'Confirmar');  
                            }  
                        });  				    
                    
				} //No caso da respota ser positiva
			  } //Fim callback function 
		}); 
        }else{
			errorMessage = trataMensagemErro(errorMessage,"");			
			$.prompt(errorMessage,{timeout: 8000});
			getNewCaptcha('divCaptchaNovoUsuario');			
         }      
    
}

function onClickSolicitarNovaSenha(e){

	//stop the form from being submitted  
	cancelarSubmit(e);

	/* declare the variables, var error is the variable that we use on the end 
	to determine if there was an error or not */  
	var error = false;  
	var txEmail    = $('#txEmailNovaSenha').val();  
	
	errorMessage = "";
	if(txEmail.length == 0){  
		var error = true;
		errorMessage = trataMensagemErro(errorMessage,"e-mail não informado");
	}else       
		if (!validarEmail(txEmail)){  
			var error = true;  
			errorMessage = trataMensagemErro(errorMessage,"e-mail inválido" );
		}
		
	//Valida se o captcha informado é valido
	result = getResultadoSincrono("controle.php?module=usuario&acao=getValidarCaptcha", $('#frmNovaSenha').serialize());

	if (result == 1)
		isCaptchaValido = true
	else
		isCaptchaValido =  false
	
	if (!isCaptchaValido){
		var error = true;
		$("#txCaptcha").focus();  
		errorMessage = trataMensagemErro(errorMessage, "Código de confirmação inválido");
	}			
		
	
	//now when the validation is done we check if the error variable is false (no errors)  
	if(error == false){  
		//disable the submit button to avoid spamming  
		//and change the button text to Sending...  
		$('#btnConfirmarNovaSenha').attr({'disabled' : 'true', 'value' : 'Aguarde...' });  
		$.post("controle.php?module=usuario&acao=setEnviarNovaSenha", $('#frmNovaSenha').serialize(),function(result){  
			//and after the ajax request ends we check the text returned  
			if(result == 1){
				 $.prompt("Sua solicitação de nova senha foi efetuada com sucesso !!<br/>Verifique seu e-mail dentro de alguns minutos.",
					{   buttons: {Fechar: true },
						callback: function(v,m,f){
						
						top.location.href = "index.php";
					}
				});
			}else{ 
				//show the mail failed div
				//mostrarMensagemValidacao("Não foi Possível realizar o login.\nMotivo["+result+"]", 'divErrorMessage');
				$.prompt("Não foi Possível enviar a solicitação.<br/>Motivo["+result+"]",{timeout: 4000});
				$('#btnConfirmarNovaSenha').removeAttr('disabled').attr('value', 'Confirmar');  
				getNewCaptcha('divCaptchaNovaSenha');
			}  
		});  
	}else{
		//mostrarMensagemValidacao(errorMessage, 'divValidationMessage');
		getNewCaptcha('divCaptchaNovaSenha');
		$.prompt(errorMessage,{timeout: 4000});
	 }  

}

function onClickReenviarChaveAtivacao(e){

	//stop the form from being submitted  
	cancelarSubmit(e);

	/* declare the variables, var error is the variable that we use on the end 
	to determine if there was an error or not */  
	var error = false;  
	var txEmail    = $('#txEmailReenvioChaveAtivacao').val();  
	
	errorMessage = "";
	if(txEmail.length == 0){  
		var error = true;
		errorMessage = trataMensagemErro(errorMessage,"e-mail não informado");
	}else       
		if (!validarEmail(txEmail)){  
			var error = true;  
			errorMessage = trataMensagemErro(errorMessage,"e-mail inválido" );
		}
		
	//Valida se o captcha informado é valido
	result = getResultadoSincrono("controle.php?module=usuario&acao=getValidarCaptcha", $('#frmReenvioChaveAtivacao').serialize());

	if (result == 1)
		isCaptchaValido = true
	else
		isCaptchaValido =  false
	
	if (!isCaptchaValido){
		var error = true;
		$("#txCaptcha").focus();  
		errorMessage = trataMensagemErro(errorMessage, "Código de confirmação inválido");
	}			
		
	
	//now when the validation is done we check if the error variable is false (no errors)  
	if(error == false){  
		//disable the submit button to avoid spamming  
		//and change the button text to Sending...  
		$('#btnConfirmarReenvioChaveAtivacao').attr({'disabled' : 'true', 'value' : 'Aguarde...' });  
		$.post("controle.php?module=usuario&acao=getReenviarChaveAtivacao", $('#frmReenvioChaveAtivacao').serialize(),function(result){  
			//and after the ajax request ends we check the text returned  
			if(result == 1){
				 $.prompt("A chave de ativação foi reenviada !!<br/>Verifique seu e-mail dentro de alguns minutos.",
					{   buttons: {Fechar: true },
						callback: function(v,m,f){
						
						top.location.href = "index.php";
					}
				});
			}else{ 
				//show the mail failed div
				//mostrarMensagemValidacao("Não foi Possível realizar o login.\nMotivo["+result+"]", 'divErrorMessage');
				$.prompt("Não foi possível atender à solicitação.<br/>Motivo["+result+"]", {timeout: 4000});
				$('#btnConfirmarReenvioChaveAtivacao').removeAttr('disabled').attr('value', 'Confirmar');  
				getNewCaptcha('divCaptchaReenvioChaveAtivacao');
			}  
		});  
	}else{
		//mostrarMensagemValidacao(errorMessage, 'divValidationMessage');
		getNewCaptcha('divCaptchaReenvioChaveAtivacao');
		$.prompt(errorMessage,{timeout: 4000});
	 }  

}

function onClickManterUsuario(){
   
    $("#divManterUsuario").load("controle.php?module=usuario&acao=getFrmManterUsuario");
    ShowContent('divManterUsuario',1); 
}


function onClickBtnCancelarManterUsuario(){
	 $.prompt("Os dados não gravados serão perdidos, deseja continuar ?",
		{buttons: {Sim: true, Não: false }, timeout: 8000,
		  callback: function(resposta,m,f){
            //Se a resposta foi afirmativa, efetuar a operação
			if (resposta){
                   	onClickManterUsuario();	    
			} //No caso da respota ser positiva
		  } //Fim callback function 
	}); //Fim prompt    
}

function onClickGravarManterUsuario(e){

        //stop the form from being submitted  
        cancelarSubmit(e);
  
        /* declare the variables, var error is the variable that we use on the end 
        to determine if there was an error or not */  
        var error            = false;  
		var txNome           = $('#txNome').val();  
		var txDiaNascimento  = $('#txDiaNascimento').val();  
		var cbMesNascimento  = $('#cbMesNascimento').val();  
		var txAnoNascimento  = $('#txAnoNascimento').val();  		
		var txNovaSenha          = $('#txNovaSenha').val();
		var dataNascimento   = '';
		
        errorMessage = "";
		
        if(txNome.length <= 0){  
            var error = true;
            $("#txNome").focus();  
			errorMessage = trataMensagemErro(errorMessage, "Nome não informado");
        }		
		
        if(txDiaNascimento.length > 0 && (txDiaNascimento > 31 || txDiaNascimento <= 0)){  
            var error = true;
            $("#txDiaNascimento").focus();  
			errorMessage = trataMensagemErro(errorMessage, "Dia de nascimento deve estar entre 1 e 31");
        }else{
		    if (txDiaNascimento <= 9 && txDiaNascimento.length == 1)
			   txDiaNascimento = '0'+txDiaNascimento;
			   
		    dataNascimento += txDiaNascimento + '/';
        }
		
        if(cbMesNascimento > 0){  
		    if (cbMesNascimento <= 9)
			   cbMesNascimento = '0'+cbMesNascimento;
		
            dataNascimento += cbMesNascimento + '/';
        }		    

        if(txAnoNascimento.length > 0 && txAnoNascimento <= 1900){  
            var error = true;
            $("#txAnoNascimento").focus();  
			errorMessage = trataMensagemErro(errorMessage, "Ano de nascimento deve ser maior que 1900");
        }else
		    dataNascimento += txAnoNascimento;

	     /*Valida se a data de nascimento composta é válida*/
		if (dataNascimento.length >= 8 && !validaData(dataNascimento)) {
            var error = true;
            $("#txDiaNascimento").focus();  
			errorMessage = trataMensagemErro(errorMessage, "Data de Nascimento inválida");			
		}
		
        if(txNovaSenha.length > 0 && txNovaSenha.length < 5){  
            var error = true; 
            $("#txNovaSenha").focus(); 
             errorMessage = trataMensagemErro(errorMessage,"A nova senha deve possuir no mínimo 5 caracteres");
        }		
		
        //now when the validation is done we check if the error variable is false (no errors)  
        if(error == false){  
                
			 $.prompt("Confirma alteração dos seus dados ?",
				{buttons: {Sim: true, Não: false },timeout: 8000,
				  callback: function(resposta,m,f){
					//Se a resposta foi afirmativa, efetuar a inclusão do novo usuário.
					if (resposta){
							$('#btnGravar').attr({'disabled' : 'true'});  
				
							$.post("controle.php?module=usuario&acao=setManterUsuario", $('#frmUsuario').serialize(),function(result){  
								//and after the ajax request ends we check the text returned  
								if(result){
									 $.prompt("Seus dados foram alterados com sucesso !!",
										{   buttons: {Fechar: true }, timeout: 4000,
											callback: function(v,m,f){
											HideContent('divManterUsuario');
										}
									});
								}else{ 
									//show the mail failed div
									$.prompt("Não foi Possível alterar os dados do usuário.<br/>Motivo["+result+"]", {timeout: 4000});
									$('#btnGravar').removeAttr('disabled');  
								}  
							});  				    
						
					} //No caso da respota ser positiva
				  } //Fim callback function 
			}); 
        }else{
			errorMessage = trataMensagemErro(errorMessage,"");
			$.prompt(errorMessage,{timeout: 8000});
         }  

}

function onClickBtnDegustacao(e){
    
        //stop the form from being submitted  
        cancelarSubmit(e);
		
		 $.prompt("Confirma cadastro no plano DEGUSTAÇÃO - COMPLETO por 30 dias ?",
			{buttons: {Sim: true, Não: false },
			  callback: function(resposta,m,f){
                //Se a resposta foi afirmativa, altera o plano
				if (resposta){
                        $('#btnDegustacao').attr({'onclick' : 'return true;'});  
            
                        $.post("controle.php?module=usuario&acao=setPlanoDegustacao",'',function(result){  
                            //and after the ajax request ends we check the text returned  
                            if(result == 'OK'){
            					 $.prompt("Parabéns, seu cadastro foi efetuado.<br/>à partir de agora você pode utilizar todas as funcionalidades por 30 dias.",
            						{   buttons: {Fechar: true },
            							callback: function(v,m,f){            							
            							top.location.href = "desktop.php";
            						}
            					});
                            }else{ 
                                //show the mail failed div
            					$.prompt("Não foi Possível cadastrar seu plano.<br/>Motivo["+result+"]", {timeout: 8000});
                                $('#btnDegustacao').attr({'onclick' : 'onClickBtnDegustacao();'}); 
                            }  
                        });  				    
                    
				} //No caso da respota ser positiva
			  } //Fim callback function 
		}); 
      
    
}


