$(document).ready( function() {
	$("#lnkayudacontraportadaaltares").click( function(e) {
		var h = $("#ayudacontraportadaaltares");
		h.css("top", e.pageY + "px");
		h.css("left", (e.pageX+30) + "px");
		h.fadeIn();
		return false;
	});
	
	$("#ayudacontraportadaaltares").click( function() {
		$(this).fadeOut();
	});

	$("#mensaje").click( function() {
		$(this).fadeOut();
	});
	
	$("#btnEnviar").click( function(e) {
		if (!controldatos(e)) {
			return false;
		} else {
			var h = $("#mensajeautocierre");
			h.centerInClient(); 
			h.html("<p>Por favor, espere.<br />Registrando los datos...</p>");
			h.fadeIn();
		}
	});
});

function controldatos(e) {
	// cc_edad --> ^(?:\+|-)?\d+$
	// cc_email --> EsMailValido
	// cc_nif --> EsNIFValido
	// cc_argumentacion --> máx 100 palabras
	// cc_puntuacion --> ^(?:\+|-)?\d+$
	var msg = "";
	
	msg += controlcampo($("#cc_nombre"), "Nombre", true, "");
	msg += controlcampo($("#cc_apellidos"), "Apellidos", true, "");
	msg += controlcampo($("#cc_edad"), "Edad", true, "numero");
	msg += controlcampo($("#cc_email"), "Correo electrónico", true, "email");
	msg += controlcampo($("#cc_nif"), "NIF/DNI", true, "");
	msg += controlcampo($("#cc_perfil"), "Perfil", false, "");
	msg += controlcampo($("#cc_miembrosequipo"), "Miembros del equipo", ($("#cc_participacion")[0].selectedIndex==1)?true:false, "");
	msg += controlcampo($("#cc_direccion"), "Dirección", true, "");
	msg += controlcampo($("#cc_cp"), "Código postal", true, "");
	msg += controlcampo($("#cc_poblacion"), "Ciudad/Poblacion", true, "");
	msg += controlcampo($("#cc_region"), "Provincia/Estado", true, "");
	if($("#cc_idpais")[0].selectedIndex <= 0) msg += "\n-Debe seleccionar un país";
	msg += controlcampo($("#cc_contraportadabajares"), "Contraportada en baja resolución", true, "");
	if ($("#cc_contraportadaaltares").val().length < 10) {
		msg += "\n-El campo 'Contraportada en alta resolución' es obligatorio";
	}
	
	if ($("#cc_argumentacion").val().length > 0) {
		//alert(wordCount($("#cc_argumentacion").val()));
		if (wordCount($("#cc_argumentacion").val())>100) msg += "\n-El argumento ocupa más de 100 palabras. Por favor, modifícalo y cópialo de nuevo.";
	} else {
		msg += "\n-El campo 'Argumentación' es obligatorio";
	}

	//msg += controlcampo($("#cc_argumentacion"), "Argumentación", true, "");
	
	//
	
	if (msg.length>0) {
		var h = $("#mensaje");
		h.centerInClient(); 
		h.html("Errores encontrados:<br />" + replace(msg, "\n", "<br />"));
		h.fadeIn();
		
		return false;
	} else {
		return true;
	}
}

function controlcampo(c, n, obl, tipo) {
	if (c.val().length==0 && obl) {
		return "\n-El campo '" + n + "' es obligatorio";
	} else {
		switch(tipo) {
			case "fecha": ok = fechaValida(c.val()); break;
			case "email": ok = mailValido(c.val()); break;
			case "numero": 
				var objRegExp  = /^[0-9]{1,}$/;
				ok = objRegExp.test(c.val());
				break;				
			default: ok = true;
		}
		
		if (!ok)
			return "\n-El campo '" + n + "' es incorrecto";
		else 
			return "";
	}
}

$.fn.centerInClient = function(options) {
    /// <summary>Centers the selected items in the browser window. Takes into account scroll position.
    /// Ideally the selected set should only match a single element.
    /// </summary>    
    /// <param name="fn" type="Function">Optional function called when centering is complete. Passed DOM element as parameter</param>    
    /// <param name="forceAbsolute" type="Boolean">if true forces the element to be removed from the document flow 
    ///  and attached to the body element to ensure proper absolute positioning. 
    /// Be aware that this may cause ID hierachy for CSS styles to be affected.
    /// </param>
    /// <returns type="jQuery" />
    var opt = { forceAbsolute: false,
                container: window,    // selector of element to center in
                completeHandler: null
              };
    $.extend(opt, options);
   
    return this.each(function(i) {
        var el = $(this);
        var jWin = $(opt.container);
        var isWin = opt.container == window;

        // force to the top of document to ENSURE that 
        // document absolute positioning is available
        if (opt.forceAbsolute) {
            if (isWin)
                el.remove().appendTo("body");
            else
                el.remove().appendTo(jWin.get(0));
        }

        // have to make absolute
        el.css("position", "absolute");

        // height is off a bit so fudge it
        var heightFudge = isWin ? 2.0 : 1.8;

        var x = (isWin ? jWin.width() : jWin.outerWidth()) / 2 - el.outerWidth() / 2;
        var y = (isWin ? jWin.height() : jWin.outerHeight()) / heightFudge - el.outerHeight() / 2;

        el.css("left", x + jWin.scrollLeft());
        el.css("top", y + jWin.scrollTop());

        // if specified make callback and pass element
        if (opt.completeHandler)
            opt.completeHandler(this);
    });
}
