/*jslint browser: true, onevar: true, undef: true, eqeqeq: true, bitwise: true, newcap: true, immed: true */
/*global document, window, jQuery */
// GPL. written by Andrew Smith - Andrew_S1 - a savage reworking of Charles Johnson's Footnotes for Wordpress - projects.radgeek.com/wp-footnotes.php

( function footnote_main( $ ) {

var hovering = false;

$.fn.extend( { footnoteclose: function footnoteclose() {
  var that = this;
  this.fadeOut('slow', function footnote_fader() { that.remove().empty(); } );
  return this;
  } } );

function closeInlineWindow() {
  $( this ).parents( ".footnoteContainer" ).footnoteclose();
  return true;
}

function delayFadeOnMouseLeave( event ) {

}

function newInlineWindow( event ){

  // First close all previous inline windows...
  $(".footnoteContainer").footnoteclose();

  hovering = event.data.hover;

  var xpos, innerWindowContentBox, outerWindowTipBox, outerWindowContentBox, boxBottom, windowBottom, innerWindowContent,

      // Setup some constants for use in creating the inline window...
      windowWidth = Math.round( $(window).width() * 0.45 ),
      windowHeight = Math.round( $(window).height() * 0.45 ),
      windowPadding = 14,
      windowTextPadding = 5,
      windowFontSize = 10,
      windowBorderSize = 1,
      windowButtonHeight = 11,
      windowButtonTextSize = 12,
      cssBoxHeight = windowHeight - ( windowPadding + windowBorderSize ) * 2,
      pageBoundPadding = 10,      // stop the window before getting this close to the bottom of the screen
    
      cssobj = {
        margin: "0 3px " + Math.round((windowPadding-windowButtonHeight)/2) + "px",
	height: "" + windowButtonHeight + "px",
        fontSize: "" + windowButtonTextSize + "px",
        lineHeight: "" + windowButtonTextSize + "px" },

      link = event.target,
      thisHref = link.href.replace( /^.*\#/, "#" ),
      $link = $(link),
      elementPos = $link.offset(), // get the position of the element that was clicked on...
      ypos = elementPos.top + $link.height() + 3,  // setup the y-positioning of the inline window...

      noteTitle = ( link.title ? link.title : "footnote" ),
      container = $("<div>").
        addClass( "footnoteContainer" ).  
        css( { display: "none" } ).
        prependTo( "body:first" ).
        bind( "mouseleave", delayFadeOnMouseLeave )
      ;

	
  if (noteTitle.indexOf( ":" ) > -1) { // Split off note gloss
    noteTitle = noteTitle.substring( 0, noteTitle.indexOf( ":" ) );
  }

  // stop the window before getting this close to the left/right/top/bottom of the screen
  
  // setup the x-position of the inline window...
  // check to see if the left 1/3 of the window will overlap the left page bound..
  if ( elementPos.left - (windowWidth/3) < pageBoundPadding ) {
    xpos = pageBoundPadding;
  } 
  // check to see if the right 2/3 of the window will overlap the right page bound...
  else if ( elementPos.left + (windowWidth*2/3) > document.width - pageBoundPadding ) {
    xpos = document.width - pageBoundPadding - windowWidth;
  }
  else {
    // if we're not going to hit either wall, set the window to be offset
    // by 1/3 to the left of where we clicked (looks better than centering
    xpos = elementPos.left - ( windowWidth / 3 );
  }

  outerWindowContentBox = $( "<div>" ).
    appendTo( container ).
    addClass( "float-a-note" ).
    width( windowWidth - ( windowPadding + windowBorderSize ) * 2 ).
    css( {
      top: ypos + 9,
      left: xpos,
      margin: 0,
      maxHeight: "" + cssBoxHeight + "px",
      padding: "" + Math.round( ( windowPadding - windowButtonHeight ) / 2 ) + "px " + windowPadding + "px " + windowPadding + "px",
      border: "" + windowBorderSize + "px solid #eee;",
      fontSize: "" + windowFontSize + "pt" } ).
    append( 
      $( "<a>" ).
	text( noteTitle ).
	addClass( "note-label" ).
	css( { float: "left", cursor: "auto" } ).
	css( cssobj )
      ).
    append(
      $( "<a>" ).
	addClass( "note-label" ).
	click( closeInlineWindow ).
	text( "close" ).
	css( cssobj ) 
      );

  // Copy the content over from the footnote
  innerWindowContent = $("<div>").addClass( "footnote-inner" ).html( $( thisHref ).html() );

  innerWindowContentBox = $("<div>").
    append( innerWindowContent ). 
    addClass( "footnote" ).
    css( { maxHeight: "" + ( cssBoxHeight - 2 * windowPadding ) + "px",
	   padding: "" + windowTextPadding + "px" } ).
    appendTo( outerWindowContentBox );

  outerWindowTipBox =  $("<div>").
    addClass( "tipbox").
    css( { left: elementPos.left - 8, 
           top: ypos } ).
    appendTo( container );
	
  // check to see if the window goes beyond the bottom of the viewport...
  boxBottom = elementPos.top + outerWindowContentBox.height() + pageBoundPadding;
  windowBottom = window.pageYOffset + window.innerHeight;
	
  // below the fold; bring 'er up
  if ( boxBottom > windowBottom ) {
    outerWindowContentBox.
      css( { top: elementPos.top - outerWindowContentBox.height() - 9 } );
    outerWindowTipBox.
      css( { top: elementPos.top - 10 } ).
      addClass( "tipboxdown" );
  }

  if ( hovering ) {
    $link.
      add( container ).
	bind( "mouseleave.footnote", delayFadeOnMouseLeave );
  }

  $(document).bind( "keypress.footnote", function footnote_keypressed(e) { 
      if ( e.keyCode !== 27 ) return true;
      // escape key pressed
      container.footnoteclose()
      $( document ).unbind( "keypress.footnote" );
      return false;
    } );

  container.fadeIn( "slow");

  // only add an "expand" button if our popup has scrollbars;
  // we have to do this after the box has been displayed, so that we can get its real height
  if ( innerWindowContent.height() > cssBoxHeight ) {
    $( "<a>" ).
      addClass( "note-label" ).
      text( "expand" ).
      attr( { href: thisHref } ).
      click( closeInlineWindow ).
      css( cssobj ).
      insertAfter( ".note-label:last" );
  }
  event.stopPropagation();
  return false;
}

$(document).ready( function footnote_init() {
  $( "a.footnoted" ).
    bind( "click.footnote", { hover: false }, newInlineWindow )/*.
    bind( "mouseenter.footnote",  { hover: true }, newInlineWindow )*/;
  } );

}( jQuery ) );