/**
 * @author Carlos
 */
$(document).ready(function(){

	$('form').each(inicializarFormulario);

});


function inicializarFormulario(i)
{
	$(this).submit(validarFormulario);
	
	$('select', this).each(inicializarSelectList);
	
	$(':radio', this).each(inicializarRadioButtons);
}

function inicializarSelectList(i)
{
	if ($(this).attr('valor'))
		$(this).val($(this).attr('valor'));
}

function inicializarRadioButtons(i)
{
	if ($(this).attr('valor'))
		this.checked = ($(this).val() == $(this).attr('valor'));
}

function validarFormulario()
{
	this.errores = [];
	
	$('.avis',this).hide();
	
	$(this).find('.esObligatori').each(validarObligatorio);
	$(this).find('.esEmail').each(validarEmail);

	if (this.errores.length > 0)
		$.each(this.errores, mostrarError);
	
	return this.errores.length == 0;
}

function mostrarError(i)
{
	$('#'+this).show('fast');
}

function mostrarAlertaErrores(errores, idDialog)
{
	var d = $('#'+idDialog);
	
}



function validarObligatorio()
{	
	if ($(this).val()=='') {
		this.form.errores.push(this.id + '_obligatori');
		//return false; //paramos en el primer error
	}	
}


function validarEmail()
{
	var reEmail = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
		
	if (!reEmail.test(this.value)) {
		this.form.errores.push(this.id + '_format');
		//return false;
	}
}

function validarConfirmacion()
{
	var idCampo = this.id.split('_')[1];
	
	if ($(this).val() != $('#' + idCampo, this.form).val()) {
		this.form.errores.push('confirmacio');
		//return false;
	}		
}

