/*
 * Attempts to adjust the vertical position of a
 * relative positioned element so that it is 
 * visible in the viewport. When the element
 * doesn't fit in the viewport, we position
 * it at scroll_top.
 * 
 * Currently, this may not be really generic
 * enough to be generally useful plug-in.
 * The reset is kind of wrong. We're 
 * probably also not taking 
 * borders/margins/padding into
 * proper account.
 * 
 */

// TODO: this is one idea for the reset, but not a great one
// var smartVerticalAlignDefaults = new Array();

jQuery.fn.smartVerticalAlign = function() {
  return this.each(function(i){
    var $element = $(this);
    
    var fudge = 15; // TODO: accomodate borders, padding, etc.

    // reset first
    var original_top = '0';
    /*
    if( $element.attr('id') ){
      var stored  = smartVerticalAlignDefaults[$element.attr('id')];
      if( stored ){
        original_top = stored;
      }
      else {
        original_top = $element.position().top;
        smartVerticalAlignDefaults[$element.attr('id')] = original_top;
      }
    }
    */
    $element.css( 'visibility', 'hidden' );
    $element.css( 'display', 'block' );
    $element.css('top', original_top + 'px');

    var e_height = $element.height() + fudge;
    var w_height = $(window).height();
    var e_top_offset = $element.offset().top;
    var e_top = $element.position().top;
    var e_bottom = e_top_offset + e_height;
    var e_new_top = null;
    var scroll_top = $(window).scrollTop();
    var statusMsg = '';
    if( e_top_offset < scroll_top ){
      statusMsg = 'a';
      e_new_top = e_top + (scroll_top - e_top_offset);
    }
    else if( e_bottom > (w_height + scroll_top) ){
      statusMsg = 'b';
      e_new_top = e_top - (e_bottom - (w_height + scroll_top));
      e_new_offset =  e_top_offset - (e_bottom - (w_height + scroll_top)); 
      if( e_new_offset < scroll_top ){
        statusMsg = 'c';
        e_new_top = e_new_top + (scroll_top - e_new_offset);
      }
    }
    if( e_new_top != null ){
      e_new_top = e_new_top + 'px';
      // window.status = statusMsg + ' ' + e_new_top;
      $element.css('top', e_new_top );
    }
    else {
      // window.status = 'd';
    }
    $element.css( 'display', 'none' );
    $element.css( 'visibility', 'visible' );
    $element.fadeIn( 'def' );
  });
};

