/*------------------------------------------*/
/* Gestión del Medio Rural de Canarias 2007 */
/*------------------------------------------*/

(function($) {

	$.fn.extend({

		/**
		 * Rellena un combo HTML (<select>) con los datos indicados.
		 * 
		 * Ejemplo:
		 *
		 *		var datos = [{ID: "1", VALOR: "Tenerife"}, {ID: "2", VALOR: "La Gomera"}];
		 *
		 *		$("select.islas").addOpciones(datos, "ID", "VALOR", {valorPrimerElemento: "0", textoPrimerElemento: "---"});
		 *
		 * Resultado:
		 *		<select id="prueba" class="islas">
		 *			<option value="0">---</option>
		 *			<option value="1">Tenerifee</option>
		 *			<option value="2">La Gomera</option>
		 *		</select>
		 *
		 * @param	datos		Array de objetos javascript.
		 * @param	atrValor	Nombre de la clave para obtener el "value" del option.
		 * @param	atrNombre	Nombre de la clave para obtener el texto del option.
		 * @param	opciones	(Opcional) Permite indicar que option se queda seleccionada, 
		 *						el valor del primer elemento...
		 */
		addOpciones: function(datos, atrValor, atrNombre, opciones)
		{
			var defaults = $.extend({valorPrimerElemento: 0, textoPrimerElemento: null, valueSeleccionado: null, atrNombreGrupo: null}, opciones);

			var auxGroup = null;
			
			return this.each(function() 
			{
				$(this).empty();

				if (defaults.valorPrimerElemento != null && defaults.textoPrimerElemento != null && ! this.multiple)
				{
					$("<option value='" + defaults.valorPrimerElemento + "'>" + defaults.textoPrimerElemento + "</option>").appendTo(this);
				}
			
				if (! datos) return false;
				
				var padre = this;

				for (var i=0, j=datos.length; i<j; i++)
				{
					if (defaults.atrNombreGrupo)
					{
						if (datos[i][defaults.atrNombreGrupo] != auxGroup)
						{
							auxGroup = datos[i][defaults.atrNombreGrupo];
							
							padre = $("<optgroup label='" + auxGroup + "'></optgroup>").appendTo(this);
						}
					}
				
					$("<option value='" + datos[i][atrValor] + "'>" + datos[i][atrNombre] + "</option>").appendTo(padre);
				}

				try	{
					$(this).val(defaults.valueSeleccionado || defaults.valorPrimerElemento);
				}
				catch(e) {}

			});
		},


		/**
		 * Situa el foco en el primer campo visible.
		 */
		focoPrimerCampo: function()
		{
			if (this.size() <= 0) return this;

			$(":input:visible:enabled:first", this).focus();

  			return this;
		},


		/**
		 * Rellena un formulario a partir de los datos indicados.
		 *
		 * Ejemplo:
		 *
		 *		var datos = {id: '1', nombre: 'Prueba'};
		 *
		 * 		$("#frmPrueba").setValues(datos, {prefijo: "exp_"});
		 *
		 *		<form id="frmPrueba">
		 *			<input type="hidden" id="exp_id">
		 *			<input type="text" id="exp_nombre">
		 *		</form>
		 *
		 * @param	datos		Objeto javascript {CLAVE:VALOR} que contiene los datos.
		 * @param	opciones	(Opcional) Prefijo y/o sufijo que se a�ade a la clave para
		 *						identificar el campo en el que se va a colocar el valor.
		 */
		setValues: function(datos, opciones)
		{
			var opciones = $.extend({prefijo: '', sufijo: ''}, opciones);
			
			return this.each(function()
			{
				for (var clave in datos)
				{
					var elem = $("#" + opciones.prefijo + clave + opciones.sufijo, this);
									
					if (elem.length > 0)
					{					
						if (datos[clave] && datos[clave].asString && elem.hasClass("fecha"))
							elem.val(datos[clave].asString());
						else
							elem.val(datos[clave] || "");
					}
					else
					{
						elem = $(":input[name=" + opciones.prefijo + clave + opciones.sufijo + "]", this);

						if (datos[clave])
						{
							if (typeof datos[clave] == "string")
								elem.val([datos[clave]]);
							else
								elem.val(datos[clave]);
						}
						else
							elem.val("");
					}
				}
			});
		},
		
		
		/**
		 * Obtiene un objeto javascript con los valores del formulario,
		 * donde la CLAVE es el ID o el NAME del elemento y el VALOR es
		 * el VALUE del elemento.
		 *
		 * Ejemplo:
		 *
		 *		<form id="frmPrueba">
		 *			<input type="hidden" id="exp_id" value="100">
		 *			<input type="text" id="exp_nombre" value="Usuario">
		 * 			<input type="checkbox" name="exp_opciones" value="1">
		 * 			<input type="checkbox" name="exp_opciones" value="2">
		 *		</form>
		 *
		 *		var datos = $("#frmPrueba").getValues({prefijo: "exp_"});
		 *
		 * Resultado:
		 *
		 *		datos == {id: '100', nombre: 'Usuario', opciones: ["1","2"]}
		 *
		 * @param	opciones	(Opcional) Array de objetos con los IDs de los campos.
		 *						(Opcional) Prefijo y/o sufijo que tienen los campos del
		 *						formulario y que se elimina antes de generar el objeto.
		 */
		getValues: function(opciones)
		{
			var opciones = $.extend({campos: null, prefijo: '', sufijo: ''}, opciones);

			var valores = {};

			if (opciones.campos)
			{
				for (var clave in opciones.campos)
				{
					valores[clave] = $("#" + opciones.prefijo + clave + opciones.sufijo, this).val();
				}
			}
			else
			{
				if (opciones.prefijo || opciones.sufijo)
				{
					var regexp = new RegExp("^" + opciones.prefijo + "|" + opciones.sufijo + "$", "g");
				}

				this.each(function()
				{
					$(":radio:checked, :checkbox:checked, :text, :password, :input:hidden, select, textarea", this).each(function() {
	
						var clave = this.id || this.name;
	
						if (this.type == "radio" || this.type == "checkbox") { clave = this.name; }
	
						if (regexp) { clave = clave.replace(regexp, ""); }
	
						if (this.type == "checkbox")
						{
							valores[clave] = valores[clave] || [];
	
							valores[clave].push($(this).val());
						}
						else if (this.type != "file")
						{
							if ($(this).val())
							{
								if ($(this).hasClass("fecha") && Date.fromString)
									valores[clave] = Date.fromString($(this).val());
								else
									valores[clave] = $(this).val();
							}
						}
					});
				});
			}

			return valores;
		},

		limpiar: function()
		{
			this.each(function()
			{
				$(this).trigger("reset").find(":hidden").val("");
			});
		}	
		
	});

})(jQuery);

