

/**
 * jQuery interface plugin
 *
 * Comportamientos de la interfaz del admin
 * @author Víctor Estévez Gómez <elia.gregorio@bittia.com>
 * @category javascript
 * @copyright Copyright © 2010, BITTIA - Grupo BITTIA
 * @filesource
 * @package javascript
 * @version 0.1
 */



(function($)

{

	$.fn.interFace = function(options)

	{
		options = options || {};
		//Enlaza interfaz con elementos relacionados

		return this.each(function()
		{      
			var node = this.nodeName.toLowerCase();

			if(node == 'a')
			{
				jQuery(this).unbind('click').bind('click', function(event)
				{
					event.preventDefault();
					//Distintos tipos de enlaces
					switch($(this).attr('class'))
					{
						//Borrar elemento con id igual a rev
						case 'delete':
							var el = $(this).attr('rev');

							//Elementos Borrar (class='delete')

							//Boxy.confirm($(this).attr('title'), function()
							//{
								$(el).slideUp('normal', function(){ $(el).remove(); });
							//});
							break;

							

						//Clonar elemento con id igual a rev, e incrementar +1 el id
						case 'clone':

							//Copiar el anterior o un id específico

							var clon;

							if($(this).attr('rev') == 'before')
							{
								clon = $($(this).prev()).clone(true);
							}
							else
							{
								clon = $('#'+$(this).attr('rev')).clone(true);
							}
							clon = $(clon);

							//Incrementa el id en 1 de los elementos necesarios
							var id = clon.attr('id').substring(0, clon.attr('id').lastIndexOf('_')+1);

							//
							var num = $($($(this).parent()).children('[id]:visible:last')).attr('id');//Número de elementos
							num = parseInt(num.substr(num.lastIndexOf('_')+1, num.length), 10) + 1;							



							if(id && num)
							{
								$(clon).attr('id', id+num);
								$(clon).css({'display': 'block'});

								//Deselecciona si tiene select

								if($('select', clon).length >= 1)
								{
									var selec = $($('select', clon)).attr('options')[$($('select', clon)).attr('selectedIndex')];
									$(selec).attr('selected', false);
									$('select', clon).attr('id', id+num);
								}												

								//Inputs text y Files
								if($(':file, :text', clon).length >= 1)
								{
									$(':file, :text', clon).each(function(it, el)
									{
										$(el).val('');
										$(el).attr('id', $(el).attr('id')+'_'+num);
										$(el).attr('disabled', '');
									});
								}

								//Labels con id nuevo si los hay
								if($('label', clon).length >= 1)
								{
									$('label', clon).each(function(it, el)
									{
										$(el).attr('for', $(el).attr('for')+'_'+num);
									});
								}



								//Quitar botón borrar si lo hay ya
								if($('a.delete', clon).length >= 1)
								{
									$('a.delete', clon).remove();
								}



								//Botón de borrar
								clon.append('<a rel="interface" rev="#'+id+num+'" class="delete" title="'+lng.del_quest_field+'">'+lng.del+'</a>');



								//Insertar
								if($($(this).prev()).css('display') == 'none')
								{
									clon.insertBefore($(this).prev());
								}
								else
								{
									clon.insertBefore(this);
								}

								//Comportamiento al enlace de borrar
								$('a[rev="#'+id+num+'"]').interFace();
							}
							break;

						

						default:
							//console.log('otro');
							break;

					}

					return false;

				});

			}

			else if(node == 'div')			

			{

				//Comparar con expresión regular

				if($(this).hasClass('image_n') || $(this).hasClass('multimedia_n'))

				{

					//Ordenar

					$('ul', this).sortable(

					{

						cursor: 'move',

						items: 'li',

						appendTo: 'body',

						opacity: 0.6,

						tolerance: 'pointer',

						placeholder: 'ui-state-highlight',

						stop: function(event, ui)

						{

							$(ui.item).css({'opacity': 1});

						}

					});

				}

			}

		});

		

	};

})(jQuery);//Call and execute the function immediately passing the jQuery object









/** 

 * Relation_list comportamiento

 */

