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&uacute;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&aacute;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). Minimo: '+min_len+' - Maximo: '+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.    ');		//no sacar espacios al final, da error IE cuando se le hace eval
			}
			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
		{
			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)
{
	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)
{
	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.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).bind('submit', function(event)
	{
		// permite cancelar submit con
		// event.stopPropagation();
		if (event.isPropagationStopped())
			return false;
		
		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()
				.prev()
					.fadeTo(10, 0.1)
					.fadeTo('slow', 1);
			return false;
		}
		//alert('form2');
		$('.submit').attr('disabled', 'disabled');
	});
	
	//$('form span').hide();
}

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

	var claseadd = '';
	var claserem = '';
	if (error)
	{
		claseadd='error';
		claserem='info';
	} else {
		claseadd='info';
		claserem='error';
	}
	
	// busco los objetos que voy a utilizar y, si no existen, los creo
	label = $(objeto).prev();
	if ( $(objeto).next('div').length == 0)
		$(objeto).after('<div></div>');
	destino = $(objeto).next('');

	$(label)
			.addClass(claseadd)
			.removeClass(claserem);
	
	if (mensaje == '')
	{
		$(destino).slideUp("slow", function (){
				$(this)
					.removeClass('error')
					.html('');
			});
	} else {
		$(destino)
			.addClass(claseadd)
			.removeClass(claserem);
		
		//sino pega el golpe, la 1? vez cuando est? vac?o
		if ($(destino).html() == '') 
		{
			$(destino).hide();
			$(destino).html(mensaje);
			$(destino).slideDown("slow");
		}

		// No hacemos else por IE, da error de sintaxis cuando se le hace eval()
		if ($(destino).html() != '')
		{
			$(destino).html(mensaje);
		}
		
		thiis = forms[  $(objeto).parent().parent().attr('id')  ];
		thiis.error = $(objeto).attr('id');
	}
}

addScript = function (id, evento)
{
	this.script = '$("#'+id+'").'+evento+'(); ' + this.script;
}
