evalAlias = function(id)
{
	this.addScript(id, 'blur');

	$("#"+id).bind("blur", function(e) {
		$(this).val(  $.trim(  $(this).val()  )  );

		var filtro =/^[a-zA-Z]+[_a-zA-Z0-9]+[a-zA-Z0-9]{1,18}$/;

		if (!filtro.test(  $(this).val()  ))
		{
			mensaje(this, 'Debe ingresar al menos 3 caracteres, no puede comenzar con un número y/o contener caracteres especiales.');
		}
		else
		{
			mensaje(this, '', false);
		}

	});
}

evalCorreo = function(id, obligatorio)
{
	this.addScript(id, 'blur');
	this.objetos[id] = new Array;
	this.objetos[id]['obligatorio'] = obligatorio;

	$("#"+id).bind("blur", function(e) {
		var obligatorio = forms[  $(this).parent().parent().attr('id')  ].objetos[$(this).attr('id')]['obligatorio'];
		
		$(this).val(  $.trim(  $(this).val()  )  );
		
		// si está vacío el campo y se permite campo vacío, salgo.
		if (obligatorio == false && $(this).val() == '')
		{
			mensaje(this, '', false);
			return;
		}
		
		//evalúo si corresponde con la expresión regular
		var filtro =/^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@+([_a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]{2,200}\.[a-zA-Z]{2,6}$/;
		if (!filtro.test(  $(this).val()  ))
		{
			mensaje(this, 'El correo no es válido.');
		}
		else
		{
			mensaje(this, '', false);
		}
	});
}

evalLen = function(id, min_len, max_len)
{
	this.addScript(id, 'blur');
	this.objetos[id] = new Array;
	this.objetos[id]['min_len'] = min_len;
	this.objetos[id]['max_len'] = max_len;

	$("#"+id).bind("blur", function(e) {
		var min_len = forms[  $(this).parent().parent().attr('id')  ].objetos[$(this).attr('id')]['min_len'];
		var max_len = forms[  $(this).parent().parent().attr('id')  ].objetos[$(this).attr('id')]['max_len'];

		var texto = $.trim(  $(this).val()  );
		texto.replace('  ', ' ');

		if( texto.length < min_len)
		{
			mensaje(this, 'Al menos tiene que escribir '+min_len+' caracteres.');
		}
		else if (max_len != null && texto.length > max_len)
		{
			mensaje(this, 'Sólo puede escribir '+max_len+' caracteres.');
		}
		else
		{
			mensaje(this, '', false);
		}
	});

	if (max_len != null)
	{
		$("#"+id).bind("keyup", function(e) {
			funcion_len(this);
		});
		$("#"+id).bind("focus", function(e) {
			funcion_len(this);
		});
		var funcion_len = function(objeto) {
			var min_len = forms[  $(objeto).parent().parent().attr('id')  ].objetos[$(objeto).attr('id')]['min_len'];
			var max_len = forms[  $(objeto).parent().parent().attr('id')  ].objetos[$(objeto).attr('id')]['max_len'];

			var texto = $.trim(  $(objeto).val()  );
			//texto.replace(/  /, ' ');	// esto por qué no funciona?

			var mens = '';
			mens = 'Ha escrito <strong>'+(texto.length)+'</strong> caracter(es). Mínimo: '+min_len+' - Máximo: '+max_len+'.';
			if (texto.length > max_len)
				mensaje(objeto, mens, true);
			else
				mensaje(objeto, mens, false);
		};
	}
}

evalContra = function(id, id_contra2)
{
	var contra = 0;
	this.addScript(id_contra2, 'blur');
	this.contra1 = id;
	this.contra2 = id_contra2;

	$("#"+id).bind("blur", function(e) {
		var contra2 = $(   '#' + forms[  $(this).parent().parent().attr('id')  ].contra2   );
		if ( $(contra2).val() != '' )
			$(contra2).blur();
	});

	$("#"+id_contra2).bind("blur", function(e) {

		var contra = $(   '#' + forms[  $(this).parent().parent().attr('id')  ].contra1   );

		if (  $(contra).val().length < 6 )
		{
			mensaje(contra, 'La contraseña debe tener al menos 6 caracteres.');
		}
		else if (  $(this).val() !=  $(contra).val()  )
		{
			mensaje(contra, 'Ambas contraseñas deben ser iguales, intente escribirlas nuevamente.');
		}
		else
		{
			mensaje(contra, '', false);
		}
	});

}

evalSelect = function(id, option_value_null)
{
	this.addScript(id, 'blur');
	this.objetos[id] = new Array;
	this.objetos[id]['option_value_null'] = option_value_null;

	$("#"+id).bind("blur", function(e) {
		var option_value_null = forms[  $(this).parent().parent().attr('id')  ].objetos[$(this).attr('id')]['option_value_null'];

		if ($(this).val() == option_value_null)
		{
			mensaje(this, 'Selecciona una opción por favor.');
		}
		else
		{
			mensaje(this, '', false);
		}

	});
}

evalEntero = function(id, minimo, maximo)
{
	this.addScript(id, 'blur');
	this.objetos[id] = new Array;
	this.objetos[id]['minimo'] = minimo;
	this.objetos[id]['maximo'] = maximo;

	$("#"+id).bind("blur", function(e) {
		var filtro =/^[-]?[0-9]+$/;

		if (!filtro.test(  $(this).val()  ))
		{
			mensaje(this, 'Escriba un número por favor.');
		}
		else
		{
			var minimo = forms[  $(this).parent().parent().attr('id')  ].objetos[$(this).attr('id')]['minimo'];
			var maximo = forms[  $(this).parent().parent().attr('id')  ].objetos[$(this).attr('id')]['maximo'];
			if ($(this).val() < minimo)
			{
				mensaje(this, 'El valor es demasiado pequeño.');
			}
			else if ($(this).val() > maximo)
			{
				mensaje(this, 'El valor es demasiado grande.');
			}
			else
			{
				mensaje(this, '', false);
			}
		}
	});
}

evalDecimal = function(id, decimales, minimo, maximo)
{
	this.addScript(id, 'blur');
	this.objetos[id] = new Array;
	this.objetos[id]['decimales'] = decimales;
	this.objetos[id]['minimo'] = minimo;
	this.objetos[id]['maximo'] = maximo;

	$("#"+id).bind("blur", function(e) {

		if (isNaN(  parseFloat($(this).val())  ))
		{
			mensaje(this, 'Escriba un número por favor.');
		}
		else
		{
			var minimo = forms[  $(this).parent().parent().attr('id')  ].objetos[$(this).attr('id')]['minimo'];
			var maximo = forms[  $(this).parent().parent().attr('id')  ].objetos[$(this).attr('id')]['maximo'];
			if ($(this).val() < minimo)
			{
				mensaje(this, 'El valor es demasiado pequeño.');
			}
			else if (maximo != null && $(this).val() > maximo)
			{
				mensaje(this, 'El valor es demasiado grande.');
			}
			else
			{
				var decimales = forms[  $(this).parent().parent().attr('id')  ].objetos[$(this).attr('id')]['decimales'];
				var numero = $(this).val();
				$(this).val(  Math.round(numero * Math.pow(10, decimales)) / Math.pow(10, decimales)  );

				mensaje(this, '', false);
			}
		}
	});
}

evalFecha = function(id, minimo, maximo)
{
	this.addScript(id, 'blur');
	this.objetos[id] = new Array;
	this.objetos[id]['minimo'] = minimo;
	this.objetos[id]['maximo'] = maximo;

	$("#"+id).bind("blur", function(e) {	
		
		var filtro = /^\d{1,2}\/\d{1,2}\/\d{2,4}$/;

		var texto = $.trim(  $(this).val()  );
		texto = texto.replace(/-/g, '/');
		
		if (!filtro.test(  texto  ))
		{
			mensaje(this, 'Escriba una fecha por favor.');
		}
		else
		{
			/*
			var minimo = forms[  $(this).parent().parent().attr('id')  ].objetos[$(this).attr('id')]['minimo'];
			var maximo = forms[  $(this).parent().parent().attr('id')  ].objetos[$(this).attr('id')]['maximo'];
			if ($(this).val() < minimo)
			{
				mensaje(this, 'El valor es demasiado pequeño.');
			}
			else if ($(this).val() > maximo)
			{
				mensaje(this, 'El valor es demasiado grande.');
			}
			else
			{
			*/
				mensaje(this, '', false);
			//}
		}
		$(this).val(texto);
	});
}

evalFile = function(id)
{
	this.addScript(id, 'blur');

	$("#"+id).bind("blur", function(e) {
		if ($(this).val() == '')
		{
			mensaje(this, 'Seleccione un archivo por favor.');
		}
		else
		{
			mensaje(this, '', false);
		}
	});
}

selectInclude = function(id, depende_de_id, depende_de_file)
{
	//this.addScript(id, 'blur');

	if (this.objetos[depende_de_id] == undefined)
		this.objetos[depende_de_id] = new Array;
	this.objetos[depende_de_id]['objetivo_id'] = id;
	this.objetos[depende_de_id]['objetivo_file'] = depende_de_file;

	//esto lo hago porque puede haber elegido valores predeterminados en el PHP
	this.objetos[depende_de_id]['value_antes'] = $('#'+depende_de_id).val();

	$("#"+depende_de_id).bind("focus", function(e) {
		/* guarda el valor antes de dar foco, para luego comparar con el nuevo
		   valor y saber si tiene que recargar */
		var frm = $(this).parent().parent().attr('id');
		var id = $(this).attr('id');
		forms[frm].objetos[id]['value_antes'] = $(this).val();
	});
	$("#"+depende_de_id).bind("blur", function(e) {
		var frm = $(this).parent().parent().attr('id');
		var id = $(this).attr('id');

		//si no cambió nada, salgo
		if (forms[frm].objetos[id]['value_antes'] == $(this).val()) return;
		forms[frm].objetos[id]['value_antes'] = $(this).val();

		var depende_value = $(this).val();
		var objetivo_id = forms[frm].objetos[id]['objetivo_id'];
		var objetivo_file = forms[frm].objetos[id]['objetivo_file'];

		//mensaje("#"+objetivo_id, 'Cargando datos...', false);
		$("#"+objetivo_id).text('');
		$("#"+objetivo_id).append('<option>Cargando...</option>');
		$("#"+objetivo_id).attr('disabled', 'disabled');

		var retorna = $.ajax({
			type: "GET",
			url: objetivo_file+"?id="+objetivo_id+"&depende="+depende_value,
			async: false
		}).responseText;

		$("#"+objetivo_id).text('');
		if (retorna != '')
		{
			$("#"+objetivo_id).attr('disabled', '');
			$("#"+objetivo_id).append(retorna);
			document.getElementById(objetivo_id).selectedIndex=0;
		}
		else
		{
			$("#"+objetivo_id).append('<option value="-1">No hay opciones...</option>');
		}
		mensaje("#"+objetivo_id, '', false);
		$("#"+objetivo_id).blur();
	});
}

Form = function(id_form)	// class
{
	this.id = id_form;
	this.error = false;
	this.script = '';	//hace eval de este script al enviar formulario para ver errores
	this.objetos = new Array();

	//this.contra = 0; //la usa contra y contra2

	this.addScript = addScript;
	this.evalAlias = evalAlias;
	this.evalCorreo = evalCorreo;
	this.evalLen = evalLen;
	this.evalContra = evalContra;
	this.evalSelect = evalSelect;
	this.evalEntero = evalEntero;
	this.evalDecimal = evalDecimal;
	this.evalFecha = evalFecha;
	this.evalFile = evalFile;
	this.selectInclude = selectInclude;

	$('#'+this.id).submit( function() {
		var thiis = forms[  $(this).attr('id')  ];
		thiis.error = '';
		
		eval(  thiis.script  );
		
		// ¿está visible el div? Si no está, fue un js externo que evita la evaluación de ese campo
		if (thiis.error != ''&& $('#'+thiis.error).parent().is(':visible'))
		{
			$('#'+thiis.error).focus();
			$('#'+thiis.error).prev().fadeTo(10, 0.1);
			$('#'+thiis.error).prev().fadeTo('slow', 1);
			return false;
		}
		$('.submit').attr('disabled', 'disabled');
	});
}

/**
* Escribe el mensaje en el <span> luego del objeto pasado como parámetro
* object objeto
* string mensaje
* bool error
*/
mensaje = function (objeto, mensaje, error)
{
	if (error === undefined) error = true;

	if (error === true)
		clas = 'error';
	else
		clas = '';

	span = $(objeto).next();
	label = $(objeto).prev();

	$(label).attr('class', clas);

	$(span).html(mensaje);
	$(span).attr('class', clas);

	if (error === true)
	{
		thiis = forms[  $(objeto).parent().parent().attr('id')  ];
		thiis.error = $(objeto).attr('id');
	}
}
/*
hayError = function (objeto)
{
	thiis = forms[  $(objeto).parent().attr('id')  ];
	if (  thiis.error  != ''  )
		thiis.error = $(objeto).attr('id');
}
*/
addScript = function (id, evento)
{
	this.script = '$("#'+id+'").'+evento+'(); ' + this.script;
}
