//  wydiwys navigation function
//  v0.2  2009 Aug 7 by Keith Lofstrom   
//     with window scaling and preload

$(window).resize(  function(){ scale() });

// keyboard / remote navigation

function navigate( current, first, prev, enter, next, last ) {
   $(document).ready(function(){   
      scale();                       // scale the new drawing
      $(document).keydown( function(e) {
         switch (e.which) {
            case 36: window.location = first;  break; // home      key
            case 35: window.location = last;   break; // end       key
            case 40: window.location = next;   break; // down      key
            case 39: window.location = next;   break; // right     key
            case 32: window.location = next;   break; // space     key
            case 37: window.location = prev;   break; // left      key
            case 38: window.location = prev;   break; // up        key
            case  8: window.location = prev;   break; // backspace key
            case 13: window.location = enter;  break; // enter     key
            // wireless remote
            case 34: window.location = next;   break; // forward   button
            case 33: window.location = prev;   break; // back      button
            case 66: window.location = enter;  break; // enter     button
         }
      });
      // preload next images
      if ( first !== current ) { pload ( first ) }
      if ( prev  !== current ) { pload ( prev  ) }
      if ( next  !== current ) { pload ( next  ) }
      if ( last  !== current ) { pload ( last  ) }
   });
}

//  preload the next image
function pload( image_with_html ) {
   var image_without_html = image_with_html.replace( /\.htm(l)?/ ,'' );
   jQuery("<img>").attr("src", image_without_html );
}

//  scale the current image
//  for best results, this requires margins and padding to be zero

function scale() {
   var WindowHeight = $(window).height();
   var WindowWidth  = $(window).width();
   var WindowAspect = WindowWidth/WindowHeight;
   $('img').each(function(){           // OK, only one img, but this is easy
      var ImageHeight = $(this).height();
      var ImageWidth  = $(this).width();
      var ImageAspect  = ImageWidth/ImageHeight;

      if( ImageAspect < WindowAspect ) {               // wide image
         $(this).height( WindowHeight ) ;
         $(this).width( WindowHeight*ImageAspect );
      } else {                                         // tall image
         $(this).height( WindowWidth/ImageAspect );
         $(this).width ( WindowWidth  ) ;
      }
   }); 
}
