/*
---
description: TinyTab - Tiny and simple tab handler for Mootools.

license: MIT-style

authors:
- Danillo César de O. Melo

requires:
- core/1.2.4: '*'

provides: TinyTab

...
*/
(function($) {
	this.TinyTab = new Class({
		Implements: Events,
		initialize: function(tabs, contents, opt) {
			this.tabs = tabs;
			this.contents = contents;
			if(!opt) opt = {};
			this.css = opt.selectedClass || 'selected'; 
			
			// cicla su tutti i tab e controlla se ci sono dei link ajax
			$each(tabs, function(tab, index){
				var a = tab.getElement('a');
				if(a){
					tab.store('urlJSON', a.get('href'));
					var html = a.get('html');
					tab.set('html', html);
				}
			}.bind(this));
			
			// cicla su tutti i tab e aggiunge l'evento click
			tabs.addEvent('click',function(e){
				var el = e.target;
				
				this.select(el);
				e.stop();
				
			}.bind(this));
			
			this.select(this.tabs[0]);
		},

		select: function(el) {
			this.tabs.removeClass(this.css);
			el.addClass(this.css);
			this.contents.setStyle('display','none');
			var content = this.contents[this.tabs.indexOf(el)];
			
			var urlJSON = el.retrieve('urlJSON');
			
			if(urlJSON && urlJSON!='' && content.get('html')==''){
				netedit.ajax.getData(
					urlJSON.replace(/\&amp;/g,'&'), 
					{
						method: 'get',
						onComplete: function(txt){
							var html = eval('(' + txt + ')');
							var content = this.contents[this.tabs.indexOf(el)];
							
							content.set('html', html);
							
							var scripts = content.getElements('script');
							$each(scripts, function(script, index){
						       eval(script.innerHTML);   // for each script tag, evaluate its contents
						    }.bind(this));
							content.tween('display', 'block');
							this.fireEvent('change',[content,el]);
						}.bind(this),
						onRequest : function() {
							var content = this.contents[this.tabs.indexOf(el)];
							content.tween('display', 'block');
							netedit.ajax.showLoading(content);
						}.bind(this)
					}
				);
			}else{
				var content = this.contents[this.tabs.indexOf(el)];
				content.tween('display', 'block');
				this.fireEvent('change',[content,el]);
			}
		}
	});
})(document.id);

/*
ESEMPIO

<ul class="tabs">
    <li>Easy</li>
    <li>Simple</li>
    <li>Tiny</li>
</ul>

<ul class="contents">
    <li>One line of code.</li>
    <li>No more than a simple tab system.</li>
    <li>Your source code have less than 1k uncompressed!</li>
</ul>

<script>
tb = new TinyTab($$('ul.tabs li'),$$('ul.contents li'));
</script>
*/
