(function( $ ){

  $.fn.twDropdown = function( options ) {  

    var settings = {
      'animationSpeed': 160,
      'animationEase': '',
      'delay': 250,// hover delay before acting
      'transition': 'slide'//slide or fade
    };
    
    return this.each(function() {
      // If options exist, overwrite
      
	  var afterTimer;
      var $rootUL = $(this);
      if( $rootUL.is('ul') ) {
        if ( options ) { 
          $.extend( settings, options );
        }
        // hide all children by default
        $rootUL.children('li').children('ul').hide();
        // show children on li mouseenter, hide on mouseleave
        $rootUL.children('li').each(function(){
		  var timer;
          var $hoverLI = $(this);
          $hoverLI.mouseenter(function(e){
			clearTimeout(timer);
            var $targetUL = $(this).children('ul');
		    if(settings.transition == 'fade'){
			  $targetUL.fadeIn(settings.animationSpeed,settings.animationEase);
		    }
		  else{
			$targetUL.slideDown(settings.animationSpeed,settings.animationEase);
		  }
            e.stopImmediatePropagation();
          });
          $hoverLI.mouseleave(function(e){
            var $targetUL = $(this).children('ul');
            timer = setTimeout(function(){
              if(settings.transition == 'fade'){
                $targetUL.fadeOut(settings.animationSpeed,settings.animationEase);
              }
              else{
                $targetUL.slideUp(settings.animationSpeed,settings.animationEase);
              }
            },settings.delay);
            e.stopImmediatePropagation();
          });
        });
      }
      else{
        alert('TWDropdown only works with ULs');
      }
      
    });

  };
})( jQuery );
