var app = new Object; // a blank object that can used to expose rails vars to js

var search_field;
var forum_search_field;
var newsletter_signup;
var user_system_focus;
var main_nav;
var page_carousel;

Event.observe(window,'load', setup_click_handlers);
Event.observe(window,'load', highlight_anchor);

function highlight_anchor() {
  loc = $$(location.hash).first().next();
  new Effect.Highlight(loc.id, { startcolor: '#ffff99', endcolor: '#ffffff', duration: 3.0, delay: 0.25 });
}

function setup_click_handlers() {
    $$('div.info_box').each(function(e) {
        Event.observe(e.select('.handle')[0], 'click',
        function(event) {
            target = event.target.parentNode.select('div.target')[0];
            Modalbox.show($(target.id), {width: 400,overlayOpacity:0, transitions:false,title: target.readAttribute('title')});
        });
    });

    $$('div.topic_tags').each(function(e) {
        Event.observe(e.select('.handle')[0], 'click',
        function(event) {
            target = event.target.parentNode.select('div.target')[0];
            Modalbox.show($(target.id), {width: 400});
        });
    });


    $$('div.post_edit').each(function(e) {
        Event.observe(e.select('.handle')[0], 'click',
        function(event) {
            target = $(this).parentNode.select('div.target')[0];
            Modalbox.show($(target.id), { method: 'put', title: target.readAttribute('title')});
        });
    });
}


// Wraps LivePipe's tab controls to create a fading carousel.
var Carousel = Class.create({
  initialize: function(container, navigation) {
    if(!$(navigation) || !$(container)) {
      throw "You specified a carousel component (container or navigation) that does not exist."; }

    // Time in miliseconds for auto-advancement of the carousel.
    this.interval_time = 9000;

    // Create a LivePipe tab control instance with fading transitions.
    this.tabs = new Control.Tabs(navigation, {
        showFunction : function (el) { $(el).appear({ duration: 0.3, delay : 0.3 }); },
        hideFunction : function (el) { $(el).fade({ duration : 0.3 }); }
    });

    this.controls = {
      play_pause: new Element('a', {'id': 'play_pause_id', 'class': 'play_pause', 'href': '#', 'title': 'Pause'}).update('Pause'),
      next: new Element('a', {'id' : 'go_next_id', 'class': 'go_next', 'href': '#', 'title': 'Next Pane'}).update('Next Pane'),
      prev: new Element('a', {'id' : 'go_prev_id', 'class': 'go_prev', 'href': '#', 'title': 'Previous Pane'}).update('Previous Pane')
    };

    this.controls.play_pause.observe( 'click', function(e){ Event.stop(e); this.toggle(); }.bind(this) );
    this.controls.next.observe( 'click', function(e){ Event.stop(e); this.next(); }.bind(this) );
    this.controls.prev.observe( 'click', function(e){ Event.stop(e); this.previous(); }.bind(this) );

    var carousel_playback_controls = new Element('div', {'class': 'carousel_playback_controls', 'id' : 'carousel_playback'});
    carousel_playback_controls.insert(this.controls.prev);
    carousel_playback_controls.insert(this.controls.play_pause);
    carousel_playback_controls.insert(this.controls.next);

    $(navigation).insert(carousel_playback_controls)

    // Start auto-advancement
    this.play();

    // Auto-Pause Disabled
    // Kill advancement on mouseenter
    // Restart on mouseleave
    // $(container).hover( this.pause.bind(this), this.play.bind(this) );
  },

  // Set a timer to manage auto-advancement.
  play: function() {
    this.timer = setInterval( this.next.bind(this), this.interval_time );
    this.playback_state = 'playing'
    this.controls.play_pause.removeClassName('paused').addClassName('playing').update("Pause").writeAttribute('title','Pause');
  },

  // Stops the auto-advancement timer.
  pause: function() {
    clearInterval(this.timer);
    this.playback_state = 'paused'
    this.controls.play_pause.removeClassName('playing').addClassName('paused').update("Play").writeAttribute('title','Play');;
  },

  // Toggles the play/paused state of the carousel
  toggle: function() {
    if(this.playback_state == 'playing') {
      this.pause();
    } else if(this.playback_state == 'paused') {
      this.play();
    }
  },

  // Move to the next pane. Adds wrap-around to LivePipe's next() method.
  next: function() {
    if ( this.tabs.activeLink == this.tabs.links.last() ) {
      this.tabs.first();
    } else {
      this.tabs.next();
    }
  },

  // Move to the previous pane. Adds wrap-around to LivePipe's previous() method.
  previous: function() {
    if ( this.tabs.activeLink == this.tabs.links.first() ) {
      this.tabs.last();
    } else {
      this.tabs.previous();
    }
  }
});

