/**
 * @author Stefan Manastirliu
 */

(function ($) {
  $.fn.htmlSelect= function (options) {
  	var open = false;
  	var defaults = {
  		"imagePosition": "left",
  		"imageWidth": "30",
  		"imageHeight": "30"
  	}
  	var options = $.extend(defaults, options);
  	 
    return this.each(function () {
		function optionsListener(){
			$("li", obj).live("mouseover",
				function(){
					$(this).addClass("hover");
			});
			
			$("li", obj).live("mouseout",
				function(){
					$(this).removeClass("hover");
				}
			);
			
			$("li", obj).live("click",function(e){
				if (!open){
					open = true;
					$("li", obj).css("display","block");
				}
				e.preventDefault();
				var li = $(this);
				li.removeClass("hover");
				
				if (!(li.hasClass("selected"))){	
					removeSelection($("li.selected"));
					doSelection(li);	
					$("li", obj).each(function(){
						if (!($(this).hasClass("selected"))){
							$(this).addClass("not-selected");
							$(this).removeClass("clicked");
						}
					});
				}
				else{
					removeSelection($("li.selected"));
					li.addClass("clicked");
					opts.each(function(){
						liParent = $(this).parent().parent("li");
						liParent.removeClass("not-selected");
					});
				}
				return false;
			});	
		}
		
    	function mouveUp(liElement){
    		liElement.remove().prependTo(obj);	
    	}
    	
    	function restorePosition(liElement){
    		oldPosition = parseInt(liElement.attr("rel"));
    		$(opts).each(function(index){
    			current = $(this);
    			if (parseInt(current.attr("rel")) > oldPosition ){
    				clone = liElement.clone()
    				$('li[rel="'+(index-1)+'"]').after(clone);
    				liElement.remove();
    			}
    		});
    	}
    	
    	function removeSelection(liElement){
    		restorePosition(liElement);
    		if(liElement.hasClass("selected")){
    			liElement.removeClass("selected");
    			liElement.removeClass("clicked");
    		}
    		liElement.addClass("not-selected");
    		$(".see-more", liElement).remove();
    		$('input[type="radio"]', liElement).attr("checked", false);
    		
    	}
    	function doSelection(liElement){
    		mouveUp(liElement);
    		if (open){
    			open = false;
    			$("li", obj).css("display","none");
    		}
    		if(liElement.hasClass("not-selected")){
    			liElement.removeClass("not-selected");
    		}
    		liElement.addClass("selected");
    		liElement.append('<span class="see-more"></span>');
    		$('input[type="radio"]', liElement).attr("checked", true);
    		
    		
    	}
    	
    	var obj = $(this);
    	optionsListener();
		opts = $(obj).find('input[type="radio"]');
		opts.each(function(position){
			if (! ($(this).is(":checked"))){
				removeSelection($(this).parents("li"));
			}
			else{
				doSelection($(this).parents("li"));
			}
			$(this).parents("li").attr("rel",position)
		});
		if ($("li.checked", obj).length == 0){
			doSelection($("li:first", obj));
		}
    })
  };
})(jQuery)

