var Multitab = new Class({
	Implements: Options,
	options: {
        id: 'tabulae'
    },		

	initialize: function(options){	
		this.setOptions(options);
		
		var chunk = 6;
				
		// estrae tutte le tab
		var tabs = [];
		$(this.options.id).getChildren().each(function(item){
			tmptab = new Hash({						
						'content' : item.getElement('ul').innerHTML
					});
			tabs.include(tmptab);
		});				
			
		// crea il box per le sottovoci
		var panelContainer  = new Element('div', {
			'id': 'panelContainer'
			});	
			
		var panelWindow  = new Element('div', {
			'id': 'panelWindow'
			});
		
		var panelSlider  = new Element('div', {
			'id': 'panelSlider'
			});
		
		panelSlider.inject(panelWindow);
		
		var goLeft  = new Element('span', {
			'id': 'goLeft',
			'styles' : {
				'opacity' : 0.2
			},
			'events' : {
				'click' : function() {
					if (this.getStyle('opacity')==1) {
						chunk--;
						if(chunk >= 6) {
							chunkWidth = $$('ul.panel li')[0].getComputedSize({
									'styles' : ['padding','border','margin']
								})['totalWidth']
							goRight.fade('in');
							$('opened').set('tween', {duration: 750, transition: 'sine:out'});
							$('opened').tween('margin-left', -chunkWidth * (chunk % 6));
							}				
						if(chunk==6) { 					
							this.fade('0.2');
							}											
						}
					}
				}	
			});

		
		var goRight  = new Element('span', {
			'id': 'goRight',
			'styles' : {
				'opacity' : 0.2
			},
			'events' : {
				'click' : function() {
					if (this.getStyle('opacity')==1) {
						if($('opened').getChildren().length - 1 >= chunk ) {
							chunkWidth = $$('ul.panel li')[0].getComputedSize({
									'styles' : ['padding','border','margin']
								})['totalWidth']
							goLeft.fade('in');
							$('opened').set('tween', {duration: 750, transition: 'sine:out'});							
							$('opened').tween('margin-left', -chunkWidth * (chunk % 6 + 1));
							}				
						if($('opened').getChildren().length - 1 == chunk ) { 
							this.fade('0.2');
							}
						chunk++;
						}
					}
				}
			});
				
		goLeft.inject(panelContainer);
		panelWindow.inject(panelContainer);
		goRight.inject(panelContainer);
		
		// popola i contenitori
		tabs.each(function(item, num) {
								
			var panel = new Element('ul', {
				'class' : 'panel',
				'html' : item.get('content')
			});
			
						
			if (num > 0 ) panel.fade('hide'); // nascondi tutte le tab successive alla prima
			else {
				panel.set('id', 'opened');				
				if (panel.getChildren('li').length <= 1) {
					goRight.fade('0.2');
				}
				if (panel.getChildren('li').length > chunk) {
					goRight.fade('in');
				}
			}
						
			panel.inject(panelSlider);
			
		});
		
		panelContainer.replaces($(this.options.id))	
	}	
		
});
