var speed = 400;

$( document ).ready( function()
{
  /*
   * Declarations.
   *
   */

  var loaded  = [];
  var frame   = $( 'div#frame' );
  var content = $( 'div#content' );
  var menu    = $( 'ul#menu' );
  var loading = $( 'div#loading' );
  var last    = false;
  var open    = false;
  var defHeight = 460;

  /*
   * Functions.
   *
   */

  // Menu button clicked.
  function clickMenuButton( btn )
  {
    $('a#close').hide();

    // Check whether frame is open.
    if( ! open )
    {
      frame.fadeIn( speed, function()
      {
        // Display frame.
        open = true;
        clickMenuButton( btn );
      });
      menu.removeClass( 'rounded' );
      return;
    }

    // Determine whether the button is newly clicked or re-clicked.
    if( last != false && last.attr( 'href' ) == btn.attr( 'href' ))
    {
      // Clear screen.
      frame.fadeOut( speed, function() { content.hide(); open = false; menu.addClass( 'rounded' ); });
      btn.removeClass( 'active' ); last = false;
    }
    else
    {
      // Clear content and load new page.
      content.fadeOut( speed, function()
      {
        if( loaded[ btn.attr( 'href' ) ] == undefined )
        {
          // Load from URL.
          loading.show();
          content.load( 'pages/' + btn.attr( 'href' ) + '.php', function()
          {
            loading.hide();
            //loaded[ btn.attr( 'href' ) ] = content.html();
            content.fadeIn( speed, function()
            {
              $('a#close').fadeIn(speed);
            });
          });
        }
        else
        {
          // Load from memory.
          content.html( loaded[ btn.attr( 'href' ) ]);
          content.fadeIn( speed );
        }
      });

      // Switch active states.
      if( last != false ) last.removeClass( 'active' );
      btn.addClass( 'active' ); last = btn;
    }
  }

  /*
   * Procedural.
   *
   */

  // Init content.
  if( content.html())
  {
    frame.show();
    content.show();

    // Init values.
    var href = document.location.href.split("/"); href = href[href.length-1];
    if( href ) last = $("a#"+href);
  }

  // Init navigation.
  $( 'ul#menu li a' ).click( function() { clickMenuButton( $( this )); return false; });
  menu.addClass( 'rounded' );

  // Init close button.
  $( 'a#close' ).click( function()
  {
    // Clear screen.
    btn = $('ul#menu li a.active');
    frame.fadeOut( speed, function() { content.hide(); open = false; menu.addClass( 'rounded' ); });
    btn.removeClass( 'active' ); last = false;
    return false;
  });

});
