$().ready(function() {
    var errorWrapperHtml = '<fieldset class="marginframe marginstandard back05">' +
    '<legend>' + aMensajes['MSG0001'] + '</legend>' +
    '<ol class="list styleoutside color08 fontmedium"><span id="errorForm"></span></ol>' +
    '</fieldset>';
    $("#errorWrapper").html(errorWrapperHtml);
    $("#errorWrapper").hide();
    $("#frmSolicitud").validate({
    onkeyup: false,
    onfocusout: false,
    rules: {
    	email: {
    		required: true,
    		email: true,
    		maxlength: 255
    	},
    	pass: {
    		required: true,
    		maxlength: 255
    	},
        comentarios: {
            required: false,
            maxlength: 4000
        }
    },
    messages: {
    	email: {
    	    required: aErrores['ERR0001'],
    	    email: aErrores['ERR0001'],
    	    maxlength: jQuery.format(aErrores['ERR0003'], $("label[for='email']").attr("title"))
    	},
    	pass: {
    	    required: aErrores['ERR0002'],
    	    maxlength: jQuery.format(aErrores['ERR0003'], $("label[for='pass']").attr("title"))
    	},
    	comentarios: {
    	    maxlength: aErrores['ERR0104']
    	}
    },
    errorLabelContainer: "#errorForm",
    errorElement: "li",
    submitHandler: function(inscripcion) {
        var sEmail = $("#email").attr("value");
        var sPass = $("#pass").attr("value");
        var iIdOferta = $("#id_oferta").attr("value");
        var sComentarios = $("#comentarios").attr("value");
        var iNumPreguntas = $("#num_preguntas").attr("value");


        // Construimos 2 arrays con las killer radio y text, para validarlas y enviar la informacion via ajax

        var error = false;
        var txt_error = "";
        var KRadio = new Array();
        var KText = new Array();
        var dataKQ = '';

        for(i=0; i<document.getElementById('frmSolicitud').elements.length; i++)
        {
            nombre = document.getElementById('frmSolicitud').elements[i].name;

            //guardamos las killer radio en un array
            if(nombre && nombre.substring(0,4) == "KQ_R")
            {
                if(!in_array(KRadio, nombre))
                {
                    KRadio.push(nombre);
                }
            }

            //guardamos las killer text en otro
            if(nombre && nombre.substring(0,4) == "KQ_T")
            {
                if(!in_array(KText, nombre))
                {
                    KText.push(nombre);
                }
            }
        }

        for(i=0; i<KRadio.length && !error; i++)
        {
            //miramos los radios a ver si estan chequeados
            if(!$("input[name="+KRadio[i]+"]:checked").val())
            {
                error = true;
                txt_error = aErrores["ERR0105"];
            }
            else {
                // Para enviar la peticion Ajax
                dataKQ = dataKQ + "& "+ KRadio[i] + "=" + $("input[name="+KRadio[i]+"]:checked").val();
            }
        }

        for(i=0; i<KText.length && !error; i++)
        {
            txtTrim = trim(document.getElementById(KText[i]).value);

            //miramos los textos a ver cumplen al longitud máxima
            if(txtTrim.length > 255)
            {
                error = true;
                txt_error = aErrores["ERR0103"];
            }

            // y la mínima
            if(txtTrim.length < 15)
            {
                error = true;
                txt_error = aErrores["ERR0103"];
            }
            if(! error){
                // Para enviar la peticion Ajax
                dataKQ = dataKQ + "& "+ KText[i] + "=" + txtTrim ;
            }
        }

        if(error) {  // si hubo error mostramos un mensaje
            $("#errorWrapper").show();
            var errores = '';
            if( $("#errorFormWrapper") ){
                $("#errorFormWrapper").hide();
            }
            errores += "<li>" + txt_error + "</li>";
            $("#errorForm").html(errores);
        }
        else {
            inscripcion.submit();
            return false;
        }
        return false;
    },
    showErrors: function(errorMap, errorList) {
        $("#errorForm").html("");
        if( $("#errorFormWrapper") ){
            $("#errorFormWrapper").hide();
        }
        if (this.numberOfInvalids() > 0) {
            $("#errorWrapper").show();
            this.defaultShowErrors();
            window.location.hash="form";
        }
    }
    });

    //Se encarga del login, de pintar la oferta anterior y siguiente si las hubiera y de comprobar si el usuario esta inscrito en la oferta
    $.ajax({  url: "/usuarios/ajaxoferta/id/"+$("#id_oferta").val(),
        dataType: "json",
        success: function(htmlresponse){
        if ( htmlresponse ) {
            pintaLogin(htmlresponse);
            checkOfertaYaInscrito(htmlresponse);
            // Ocultamos el fomulario de login
            if(htmlresponse.tipo == 'C'){
                var formLogin = $("#form_oferta_login")
                                 .html("<p class=\"fontmedium color06\">"+aVarios['VAR0101']+" <a rel=\"me\" class=\"deconone\" href=\""+htmlresponse.urls.candidatos_acceso+"\">"+htmlresponse.data.usuario.EMAIL+"</a> "+
                                       "<em class=\"color08\">(<a class=\"nowrap fontnormal deconone color08\" href=\""+htmlresponse.urls.candidatos_logout+"\">"+aVarios['VAR0103']+"</a>)</em></p>");
            }
            // Oferta anterio y siguiente si las hubiera
            if(htmlresponse.html_antsig){
                $("#antsig").html(htmlresponse.html_antsig);
            }

            pintaOfertasInscritas(htmlresponse);
        }
    }
    });
});