$(document).ready(function(){
    var enviar_login = function() {
        var form = $("#entrarForm");
        form.find(":submit").attr("disabled", true);        
        form.find(":submit").addClass('btn-striped');
        $('#entrarForm .resultado').children().remove();
        $.ajax({
            url: form.attr('action'),
            dataType: 'json',
            type: 'POST',
            data : form.serialize()+'&ajax=login-form',
            success: function(data, textStatus, XMLHttpRequest) {
                form.find(":submit").removeClass('btn-striped');
                form.find(":submit").attr("disabled", false);
                if (data.status == '200') {
                    window.location.href = data.redirect;
                }
                else {
                    if (data != null && typeof data == 'object') {
                        $.each(data, function(key, value){
                            jQuery('<label/>', {
                                text: value
                            }).addClass('error').appendTo('#entrarForm .resultado');
                        }); 
                    }
                }
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                form.find(":submit").removeClass('btn-striped');
                form.find(":submit").attr("disabled", false);
                jQuery('<label/>', {
                    text: 'Error de comunicación con el servidor'
                }).addClass('error').appendTo('#entrarForm .resultado');
            }
        });
        return false;							
    };
                
    $("#entrarForm").validate({
        onfocusout: false,
        onkeyup: false,
        onclick: false,
        rules:{
            FormularioLogin_email:{
                required:true,
                email: true
            },
            FormularioLogin_password:{
                required:true
            }
        },
        messages:{
            FormularioLogin_email:{
                required:"Introduzca su e-mail",
                email:"Indique un e-mail válido"
            },
            FormularioLogin_password:{
                required:"Indique su contraseña",
            }
        },
        errorClass: "error help-inline",
        errorElement: "span",
        highlight:function(element, errorClass, validClass) {
            $(element).parents('.control-group').addClass('error');
        },
        unhighlight: function(element, errorClass, validClass) {
            $(element).parents('.control-group').removeClass('error');
        },
        submitHandler: enviar_login
    });				

    var enviar_registro = function() {
        var form = $("#registroForm");
        form.find(":submit").attr("disabled", true);
        form.find(":submit").addClass('btn-striped');
        $('#registroForm .resultado').children().remove();
        $.ajax({
            url: form.attr('action'),
            dataType: 'json',
            type: 'POST',
            data : form.serialize()+'&ajax=registro-form',
            success: function(data, textStatus, XMLHttpRequest) {
                form.find(":submit").removeClass('btn-striped');
                form.find(":submit").attr("disabled", false);
                if (data.status == '200') {
                    form.clearForm();
                    $('.modal .modal-header h3').text(data.titulo);
                    $('.modal .modal-body p').text(data.texto);
                    $('.modal').modal('show');
                }
                else {
                    if (data != null && typeof data == 'object') {
                        $.each(data, function(key, value){
                            jQuery('<label/>', {
                                text: value
                            }).addClass('error').appendTo('#registroForm .resultado');
                        }); 
                    }
                }
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                form.find(":submit").removeClass('btn-striped');
                form.find(":submit").attr("disabled", false);
                jQuery('<label/>', {
                    text: 'Error de comunicación con el servidor'
                }).addClass('error').appendTo('#registroForm .resultado');
            }
        });
        return false;							
    };
                
    $("#registroForm").validate({
        onfocusout: false,
        onkeyup: false,
        onclick: false,
        rules:{
            FormularioRegistro_email:{
                required:true,
                email: true
            },
            FormularioRegistro_password:{
                required:true,
                minlength: 6
            },
            FormularioRegistro_password2:{
                required:true,
                minlength: 6,
                equalTo: "#FormularioRegistro_password"
            },
            FormularioRegistro_acepto:{
                required:true
            }
        },
        messages:{
            FormularioRegistro_email:{
                required:"Introduzca su e-mail",
                email:"Indique un e-mail válido"
            },
            FormularioRegistro_password:{
                required:"Indique una nueva contraseña",
                minlength:"La contraseña debe al menos 6 caracteres"
            },
            FormularioRegistro_password2:{
                required:"Introduzca otra vez la contraseña",
                minlength:"La contraseña debe al menos 6 caracteres",
                equalTo:"La confirmación de contraseña no coincide"
            },
            FormularioRegistro_acepto:""
        },
        errorClass: "error help-inline",
        errorElement: "span",
        highlight:function(element, errorClass, validClass) {
            $(element).parents('.control-group').addClass('error');
        },
        unhighlight: function(element, errorClass, validClass) {
            $(element).parents('.control-group').removeClass('error');
        },
        submitHandler: enviar_registro
    });
});

$.fn.clearForm = function() {
    return this.each(function() {
        var type = this.type, tag = this.tagName.toLowerCase();
        if (tag == 'form')
            return $(':input',this).clearForm();
        if (type == 'text' || type == 'password' || tag == 'textarea')
            this.value = '';
        else if (type == 'checkbox' || type == 'radio')
            this.checked = false;
        else if (tag == 'select')
            this.selectedIndex = -1;
    });
};

