// (c) 2009 Patrick Reiner. All rights reserved.

// Turns ordinary tabs into JS tabs with blind effect
//
// === Applied Via
// * class "js_blind_tab"
//
// === Requirements
// * tab element ids must be of the form 'tab_X' where X is an integer from 0 to 10
// * tab content element ids must be of the form 'tab_X_content'
//
// === Example
//   <div id="tab_0" class="js_blind_tab">
//   ...
//   <div id="tab_0_content">
//
var JSBlindTab = Behavior.create({
  initialize : function() {
    // Determine tab number and tab content div from element 'id'
    this.tab_number = parseInt( this.element.readAttribute( 'id' ).split( '_' ).reverse()[ 0 ] )
    this.content_element = $( 'tab_' + this.tab_number + '_content' )
    
    // Validate tab number and content div
    if ( this.tab_number === NaN || this.content_element === null ) {
      console.assert( AB_GLOBALS.get( 'RAILS_ENV' ) == 'production', 'Could not apply margin to CSS: ' + this.element.readAttribute( 'class' ) )
    }
  },
  onclick : function() {
    // Remove 'unselected_tab' and add 'selected_tab' class to THIS tab
    // Add 'unselected_tab' and remove 'selected_tab' class from all tabs except THIS tab
    for ( var i=0; i < 10; i++ ) {
      tab_element = $( 'tab_' + i )
      if ( tab_element !== null && i != this.tab_number ) {
        tab_element.removeClassName( 'selected_tab' )
        tab_element.addClassName( 'unselected_tab' )
      } else if ( tab_element !== null && i == this.tab_number ) {
        tab_element.addClassName( 'selected_tab' )
        tab_element.removeClassName( 'unselected_tab' )
      }
    }
    
    // Hide all tab contents except THIS tab's
    for ( var i=0; i < 10; i++ ) {
      content_element = $( 'tab_' + i + '_content' )
      if ( content_element !== null && i != this.tab_number && content_element.visible() === true ) {
        Effect.toggle( content_element, 'blind', { duration: 0.5, queue: { scope:'tabs', position:'end', limit: 3 } } )
      }
    }
    
    // Show THIS tab content, if not already shown
    if ( this.content_element.visible() === false ) {
    	Effect.toggle( this.content_element, 'blind', { duration: 0.5, queue: { scope:'tabs', position:'end', limit: 3 } } )
    }
    
    // Return false to cancel link
    return false
  }
})
Event.addBehavior( { '.js_blind_tab': JSBlindTab() } )