/*--------------------------------------------------------------------
  TabKit.js
                                                          1 Sep 2010
                                                       Kazuhisa Togo
----------------------------------------------------------------------
  <!> Requirements
    + Prototype.js 1.6
    + Script.aculo.us
----------------------------------------------------------------------
  Copyright (c) 2010 Kazuhisa Togo

  Permission is hereby granted, free of charge, to any person
  obtaining a copy of this software and associated documentation
  files (the "Software"), to deal in the Software without
  restriction, including without limitation the rights to use, copy,
  modify, merge, publish, distribute, sublicense, and/or sell copies
  of the Software, and to permit persons to whom the Software is
  furnished to do so, subject to the following conditions:

  The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
  HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  DEALINGS IN THE SOFTWARE.
--------------------------------------------------------------------*/



var TabKit = Class.create({
	// Set default values
	defaults: {
		delay: 5,
		duration: 0.5,
		activeTabsClassName: 'active',
		primaryView: 0
	},

	//------------------------------
	// Constructor
	//------------------------------

	initialize: function( selector, triggers, options ){
		this.options = options || {};
		// Initialize variables
		this.nodes = {
			triggers: {},
			views:    []
		};
		this.currentView = 0;
		this.autoplay_enabled    = !! this.options.autoPlay;
		this.autostop_enabled    = Object.isUndefined( this.options.autoStop ) ? true : !! this.options.autoStop;
		this.scaling_enabled     = Object.isUndefined( this.options.scaling  ) ? true : !! this.options.scaling;
		this.styling_enabled     = Object.isUndefined( this.options.styling  ) ? true : !! this.options.styling;
		this.delay               = this.options.delay               || this.defaults.delay;
		this.duration            = this.options.duration            || this.defaults.duration;
		this.currentView         = this.options.primaryView         || this.defaults.primaryView;
		this.activeTabsClassName = this.options.activeTabsClassName || this.defaults.activeTabsClassName;

		var scanNodes = function(){
			// Get views
			if( Object.isString(selector)){
				this.nodes.views = $$(selector);
			} else {
				$A(selector).each( function(e){
					this.nodes.views.push( $(e) || $$(e)[0]);
				}.bind(this));
			}
			// Get container
			if(this.options.container) this.nodes.container = $( this.options.container ) || $$(this.options.container)[this.currentView];
			else this.nodes.container = $( this.nodes.views[this.currentView].parentNode );

			// Containers style
			if(this.styling_enabled) this.nodes.container.setStyle({
				overflow: 'hidden',
				padding:  0
			});
			if( this.nodes.container.getStyle('position') == 'static' ) this.nodes.container.style.position = 'relative';
			// Views style
			this.nodes.views.each( function( e, i ){
				// Set style
				if(this.styling_enabled) e.setStyle({
					position: 'absolute',
					top:      0,
					left:     0,
					margin:   0
				});
				// Hide views
				e.hide();
			}.bind(this));

			// Show first view
			this.nodes.views[this.currentView].show();
			// Stretch container
			if(this.scaling_enabled) this.nodes.container.setStyle({
				height: this.nodes.views[this.currentView].offsetHeight +'px',
				width:  this.nodes.views[this.currentView].offsetWidth  +'px'
			});

			// Bind self object
			[ 'select', 'next', 'previous', 'play', 'stop', 'observe' ].each( function(key){
				this[key] = this[key].bind(this);
			}.bind(this));

			// Enable autoplay
			if(this.autoplay_enabled) this.play();

			// Start observing trigger event
			if(triggers){
				if(Object.isString(triggers)) triggers = $$(triggers);
				( Object.isArray(triggers) ? $R(0,triggers.length-1) : Object.keys(triggers)).each( function(key){
					if( ! triggers[key]) return;
					else if( Object.isElement( triggers[key]) ||( Object.isString( triggers[key]) && $( triggers[key]))) this.observe( triggers[key], ['click','keypress'], key );
					else ( Object.isString( triggers[key]) ? $$( triggers[key]) : $A( triggers[key])).each( function(e){ this.observe( e, ['click','keypress'], key ); }.bind(this));
				}.bind(this));
			}

			// Execute afterInitialized callback
			if(this.options.afterInitialized) try{
				( this.options.afterInitialized.bind(this))();
			} catch(e){alert(e);}

		}.bind(this);

		if(this.options.initiateImmediately) scanNodes();
		else Event.observe(window, 'load', scanNodes);
	},


	//------------------------------
	// Select view
	//------------------------------

	select: function( view ){
		// Calculate view number
		if( isNaN(view) && ! Object.isString(view)) view = 0;
		if( view !== 0 && ( view == '+' || view == undefined || view == '' )) view = this.currentView + 1;
		else if( view == '-' ) view = this.currentView - 1;
		if( view && ! isNaN(view)){
			if( view < 0 ) view = this.nodes.views.length - 1;
			if( view > this.nodes.views.length - 1 ) view = 0;
		}

		if( this.currentView != view ){
			// Select
			(( this.options.effect || function( next, current, container ){
				// Stop effect
				if( container.scaleEffect && container.scaleEffect.cancel ) container.scaleEffect.cancel();
				if( current.fadeEffect    && current.fadeEffect.cancel    ) current.fadeEffect.cancel();
				if( next.fadeEffect       && next.fadeEffect.cancel       ) next.fadeEffect.cancel();
				// Resize container
				next.setOpacity(0);
				next.show();
				if(this.scaling_enabled) container.scaleEffect = new Effect.Morph( container, { style: {
					height: next.offsetHeight +'px',
					width:  next.offsetWidth  +'px'
				}, duration: this.duration });
				// Fade view
				current.fadeEffect = new Effect.Fade( current, { duration: this.duration });
				next.fadeEffect    = new Effect.Appear(  next, { duration: this.duration });
			}).bind(this))( this.nodes.views[view], this.nodes.views[this.currentView], this.nodes.container );

			// Toggle tabs classname
			this.setTriggersActivity(view);
			this.setTriggersActivity( this.currentView, false );

			// Execute onSelect callback
			if(this.options.onSelect) try{
				( this.options.onSelect.bind(this))( view, this.currentView );
			} catch(e){alert(e);};

			this.currentView = view;
		}

		// Disable autoplay
		if(this.autostop_enabled) this.stop();
		else if(this.autoplay_enabled) this.play();
	},

	// Next
	next: function(evt){
		this.select('+');
		try{ if( evt ||( evt = window.event || event )) Event.stop(evt); } catch(err){}
	},

	// Previous
	previous: function(evt){
		this.select('-');
		try{ if( evt ||( evt = window.event || event )) Event.stop(evt); } catch(err){}
	},


	//------------------------------
	// Timer
	//------------------------------

	// Recursive timer
	autoplay: function(){
		// Next
		this.next();
		// Recursive call
		this.play();
	},

	// Enable autoplay
	play: function(evt){
		this.stop(evt);
		this.autoplay_enabled = true;
		this.autoplay_timer = setTimeout( this.autoplay.bind(this),  this.delay * 1000 );
		// Toggle triggers classname
		this.setTriggersActivity( 'play' );
		this.setTriggersActivity( 'stop', false );
	},

	// Disable autoplay
	stop: function(evt){
		this.autoplay_enabled = false;
		if( this.autoplay_timer ) clearTimeout( this.autoplay_timer );
		try{ if( evt ||( evt = window.event || event )) Event.stop(evt); } catch(err){}
		// Toggle triggers classname
		this.setTriggersActivity( 'stop' );
		this.setTriggersActivity( 'play', false );
	},


	//------------------------------
	// Observe trigger event
	//------------------------------

	// Begin trigger event observing
	observe: function( element, evt, func ){
		if([ 'next', 'previous', 'play', 'stop' ].indexOf(func) < 0 && isNaN(func))
			throw '[TabKit.observe] No such a method: '+ func;
		if( ! ( element = $(element))) return;
		( Object.isArray(evt) ? evt : [evt]).each( function(ev){
			Event.observe( element, ev, isNaN(func) ? this[func] : function(e){ this.select(func); if( e ||( e = window.event || event )) Event.stop(e); }.bindAsEventListener(this));
		}.bind(this));
		if( ! this.nodes.triggers[func]) this.nodes.triggers[func] = [];
		this.nodes.triggers[func].push(element);
		// Activate tabs classname
		if( func == this.currentView ) this.setTriggersActivity(func);
		else if( func == 'play' &&   this.autoplay_enabled ) this.setTriggersActivity( 'play' );
		else if( func == 'stop' && ! this.autoplay_enabled ) this.setTriggersActivity( 'stop' );
		return element;
	},


	//------------------------------
	// Toggle triggers classname
	//------------------------------

	setTriggersActivity: function( trigger, activate ){
		if( this.activeTabsClassName && this.nodes.triggers[trigger]){
			this.nodes.triggers[trigger].each( function(e){
				// Toggle classname
				if( activate || Object.isUndefined(activate)) e.addClassName(this.activeTabsClassName);
				else e.removeClassName(this.activeTabsClassName);
			}.bind(this));
		}
	}
});
