/*
 * jQuery subSlider 0.0.2 - Fancy, yes?
 *
 * Copyright (c) 2008 Greater Good, Inc (wearegreatergood.com)
 *
 */
$.fn.subSlider = function(settings){
  
  // Firefox 2 gets nothing..
  if ( $.browser.mozilla && $.browser.version.substr(0,3) == '1.8' ) return;
  // neither does IE 6 and below
  if ( $.browser.msie && $.browser.version.substr(0,3) <= '6.0') return;
  
  var container   = this;
  var width       = 0;
  var top         = 0;
  var left        = 0;
  var background  = $('<div class="background"><!-- --></div>').css({
    position: 'absolute',
    zIndex: '-8'
  });
  
  findHome();
  $(this).prepend(background);

  $(container).children('a').each(function(i){
    $(this).mouseover(function(e){ move(this); });
    $(this).mouseout(function(e){ move(); });
    $(this).click(function(e){ setCurrent(this); });
  });
  
  function findHome(){
    var current     = $(container).children('.current:first');
    var firstChild  = $(container).children('a:first');
    var home        = ($(current).length) ? (current) : ($(container).children('a:first'));
    width           = ($(current).length) ? getWidth(home) : 0;
    top             = $(home).position().top;
    left            = getLeft(home);
    
    $(background).css({
      top: top,
      left: left,
      width: width
    });
  } // end function findHome()
  
  function move(to){
    if ( $(to).hasClass('current') ) return;
    
    var moveTo    = (to) ? getLeft(to)  : left;
    var resizeTo  = (to) ? getWidth(to) : width;
    
    $(background).animate({
      left: moveTo,
      width: resizeTo
    }, {
      queue: false,
      duration: 800
    });
  } // end function move();
  
  function setCurrent(el){
    $(container).children('a').each(function(i){ 
      $(el).removeClass('current');
    });

    $(el).addClass('current');
    
    width           = getWidth(el);
    left            = getLeft(el);
    
    move(el);
  } // end function setCurrent()
  
  function getWidth(el){ // shortening things
    return $(el).outerWidth(true);
  } // end function getWidth();
  
  function getLeft(el){ // just call me stubs..
    var margins = parseInt($(el).css('margin-left')) + parseInt($(el).css('margin-right'));
    return $(el).offset().left - margins/2;
  } // end function getLeft()
} // end subSlider plugin