$(function (){
	$("#mensagem").Mensagem();
	//$("*").disableSelection();
    $('*').ajaxComplete(function (){     
        $("a[name='voltar']").click(function (){//refresca sempre o botão voltar sempre que houver ajax
            $("#resultadoAjax").fadeOut(500,function (){
                $(this).html('');
                $("#icon").fadeIn(500);
            })
        });
    });
	
	$("input").focusin(function (){
		if(!$(this).data('v')){
			$(this).data('v',$(this).val()).val('');
			$(this).data('entrou',true);
			if($(this).attr('name')=='password' || $(this).attr('name')=='pw'){
				this.type = 'password';
			}
		}
		$(this).css('border','');
	}).focusout(function (){
		if($(this).val()==""){
			if($(this).attr('name')=='password' || $(this).attr('name')=='pw'){
				this.type = 'text';
				
			}
			$(this).data('entrou',false);
			$(this).val($(this).data('v'));
			$(this).data('v','');	
		}
	});
  

    $("input , select").focus(function (){
        if($(this).css('border')=='1px solid red'){
            $(this).css('border','none')
        }
        var name='campo'+$(this).attr('name');
        $("div[name='"+name+"']").hide();
    });    

    //Página de login
    function send_login (){
	   var email_e=$("input[name='email']").val(),password_e=$("input[name='password']").val(),
        reme_e = $("input[name='reme']:checked").val() ? '1' : '0';
        
        $.ajax({
            url: 'include/login.php',
            type: 'POST',
            dataType: 'json',
            contentType: "application/x-www-form-urlencoded; charset=utf-8",
            data: {
                email:email_e,
                password: password_e,
                reme: reme_e
            },
            success: function (res){
            	window.clickFlag = 0;
            	$("div[name='login']").html($("div[name='login']").data('v'));
                if(res[0]=='NOK'){
                	$("#mensagem").Mensagem('showText',{
                		'text': 'O seu login e/ou palavra-passe estão incorrectos! Por favor tente de novo...',
                		'classe':'erro'
                	});
                	$("input[name='email']").css('border','1px solid red');
	         		$("input[name='password']").css('border','1px solid red');
               	}else if(res[0]=='OK'){
                   window.location =  window.location;
                }else if(res[0]=='NOVA'){
                    window.location='novapasse.php';
                }else if(res[0]=='CONFIRMADO'){
                   $("#mensagem").Mensagem('showText',{
                		'text': 'Deve confirmar o seu e-mail primeiro',
                		'classe': 'erro'
                	});
                }else{
                	
                }
                
            },
            complete: function (){
                //$("#res").html('');
            },
            beforeSend: function (){
                var text = $("#res").html(),
                textB = $("div[name='login']").html();
                $("div[name='login']").data('v',textB).html(text);
            }
        });
    }
    
    if($("form[name='login']") && $("#tool_pad")){
    	$(window).keypress(function (e){
    		if(e.keyCode==13 && $("div.button[name='login']").size()>0){
    			if(window.clickFlag == 1){
    				return true;
    			}
    			window.clickFlag = 1;
    			send_login();
    		}
    	});
    }
    
    $("form[name='login']").submit(function (){
	    send_login();
	    return false;	
    });
    $("div[name='login']").click(function (){
        send_login();
        return false;
    });
    
    $("div[name='recuperarpasse']").click(function (){//recuperacao.php
    	 
        $.ajax({
            url: 'recuperacaoemail.php',
            type: 'post',
            contentType: "application/x-www-form-urlencoded; charset=utf-8",
            data: {
                email: $("input[name='email']").val()
            },
            success: function (res){
                var sms = $("#mensagem");
                switch (res) {
                    case '0'://não tem email - post
                    	sms.Mensagem('showText',{
                			'text': 'Por favor preencha o campo e-mail correctamente...',
                			'classe': 'erro'
                		});
						$("input[name='email']").css('border','1px solid red');
                        break;
                        
                    case '1'://email não valido
                    	sms.Mensagem('showText',{
                			'text': 'O seu e-mail n&atilde;o &eacute; valido',
                			'classe': 'erro'
                		});
						$("input[name='email']").css('border','1px solid red');
                        break;
                    case '2'://não consta nas nosas bases de dados
                    	sms.Mensagem('showText',{
                			'text': 'O seu e-mail n&atilde;o se encontra nas nossas bases de dados',
                			'classe': 'erro'
                		});
                        break;
                    case '3'://encontra-se repetidos - grave! !importante rever!
                    	sms.Mensagem('showText',{
                			'text': 'O seu e-mail encontra-se repetido nas nossas bases de dados',
                			'classe': 'erro'
                		});
						$("input[name='email']").css('border','1px solid red');
                        break;
                    case 'OK'://passa para ok.
                        window.location='sucesso.php';
                        break;
                    default:
                    	sms.Mensagem('showText',{
                			'text': 'Ocorreu um erro inesperado, volte a tentar',
                			'classe': 'erro'
                		});
                        break;
                }//fim de switch

            },//fim de sucesso de ajax - recuperar
            complete: function (){
                $("#res").html('');
            },
            beforeSend: function (){
                $("#res").html('<p>aguarde...</p>');
            }
        });//fim de ajax
        return false;//para não submeter o formulario html;
    });//fim de submeter o form recuperar

    $("div[name='sememail']").click(function (){
        var sms = $("#mensagem"),
        nif_e=$("input[name='nif']").val(),contacto_e=$("input[name='contacto']").val(),
        dia_e=$("select[name='dia']").val(),mes_e=$("select[name='mes']").val(),
        ano_e=$("select[name='ano']").val();
        sms.clearQueue().slideUp(200);
        $.ajax({
            url: 'verificarsememail.php',
            type:'post',
            contentType: "application/x-www-form-urlencoded; charset=utf-8",
            dataType: 'json',
            data: {
                nif: nif_e,
                dia: dia_e,
                mes: mes_e,
                ano: ano_e,
                contacto: contacto_e
            },
            success: function (resposta){
                var string;
                for(var item in resposta){
                    if(resposta[0]!='OK'){

                        if(resposta[item].indexOf('|')>0 && resposta[item].split('|')[0]=='sms'){
                            sms.css('opacity','1').
                            html('<p>'+resposta[item].split('|')[1]+'</p>')
                            .slideDown(800).delay(8000).slideUp(200);
                        }else{//se o resultado[item] for diferente de sms
                            if(resposta[item].indexOf('|')>1){//se no resultado res[item] tiver '|' fazer split
                                string = resposta[item].split('|');
                            }else{
                                string=new Array (resposta[item]);
                            }
                            $("input[name='"+string[0]+"']").css('border','1px solid red');
                            $("select[name='"+string[0]+"']").css('border','1px solid red');
                            if(string[1]!=""){
                                $("div[name^='campo"+string[0]+"']").show().html(string[1]);
                            }
                        }
                    }else{//se o resposta[0] for igual a ok
                        window.location='novoemail.php';
                    }
                }//fim de loop
            },//fim de sucesso
           complete: function (){
                $("#res").html('');
            },
            beforeSend: function (){
                $("#res").html('<p>aguarde...</p>');
            }
        });
        return false;
    });//fim de click semmail

    $("input[name='novoemail']").click(function (){
        var email_e=$("input[name='email']").val(),reemail_e=$("input[name='reemail']").val(),
        passe_e=$("input[name='passw']").val(),repasse_e=$("input[name='repassw']").val(),
        sms=$("#mensagem");
        
        $.ajax({
            url: 'updatenovoemail.php',
            dataType: 'json',
            type: 'post',
            data: {
                'email': email_e,
                'reemail': reemail_e,
                'passw': passe_e,
                'repassw': repasse_e
            },
            success: function (res){
                if(res[0]=='OK'){
                    window.location='sucesso.php';
                }
                for(var item in res){
                    if(res[item].indexOf('|')>0){
                        var string = res[item].split('|');
                        $("input[name='"+string[0]+"']").css('border','1px solid red');
                        $("div[name='campo"+string[0]+"']").html('').show().html(string[1]);
                    }else{//senão tiver '|'
                        $("input[name='"+res[item]+"']").css('border','1px solid red');
                    }//fim de find '|';
                    if(res[item].split('|')[0]=='sms'){
                        sms.css('opacity','1')
                        .html('<p>'+res[item].split('|')[1]+'</p>')
                        .slideDown(800)
                        .delay(8000)
                        .slideUp(1000);
                    }
                }
            },
            error: function (){

            },
			complete: function (){
                $("#res").html('');
            },
            beforeSend: function (){
                $("#res").html('<p>aguarde...</p>');
            }
        });
        return false;
    });//fim do novoemail

    $("div[name='novapasse']").click(function (e){
        var sms=$("#mensagem"),passe_e=$("input[name='novapassword']").val(),
        repasse_e=$("input[name='repassword']").val();
        
        $.ajax({
            url: 'novapasseemail.php',
            dataType:'json',
            type:'post',
            data:{
                novapassword: passe_e,
                repassword: repasse_e
            },
            success: function (res){
                for(var item in res){
                    if(res[item]=='OK'){
                        window.location='sucesso.php';
                    }else{
                        if(res[item].indexOf('|')>0){
                            if(res[item].split('|')[0]=='sms'){
                            	sms.Mensagem('showText',{
                					'text': res[item].split('|')[1],
                					'classe': 'erro'
                				});
                            }
                        }else{
                            $("input[name='"+res[item]+"']").css('border','1px solid red');
                        }
                    }
                }//fim do for
            },
            error: function (){
               
            },
			complete: function (){
                $("#res").html('');
            },
            beforeSend: function (){
                $("#res").html('<p>aguarde...</p>');
            }
        });
        e.preventDefault();
    });

    
   
});//jquery
