


(function($){
 $.fn.dropdown = function(options) {

  var defaults = {
   showSpeed: 200,
   hideSpeed: 100,
   callBackFn: null
  };
  var options = $.extend(defaults, options);

  this.each(function() { 
    var top= $(this);
   
    var dropDownMain = top.children(".jsdropdown_main");
    var dropDownText = dropDownMain.children(".dropdown_inner");
    var dropDownList = top.children(".jsdropdown_list");
    var dropDownElems = dropDownList.children(".elem");
    var dropDownAll = top.find(".jsdropdown_main, .jsdropdown_list .elem");
    var dropDownVal = top.children("input.jsdropdown_value");
    
    /* Open the dropdown */
    dropDownMain.mousedown(function(event) {
      
      
      //dropDownList.slideToggle(options.showSpeed);

      if (dropDownList.is(":visible")) {
        //        alert('hey');
        dropDownList.slideUp(options.hideSpeed);
      } else {
        dropDownElems.removeClass("highlighted");
        dropDownList.children(".selected").addClass("highlighted");
        dropDownList.slideDown(options.showSpeed);
        
        // Set click outside event
        $("body").bind('mousedown', function(event) {
         
          dropDownList.slideUp(options.hideSpeed);
          $(this).unbind(event);
        });
      }

      event.stopPropagation();     // make sure click here doesn't trigger body event
     
    });


  
    // Hover over elements (highlight)
    dropDownElems.mouseover(
      function(event) {
        dropDownElems.removeClass("highlighted");
        $(this).addClass("highlighted");
      
      });

    // Finally choose an option (click, or finish dragging)
    dropDownElems.mouseup(chooseOption);
    dropDownElems.mousedown(chooseOption);
    
    // Helper to choose an option
    function chooseOption(event) {
      var $this = $(this);
      var myText = $this.text();
      var myVal = $this.attr('title');

      // Set selected class
      dropDownElems.removeClass("selected");
      $this.addClass("selected");
    
      // Update state
      dropDownText.text(myText);
      dropDownVal.val(myVal);

      event.stopPropagation();
      $("body").unbind("mousedown");

      dropDownList.slideUp(options.hideSpeed);

      // Callback
      if (options.callBackFn) {
        options.callBackFn(myVal);
      }

    }
   

    // Disable text selection
    dropDownAll.each(function() {
      this.onselectstart = function() {return false;} // ie
      this.onmousedown = function() {return false;} // mozilla
    
      //alert($(this).html());
                   
    });


  });
 };
})(jQuery);

