/**
 * Billboard - jQuery Plugin
 * The simplest and easiest to implement rotating billboard.
 *
 * Examples and documentation coming soon.
 *
 * Copyright (c) 2010 Anther LLC.
 * If you find any bugs or want to submit additions to the code please feel
 * free to contact steve@antherllc.com
 *
 * Version 1.0 (11/23/2010)
 * Requires jQuery v1.3+
 *
 * Dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 *
 * Much love to everyone that has written jQuery tutorials.
 */
(function($) {

  // Declare our plugin
  $.fn.billboard = function(images, titles, userOptions) {

    // If this plugin is being called on multiple instances, we need
    // to handle each of them to ensure we maintain chainability.
    if(this.length > 1) {

      this.each(function() {
        $(this).billboard(userOptions)
      });

      return this;
    }

    //preload images
    $(images).each(function(){
        $('<img/>')[0].src = this;
    });

    // preload titles
    $(titles).each(function(){
        $('<img/>')[0].src = this;
    });

    // We've made it past handling all of the nodes we need to work on, so
    // we need to declare our class variables

    //
    // Public class variables
    //

    /** @var the number of panels for this billboard */
    this.panelCount = 0;

    /** @var the index of the panel currently being SHOWN */
    this.currentPanelIndex = 0;

    /** @var default settings for the plugin */
    this.defaultSettings = {
      panelClass : 'billboard-panel',
      titleClass : 'billboard-title',
      speed : 5000
    };

    /** @var user-defined settings for the plugin */
    this.options = {};

    //
    // Private class variables
    //

    /**
     * @var Interval that makes a callback to the swap method every n seconds
     */
    var swapper;

    

    //
    // Public methods
    //

    /**
     * Starts cycling the billboard panels
     */
    this.start = function() {
      var billboard = this;
      
      swapper = setInterval(function() {swap(billboard,1)}, this.options.speed);      
    };

    /**
     * Stops cycling the billboard panels
     */
    this.stop = function() {
      clearInterval(swapper);
    };

    this.display = function(index, billboard) {
      var panelClass = '.' + billboard.options.panelClass;
      this.currentPanelIndex = index;
      billboard.children(panelClass).hide();

      // show the background image
      billboard.children(panelClass + ':eq(' + index + ')').show();

      // animate the title
      animateTitle(billboard, index, billboard.options.speed / 2);
                 
      $('#billboard-controller').children().removeClass('current-panel');

      $('#billboard-controller')
        .children(':eq(' + index + ')')
          .addClass('current-panel');
    };

    //
    // Private Methods
    //
    this.init = function() {

      // make the reference easier:
      // this is equivalent to the object we are inside
      // $this is equivalent to the jQuery object that is being billboard'd
      var $this = $(this);
      var billboard = this;

      // extend our user-defined options into our defaults
      if(userOptions) {
        $.extend(billboard.options, billboard.defaultSettings, userOptions);
      }
      else {
        $.extend(billboard.options, billboard.defaultSettings);
      }

      // set the private variables as needed
      billboard.panelCount = images.length;

      // create our panels and titles
      for(var i = 0; i < billboard.panelCount; i++){
        var billboardClass = billboard.options.panelClass;
        var titleClass = billboard.options.titleClass;

        $this.append(
          '<div class="' + billboardClass + '" id="panel-' + i + '">' 
            + '<div class="' + titleClass + '" id="title-' + i + '"></div>' +
          '</div>'
        );

        $('#panel-' + i).css('background-image', 'url(' + images[i] + ')');
        $('#title-' + i).css('background-image', 'url(' + titles[i] + ')');

        if(i == 0)
        {
          $('#title-' + i)
            .css('height', '100%')
            .css('width', '665px')
            .css('left', '-145px')
            .attr('class', billboard.options.titleClass + ' remove');
        }
      }
      

      // hide all of the children
      $this.children('.' + billboard.options.panelClass)
       .mouseover(function(){
         billboard.stop();
//         $('#controller-forward').fadeIn("fast")
//         $('#controller-backward').fadeIn("fast")
       })
       .mouseout(function(){
//         $('#controller-forward').fadeOut("fast")
//         $('#controller-backward').fadeOut("fast")
         billboard.start();
       })
       .hide();

      // create the controls
      createControls(billboard);

      // show the first child
      $this.children('.' + billboard.options.panelClass + ':eq(0)').show();

      animateTitle(billboard, 0, billboard.options.speed / 2);

      // start the billboarding!
      billboard.start();

      // Ensure that we return 'this' to maintain chainability
      // For example, if we wanted to we could call
      //       $('#mydiv').billboard().stop()
      //
      return billboard;
    }

    return this.init();
  }

  function createControls(billboard) {

    var panelCount = billboard.panelCount;

    // Insert a div into the billboard to hold the buttons
    $('#billboard').append('<div id="controller-forward"></div>');
    $('#billboard').append('<div id="controller-backward"></div>');


    $('#controller-forward')
     .click(function(){
        billboard.stop();
        swap(billboard,1);
        billboard.start();
      });
    $('#controller-backward')
     .click(function(){
        billboard.stop()
        swap(billboard,-1);
        billboard.start();
      });

    var count = 0;
    for(count = 1; count <= panelCount; count++) {
      $link = $('<a href="Javascript:void(0); return 0;" class="billboard-button">' + count + '</a>')
                .mouseover(function() {
                  billboard.stop();
                  
                })
                .mouseout(function() {
                  billboard.start();
                });

      if(count == 1) {
        $link.addClass('current-panel');
      }
                
      $('#billboard-controller').append($link);
    }
  }

  function animateTitle(billboard, index, speed){
    $('.' + billboard.options.titleClass)
      .stop(true, true) //stop animating
      .css('margin-left', '0'); //reset position
    $('#title-' + index).show();
    $('#title-'+index).animate({marginLeft: 196},speed);
  }

  /**
   * Swaps the billboard panels
   */
  function swap(billboard, direction) {

    if($('.remove').length > 0)
    {
      var removeId = $('.remove').parent('div').attr('id');
      $('#' + removeId).remove();
      billboard.panelCount--;
      billboard.currentPanelIndex = billboard.panelCount -1;
    }

    // if we're at the end, make it start over at 0
    if(billboard.currentPanelIndex == billboard.panelCount - 1)
    {
      if(direction == -1)
      {
        billboard.currentPanelIndex = billboard.currentPanelIndex + direction;
      }
      else
      {
        billboard.currentPanelIndex = 0;
      }
    }
    else
    {
      if(direction == -1 && billboard.currentPanelIndex == 0)
      {
        billboard.currentPanelIndex = billboard.panelCount - 1;
      }
      else
      {
        billboard.currentPanelIndex = billboard.currentPanelIndex + direction;
      }
    }

    billboard.display(billboard.currentPanelIndex, billboard);
    animateTitle(billboard, billboard.currentPanelIndex + 1, billboard.options.speed / 2);

  }
})(jQuery);