(function($)

{

	$.fn.relationList = function(opt)

	{

		//Opciones

		opt = $.extend({},

		{

			path: INSTALATION_DIR+'/admin/ajax/relation_list.php',

			template: function(id, str)//applied to each item in datasource 

			{

				return "<option value='" + id + "'>" + str + "</option>";

			}

		}, opt);

	

		//Comportamiento

		return this.each(function()

		{

			//Contenedor general

			var source = $(this);



			//Lista elementos ordenable

			var list_items = $(this).find('.asmList');

			list_items.sortable(

			{

   				stop: function(event, ui) 

				{

					list_items.trigger('updateValues');

				}

			});

			

			//Actualizar el input con los valores

			list_items.bind('updateValues', function(event)

			{

				//Obtener valores para convertir a json

				var values = new Array();

				$.each($('li[rel]', list_items), function(num, value)

				{

					values[values.length] = $(value).attr('rel').split('-*-');

				});

				

				//Opciones seleccionadas como valor en el input

				$(list_items.next()).val(JSON.stringify(values));

			});

			

			//Editar elemento al doble click

			list_items.bind('dblclick', function(event)

			{

				var rel = (event.target.nodeName == 'LI')? $(event.target).attr('rel') : $(event.target).parents('li').attr('rel');//Obtener valores del select

				var vals = rel.split('-*-');//Separar valores

				//Rellenar campos

				$.each($(':input[type!="file"][name!="MAX_FILE_SIZE"]', $('.items', source)), function(num, el)

				{

					$(this).val(vals[num]);

				});

			});

			

			//Botón añadir elemento. Todos los valores de formularios los añade en nuevo item de lista

			$('a.new', source).live('click', function(event)

			{

				event.preventDefault();

				

				var $itemLabel = '';

				var sep = '';

				var ids = '';

				//Recorrer elementos para obtener ids y texto a mostrar

				$.each($(':input[type!="file"][type!="radio"][name!="MAX_FILE_SIZE"], :radio[checked]', $(this).parent()), function(num, el)

				{

					//Quitar [] en el nombre del campo

					var name = $(el).attr('name');

					if($(el).attr('name').substring($(el).attr('name').length-2, $(el).attr('name').length) == '[]')

					{

						name = $(el).attr('name').substring(0, $(el).attr('name').length-2);

					}

					

					//Texto e ids del elemento

					$itemLabel += "<span class='asmListItemLabel "+name+"'>"+(($(':selected', el).text())? $(':selected', el).text() : $(el).val())+"</span>";

					ids += sep+$(el).val();

					sep = '-*-';

				});



				//No existe elemento igual, añadir

				if($('[rel="'+ids+'"]', list_items).length < 1 && ids && ids != '0-*-0' && ids != '-*-' && ids != '00:00-*-')

				{

					//Enlace de borrar

					var $removeLink = $("<a href='#' class='asmListItemRemove'>"+lng.del+"</a>");

					//li para la lista con los textos y enlace

					var $item = $("<li rel='"+ids+"' class='asmListItem'></li>").append($itemLabel).append($removeLink);

					//Añadir elemento a la lista

					list_items.append($item);

					//Actualizar datos del input con valores

					list_items.trigger('updateValues');

				}

			});

			

			

			//Tipo archivo, subir por ajax

			//Selects relacionados

			var $selfuploads = $(':file', this);

			if($selfuploads.length > 0)

			{

				//Campos select asociados a otro

				new AjaxUpload('#'+$selfuploads.attr('id'),

				{

					action: INSTALATION_DIR+'/admin/ajax/upload_file.php',

					responseType: 'json',

					autoSubmit: true,

					onSubmit: function(file, ext)

					{

						loading(source);//Cargando

					},

					onComplete: function(file, response)		

					{

						loadingEnd();

						//Respuesta subida archivo

						if(response && response != 'error')

						{

							//Campo oculto para obtener valor

							$(this._button).before('<input id="aux_rl_upload" type="hidden" name="'+$(this._button).attr('name')+'" value="'+response.file_abs+'" />');

							//Añadir elemento

							$('a.new', source).trigger('click');

							//Borrar campo auxiliar

							$('#aux_rl_upload').remove();

						}

						else

						{

							//Reactivar campo

							Boxy.alert(lng.err_file_upload+' '+file, null, {title: 'Error'});

						}

					}

				});

			}

		

			//Selects relacionados

			var self = $(this).find('[rel] select');			

			//Campos select asociados a otro

			self.bind("change.relation_twice", function(event)

			{

				//Buscar en que posición está el elemento

				for(var i=0; i < self.length; i++)

				{

					if(self[i] == this)

						break;

				}

				

				loading(source);

				

				//Es el último, obtiene del anterior. Si no el siguiente

				var el = (i+1 == self.length)? i-1 : i+1;



				//Table, el class del select. Si hay varios class, el primero

				var table_source = $(self[i]).parents('div[rel][rev]').attr('rel');

				//Tabla relación, invertir si es último select

				var table_relation = $(self[i]).parents('div[rel][rev]').attr('rev');

				

				//Obtener elementos

				$.get(opt.path, {'relation': table_relation, 'source': table_source, 'id': $(self[i]).val()}, function(data, textStatus)

				{

					if(textStatus == 'success')

					{

						//Valor antiguo del select a actualizar

						var old_value = $(self[el]).val();

						//Vaciar opciones

						$(self[el]).empty();

						//Insertar nuevos elementos

						$.each(data, function(num, value)

						{

							//Añadir nuevas

							$(self[el]).append(opt.template(value[0], value[1]));//Añadir

						});

						//Selecciona el antiguo elemento seleccionado

						$("[value='"+old_value+"']", self[el]).attr("selected", true);

					}

					loadingEnd();

				}, 'json');

			});

			

			//Botones de borrar de la lista al editar

			$('.asmListItemRemove', source).live('click', function(event)

			{

				event.preventDefault();

				$(this).parent().slideUp('normal', function()

				{

					$(this).remove();

					list_items.trigger('updateValues');

				});

				

				return false;

			});

			

			source.css({'display': 'block'});

		});

	};

})(jQuery);//Call and execute the function immediately passing the jQuery object




