$.fn.drilldown = function(options){

	var level=0;
	var is_animated=false;
	
	var defaults = {
		'width':'250px',
		'height':'300px',	
		'back':'Indietro',
		'easing':'swing',
		'onSelect':function(selected){alert('hai selezionato: '+selected)}	
		
	};
	  
	// estendiamo le opzioni di default con quelle passate dall'utente'
	var opts = $.extend(defaults, options);

	var root_id = $(this).attr('id');
	var $root = $(this);
	
	$(this).wrap('<div class="drilldown_container"></div>');
	var root = $(this).attr('id','drillmenu_root').parent().append('<a href="#" id="'+root_id+'drilldown_menu_back" class="back">'+opts.back+'</a>');
	
	$('.drilldown_container')
	.css('width',parseInt(opts.width)+'px')
	.css('height',parseInt(opts.height)+'px');

	$('li',root).wrapInner('<a href="#"></a>');			
	$('ul',root).each(function(i){
		$(this).css('width',parseInt(opts.width)+'px');
		if(i>0) {			
			$(this).parent().addClass('has_child');
			$(this).hide();
		}
	})
	
	$('ul ul').css('width',parseInt(opts.width)+'px').css('margin-left',parseInt(opts.width)+'px');
	
	$('a',root).click(function(event){
		
		event.preventDefault();event.stopPropagation();
		
		if(is_animated)return false;
				
		if($(this).attr('id')== root_id+'drilldown_menu_back'){
			is_animated=true;
			var $to_hide = $('ul.step_'+level);
			$to_hide.removeClass('visited').removeClass('step_'+level);
			$('ul#drillmenu_root',root).animate({'left': -1*(--level)*parseInt(opts.width)+'px'},300,opts.easing,function(){is_animated=false;$to_hide.hide()});
			if(level==0){
				$("#"+root_id+"drilldown_menu_back",root).hide();
			}
						
		}else{		
			if($('ul:first',this).length) {	
				if($('ul:first',this).hasClass('visited')) return false;
				
				is_animated=true;
				
				$('ul:first',this).show().addClass('visited step_'+(++level));			
				$('ul#drillmenu_root',root).animate({'left':-1*(level)*parseInt(opts.width)+'px'},300,opts.easing,function(){is_animated=false;});							
				$(root).css('height',parseInt(opts.height)+parseInt($("#"+root_id+"drilldown_menu_back",root).height())+'px');
				$("#"+root_id+"drilldown_menu_back").show();				
			}else{
				//sono arrivato alla foglia, callback sul valore selezionato
				$('li.selected',root).removeClass('selected');
				
				$(this).parent().addClass('selected');
				opts.onSelect($(this).parent().attr('id'));
		     	var title =  $(this).parent().attr("title");
				 
			}
		}
		
		//return false;
	})	
}
