/**
 * SimpleTabs - Unobtrusive Tabs with Ajax
 *
 * @example
 *
 *	var tabs = new SimpleTabs($('tab-element'), {
 * 		entrySelector: 'h2.tab-tab'
 *	});
 *
 * @version		1.0
 *
 * @license		MIT License
 * @author		Harald Kirschner <mail [at] digitarald.de>
 * @copyright	2007 Author
 */
var SimpleTabs = new Class({

	Implements: [Events, Options],

	/**
	 * Options
	 */
	options: {
		show: 0,
		delay:0,
		showMenuBelow:0,
		entrySelector: '.rgtabs-entry',
		classWrapper: 'rgtabs-wrapper',
		classMenu: 'rgtabs-menu',
		classContainer: 'rgtabs-container',
		onSelect: function(toggle, container, index) {
			toggle.addClass('rgtabs-selected');
			var list = $$('.rgtabs-selected a');
			list.each(function(element) {
				element.addClass('sel');
			});
			container.setStyle('display', '');
		},
		onDeselect: function(toggle, container, index) {
			var list = $$('.rgtabs-selected a');
			list.each(function(element) {
				element.removeClass('sel');
			});
			toggle.removeClass('rgtabs-selected');
			container.setStyle('display', 'none');
		},
		onRequest: function(toggle, container, index) {
			container.addClass('rgtabs-ajax-loading');
		},
		onComplete: function(toggle, container, index) {
			container.removeClass('rgtabs-ajax-loading');
		},
		onFailure: function(toggle, container, index) {
			container.removeClass('rgtabs-ajax-loading');
		},
		onAdded: Class.empty,
		getContent: null,
		ajaxOptions: {},
		cache: true
	},

	/**
	 * Constructor
	 *
	 * @param {Element} The parent Element that holds the tab elements
	 * @param {Object} Options
	 */
	initialize: function(element, options) {
		this.element = $(element);
		this.setOptions(options);
		this.current = 0;
		this.selected = null;
		this.build();
		this.loadActive();
		this.prepareTimer(this.options.show+1);
	},

	build: function() {
		this.tabs = [];
		var count =0;
		var count2 =0;
		this.menu = new Element('ul', {'class': this.options.classMenu});
		this.menucontainer = new Element('div', {class: 'rgtabs-menucontainer'});
		this.menucontainer.adopt(this.menu);
		this.wrapper = new Element('div', {'class': this.options.classWrapper});

		this.element.getElements(this.options.entrySelector).each(function(el) {
			count++
		}, this);
		
		this.count = count;		
		this.navPrev = new Element('a', {
  				'href': 'javascript:void(0)',
  				'class': 'rgtabs-nav prev',
  				'events': {
					'click': this.moveNav.bindWithEvent(this, 'prev')
  				}
  			}).set('html','&laquo; vorherige Seite');

		this.navNext = new Element('a', {
  				'href': 'javascript:void(0)',
  				'class': 'rgtabs-nav next',
  				'events': {
					'click': this.moveNav.bindWithEvent(this, 'next')
  				}
  			}).set('html','nächste Seite &raquo;');
		
		this.element.getElements(this.options.entrySelector).each(function(el) {
			if (count2==0) {
				classname="tabfirst";
			} else if (count2+1==count) {
				classname="tablast";
			} else {
				classname="tabmiddle";
			}
      		count2++;
			var content = el.get('href') || (this.options.getContent ? this.options.getContent.call(this, el) : el.getNext());
			this.addTab(el.innerHTML, el.title || el.innerHTML, content,classname);
		}, this);
		
		if (this.options.showMenuBelow==1) {
			this.menu2=  this.menu.clone();
			this.element.empty().adopt(this.wrapper).adopt(this.menucontainer);
		} else {
			this.element.empty().adopt(this.menucontainer).adopt(this.wrapper);
		}

		if (this.tabs.length) {
			this.select(this.options.show);
			this.current = this.options.show;
    	}		
		/* ORIGINAL
		this.element.empty().adopt(this.menu, this.wrapper);
		if (this.tabs.length) this.select(this.options.show);*/
	},

	/**
	 * Add a new tab at the end of the tab menu
	 *
	 * @param {String} inner Text
	 * @param {String} Title
	 * @param {Element|String} Content Element or URL for Ajax
	 */
	addTab: function(text, title, content,classname) {
		var grab = $(content);
		var container = (grab || new Element('div'))
			.setStyle('display', 'none')
			.addClass(this.options.classContainer)
			.inject(this.wrapper);
		var pos = this.tabs.length;
		var evt = (this.options.hover) ? 'mouseenter' : 'click';
		var linkElement = new Element('a', {
			href: 'javascript:void(0)',
			title: title,
			events: {
				click: this.onClick.bindWithEvent(this, [this.tabs.length])
			}
 		});
		
 		linkElement.set('html',text);
			
		var tab = {
			/* ORIGINAL
			container: container,
			toggle: new Element('li').grab(new Element('a', {
				href: '#',
				title: title
			}).grab(
				new Element('span', {html: text})
			)).addEvent(evt, this.onClick.bindWithEvent(this, [pos])).inject(this.menu)*/
			container: container.setStyle('display', 'none').addClass(this.options.classContainer).inject(this.wrapper),
 			toggle: new Element('li').addClass(classname).adopt(linkElement).inject(this.menu)
		};
		if (!grab && $type(content) == 'string') tab.url = content;
		this.tabs.push(tab);
		return this.fireEvent('onAdded', [tab.toggle, tab.container, pos]);
	},

	onClick: function(evt, index) {
		this.select(index);
		return false;
	},
	
	/**
	 * Needed by navigation prev/next functionality
	 * @author adrian@foeder.de
	 * @see declaration of "this.navPrev" and "this.navNext"
	 */
	moveNav: function(evt, dir) {
		evt.stop();
		var stepDir = ('prev'==dir ? -1 : 1);
		var newStep = 0;

		if (dir=='prev') {
			if (this.selected==0) newStep = this.count-1;
			else newStep= this.selected-1; 		
		} else {
			if (this.selected+1==this.count) newStep = 0;
			else newStep= this.selected+1; 		
		}
		
		this.select(newStep);
	},

	/**
	 * Select the tab via tab-index
	 *
	 * @param {Number} Tab-index
	 */
	select: function(index) {
		if (this.selected === index || !this.tabs[index]) return this;
		if (this.ajax) this.ajax.cancel().removeEvents();
		var tab = this.tabs[index];
		var params = [tab.toggle, tab.container, index];
		if (this.selected !== null) {
			var current = this.tabs[this.selected];
			if (this.ajax && this.ajax.running) this.ajax.cancel();
			params.extend([current.toggle, current.container, this.selected]);
			this.fireEvent('onDeselect', [current.toggle, current.container, this.selected]);
		}
		this.fireEvent('onSelect', params);
		if (tab.url && (!tab.loaded || !this.options.cache)) {
			this.ajax = this.ajax || new Request.HTML();
			this.ajax.setOptions({
				url: tab.url + '&type=543',
				method: 'get',
				/*evalScripts: true,*/
				update: tab.container.empty(),

				onComplete: function(resp) {
					tab.loaded = true;
					/*tab.container.empty().set('html', resp);*/
					this.fireEvent('onComplete', params);
				}.bind(this)
			}).setOptions(this.options.ajaxOptions);
			this.ajax.send();
			this.fireEvent('onRequest', params);
		}
		this.selected = index;
		return this;
	},	
	loadActive: function() {
		var show = -1;    
		this.element.getElements('.rgtabs-wrapper .rgtabs-container a[id^="c"]').each(function(anchorid, i) {
			if (window.location.hash.test(anchorid.id)) {
			  show = i;
			  //alert(i);
			}
		});    		
		if (show!=-1) {
			  this.select(show);
			  //alert('2222'+show);    
		}	
	},
	prepareTimer: function(index) {
	    if (this.options.delay>0) {
        if (index >=this.count) index = 0;
        this.select.delay(this.options.delay, this,index);
      	}
	} 

});