jQuery.fn.extend({ 
	desplegable : function(options) {
		var defaults = {
				padding : 10,
				width : 155,
				texto : "Seleccione opción...",
				fondo1: "/imagenes/select.gif",
				fondo2: "/imagenes/select2.gif",
				flecha1: "/imagenes/select_flecha.gif",
				flecha2: "/imagenes/select_flecha2.gif"
		};  
		var options = $.extend(defaults,options); 
		this.each(function(){	
			
			var $this = jQuery(this);
			
			//$this.css({'z-index':'9'});
			$thisId = $(this) .attr("id");
			var desplegado = false;
			var seleccionado = "";
			
			if ($('.selected',$this).html()!=null){
				options.texto = $('.selected .value',$this).html();
				$('input[type=hidden]',$this).val($('.selected .id',$this).html());
			}
			
			$.contenido = $this.html();
			/*Vaciamos el contenido del select */
			$this.empty();
			/*Ponemos el texto por def ecto*/
			$this.prepend('<p>'+options.texto+'</p>');
			/*Ponemos la flecha del desplegable*/
			$this.prepend('<a href="#" id="flecha" ></a>');
			$('#flecha',$this).css({'background' : 'url("'+options.flecha1+'") no-repeat'});
			$this.append('<div id="desplegadoBlanco"><div id="desplegado">'+$.contenido+'</div></div>');
			$this.css({"width":options.width+"px"});
			$('#desplegado',$this).css({"width":options.width-options.padding+"px"});
			/*Accio que amaga el desplegable*/
			function _amagarDesplegable(objecte){
					$('#desplegado',objecte).slideUp(function(){
						desplegado = false;
						$('#flecha',objecte).css({'background' : 'url("'+options.flecha1+'") no-repeat'});
						$this.css({'background' : 'url("'+options.fondo1+'") no-repeat'});	 											  
					}); 

			};		
			
			
			$this.click(function(){		
				if (!this.desplegado){ 
					$('#desplegado',$this).slideDown(function(){
						$(document).one('click', function (){
							_amagarDesplegable($this);
							desplegado = false; 
						});
					})
					desplegado = true; 
					$('#flecha',$this).css({'background' : 'url("'+options.flecha2+'") no-repeat'});
					$($this).css({'background' : 'url("'+options.fondo2+'") no-repeat'});								 
				}
				else { 
					desplegado = false; 
					_amagarDesplegable($this);
				}
			});
			
			$('#desplegado ul li',$this).click(function(){
			
				this.seleccionado = $('a.id',$(this)).html();
				$('p',$this).html($('a.value',$(this)).html());
				$('#desplegado ul li',$this).removeClass("selected");
				$(this).addClass("selected");
				$('input[type=hidden]',$this).val($('.id',$(this)).html());
				$this.trigger("cambiado");			
			});
			
			$('#desplegado ul li',$this).hover(function(){
				$('a',$(this)).css({'font-weight':'bold'});
			},function(){
				$('a',$(this)).css({'font-weight':'normal'});
			});		
		});
	}
});
