jQuery(function($) {
  
  $('p').each(function() { if($(this).html().length == 0) { $(this).remove(); } });
  
  topDebounce = null;
  
  $(window).bind('scroll', function() {
    
    if(topDebounce) { clearTimeout(topDebounce); }
    
    if($(window).scrollTop() > 100 && !do_splash) {
      topDebounce = setTimeout(function() { $('#top').stop(true, true).fadeIn(); }, 50);
    } else {
      topDebounce = setTimeout(function() { $('#top').stop(true, true).fadeOut(); }, 50);
    }

  }).bind('resize', function() {
    
    lightbox.resize();
    
  });
  
  $('body').addClass('clearfix');
  
  $('#top').click(function(event) {
    event.preventDefault();
    $.scrollTo(0, 500, {
      axis: 'y',
      easing: 'easeOutExpo'
    });
  });
  
  $('nav li a').click(function(event) {
    
      if($(this).attr('href') == '#') { event.preventDefault(); }
      if($(this).parents('li').first().hasClass('active')) {
        $(this).parents('li').first().removeClass('active');
      } else {
        $(this).parents('ul').last().find('li').removeClass('active');
        $(this).parents('li').addClass('active');
      }
    
  });
  
  $('ul ul ul .active').parents('li').addClass('active');

  lightbox = {
    
    bind: function() {
      
      $(window).bind('keydown', function() { if(event.keyCode == 27) { lightbox.hide(); } });
      
      $('body').append(
        $('<div />').attr('id', 'blanket').click(function() { lightbox.hide(); })
      ).append(
        $('<div />').attr('id', 'lightbox').append(
          $('<div />').addClass('inner').append(
            $('<div />').addClass('image').append(
              $('<img />')
            )
          ).append(
            $('<div />').addClass('caption').append(
              $('<div />').addClass('text')
            ).append(
              $('<div />').addClass('int').text('1 / 1')
            ).append(
              $('<div />').addClass('controls').append(
                $('<a />').attr('href', '#').attr('rel', 'close').text('Close').click(function(event) { event.preventDefault(); lightbox.hide(); })
              ).append(
                $('<a />').attr('href', '#').attr('rel', 'previous').text('Previous')
              ).append(
                $('<a />').attr('href', '#').attr('rel', 'next').text('Next')
              )
            )
          )
        )
      );
      
      $lightboxImages = $('a[rel="lightbox"]');
      
      $lightboxImages.each(function() {
        $(this).click(function(event) {
          event.preventDefault();
          lightbox.display(this);
        });
      });
      
    },
    
    reset: function() {
      $('#lightbox .image').attr('src', '#');
      $('#lightbox').stop(true, true).fadeOut('fast');
    },
    
    display: function(whom) {
      
      lightbox.reset();
      
      $('#blanket').stop(true, true).fadeIn('fast');
      
      currentIndex = $lightboxImages.index($(whom));
      
      $('#lightbox a[rel="next"], #lightbox a[rel="previous"]').unbind('click').click(function(event) { event.preventDefault(); lightbox.hide(); }).addClass('dim');
      
      preloader = new Image();
      
      preloader.onload = function() {
        $('#lightbox img').attr('src', $(this).attr('src')).parents('.image').fadeIn();
  
        $(this).unbind('load');
        
        $('#loading').stop(true, true).fadeOut('fast');

        $('#lightbox .caption .text').html($(whom).data('caption'));
        
        $('#lightbox .int').text((currentIndex + 1) + ' / ' + $('a[rel="lightbox"]').length.toString());
        
        if($lightboxImages[currentIndex+1]) { $('#lightbox a[rel="next"]').removeClass('dim').unbind('click').click(function(event) { event.preventDefault(); lightbox.display($lightboxImages[currentIndex+1]); }); }

        if($lightboxImages[currentIndex-1]) { $('#lightbox a[rel="previous"]').removeClass('dim').unbind('click').click(function(event) { event.preventDefault(); lightbox.display($lightboxImages[currentIndex-1]); }); }
        
        $('#lightbox').stop(true, true).fadeIn('fast');
        
        setTimeout(function() { lightbox.resize(); }, 500);
      }
      
      preloader.src = $(whom).attr('href');
      
      if(!preloader.complete) {
        $('#loading').stop(true, true).fadeIn('fast');
      }
    },
    
    hide: function() {
      $('#blanket, #lightbox').stop(true, true).fadeOut('fast', function() {
        $('#lightbox .image').fadeOut('fast').attr('src', '#');
        preloader = new Image();
      });
    },
    
    resize: function() {
      
      if($('#lightbox').is(':visible')) {
        
        $('#lightbox img').css('width', 'auto').css('height', 'auto');
        
        if($(window).height() < ($('#lightbox img').height() + 40)) {
          $('#lightbox img').css('height', $(window).height() - 100).css('width', 'auto');
        }
        
        $('#lightbox .inner').css('marginTop', ($(window).height() - $('#lightbox .inner').height()) / 2)
        
        $('#lightbox a[rel="next"], #lightbox a[rel="previous"]').css('top', $(window).height() / 2 - 30)
        
      }
      
    }
    
  }
  
  lightbox.bind();
  
  splash = function() {
    
    if(do_splash == true && $.cookie('splash_seen') != 'true') {
      
      splash_preload = new Image();
      splash_preload.src = splash_image;
      
      $('#navigation').hide();
      $('content > div[columns] > [gutter] *').fadeTo(0, 0);
      $('body').append(
        $('<div />').attr('id', 'splash_image').css('background-image', 'url("'+splash_image+'")').click(function() { close_splash(); })
      );
      
      $('#enter').show().find('a').click(function(event) { event.preventDefault(); close_splash(); });
      
    }
    
  }();
  
  close_splash = function() {
    
    $('#navigation').fadeIn();
    $('content > div[columns] > [gutter] *').fadeTo('default', 1);
    $('#splash_image, #enter').fadeOut(function() { $(this).remove(); });
    $.cookie('splash_seen', 'true', 1);
    
  }
  
  $('nav li.sector').tsort({ attr: 'data-sort' });

});