// Set placeholder value and bind focus/blur events for global search field.
var SearchField = Class.create({
  initialize: function(field, text) {
    this.placeholder_text = text + '...';

    if( !$(field) ) {
      return ;
    }

    this.field = $(field);

    this.field.observe( 'focus', this.clear.bind(this) );
    this.field.observe( 'blur', this.reset.bind(this) );

    this.reset();
  },

  // Clears the search field there isn't already a query in it.
  clear: function() {
    if( this.placeholder_text == this.field.value ){
      this.field.clear();
    }
    this.field.setStyle({
      color: '#000'
    });
  },

  // Resets the search field to display placeholder text if it is blank.
  reset: function() {
    if( '' == this.field.value ){
      this.field.value = this.placeholder_text
      this.field.setStyle({
        color: '#aaa'
      });
    }
  }
});



// Set placeholder value and bind focus/blur events for global search field.
var MessageField = Class.create({
  initialize: function(field, text) {
    this.placeholder_text = text + '...';

    if( !$(field) ) {
      return ;
    }

    this.field = $(field);

    this.field.observe( 'focus', this.focus.bind(this) );
    this.field.observe( 'blur', this.action.bind(this) );

    this.action();
  },

  // Clears the search field there isn't already a query in it.
  focus: function() {
    if( this.placeholder_text == this.field.value ){
      this.field.clear();
    }
    this.field.setStyle({
      color: '#000'
    });
  },

  // Clears the search field there isn't already a query in it.
  action: function() {
    if( '' == this.field.value ){
      this.field.value = this.placeholder_text
      this.field.setStyle({
        color: '#aaa'
      });
    }
  },

  // Resets the search field to display placeholder text if it is blank.
  reset: function() {
  }
});


// newsletter signup
// TODO this is cargo-cult, just copied from SearchField above, and should be generalized
var NewsletterSignup = Class.create({
  initialize: function(field) {
      this.placeholder_text = 'Your email';

      if( $(field) ) {

      this.field = $(field);

      this.field.observe( 'focus', this.clear.bind(this) );
      this.field.observe( 'blur', this.reset.bind(this) );

      this.reset();
    }
  },

  // Clears the search field there isn't already a query in it.
  clear: function() {
    if( this.placeholder_text == this.field.value ){
      this.field.clear();
    }
    this.field.setStyle({
      color: '#000'
    });
  },

  // Resets the search field to display placeholder text if it is blank.
  reset: function() {
    if( '' == this.field.value ){
      this.field.value = this.placeholder_text
      this.field.setStyle({
        color: '#aaa'
      });
    }
  }
});


// Handles interaction for the main nav. Wraps a LivePipe tab control.
var MainNav = Class.create({
  initialize: function(container, controls) {

    if(!$(controls) || !$(container)) {
/* if there's no main_nav_ul, this `throw` call prevents the rest of the page JS from running
 * the conditional is weird since i wanted to make the fewest changes possible
 *
 *    throw "You specified a nav component (container or controls) that does not exist.";
 */
    }
    else {

      // Create a LivePipe tab control instance.
      this.tabs = new Control.Tabs(controls, {
          linkSelector: 'li',
          hover: true
      });

      // Using protohover, define clear the current tab the the mouse leave the container.
      $(container).observe('mouseleave', this.clear.bind(this) );

      // Clear the initally active first tab.
      this.clear();
    }
  },

  clear: function() {
    if(this.tabs.activeContainer) {
      this.tabs.options.hideFunction(this.tabs.activeContainer); }

    this.tabs.links.each(function(item){
      (this.tabs.options.setClassOnContainer ? $(item.parentNode) : item).removeClassName(this.tabs.options.activeClassName);
    }.bind(this));
  }
})

// Run when the DOM is ready
document.observe("dom:loaded", function() {

  // Initialize the interaction for the main nav.
  main_nav = new MainNav('nav','main_nav_ul');

  // Set placeholder value and bind focus/blur events for global search field.
  search_field = new SearchField('global_search_input', 'Search');
  user_system_focus = new MessageField('user_system_focus', 'e.g., Corrections, courts, law enforcmenet, mental health court');
  forum_search_field = new SearchField('forum_search_input', 'Search Forum');
  newsletter_signup = new NewsletterSignup('tdkiih-tdkiih');

  // Initialize the page carousel if needed.
  if($('carousel_controls')) {
    page_carousel = new Carousel('carousel','carousel_controls');
  }

  $$('.javascript').each(function(e) { eval(e.firstChild.data); });
  $$('ul.control_tabs').each(function(e) {
    var t = new Control.Tabs(e.id);

    $$('.' + e.id + '_next').each(function(i) {
    i.observe('click', function(e) {
      t.next();
      Event.stop(e);
    }.bindAsEventListener(e.id));
  }); });

});

