$(document).ready(function(){
  
  $.easing.def = 'easeOutExpo';
  var speed = 500;
  
  var loadImages = function() {
    $('img').load(function(e) {
      setTimeout(function() {
        $(e.currentTarget).fadeTo('slow', 1);
      }, 100);
    }).fadeTo(0, 0);
  };
  
  var touchEvents = function() {
    
    $('.toggle').bind('touchstart touchend', function(event) {
      event.preventDefault();
      $(this).toggleClass('hover');
    });
    
  }();
  
  var textBreaks = function() {
    
    $('.post .content p').each(function() {
      
      if($(this).find('img').length > 0) {
        
        $(this).find('br').remove();
        
        $(this).find('img').each(function() {
          
          $(this).addClass($(this).attr('alt'));
          
          if($(this).height() > $(this).parents('p').eq(0).height()) {
            $(this).parents('p').eq(0).css('height', $(this).height());
          }
          
        })
        
      }
      
      if($(this).text().length > 10) {
        $(this).css('width', 325).wrap($('<p />').css('margin-bottom', 0));
      }
      
    });
    
  }
  
  var pjax = function() {
    
    $('span[rel="next"]').eq(0).parents('a').attr('rel', 'next');
    $('span[rel="prev"]').eq(0).parents('a').attr('rel', 'prev');
    
    $pjax = $('#footer').find('a[rel="next"], a[rel="prev"]')
    
    $pjax.click(function(e) {
      
      e.preventDefault();
      
      $pjax_url = $(this).attr('href');
      $pjax_rel = $(this).attr('rel');
      
      $.ajax({
        url: $pjax_url,
        beforeSend: function() {
          
          $('#footer').hide();
          
          if($pjax_rel == 'next') {
           
            $('#content').animate({
              left: 0 - $('#content').width()
            }, speed, $.easing.def).animate({ left: $(window).width() }, 0);
            
          }
          
          if($pjax_rel == 'prev') {
           
            $('#content').animate({
              left: $(window).width()
            }, speed, $.easing.def).animate({ left: 0 - $('#content').width() }, 0);
            
          }
          
        },
        success: function(response) {
          
          if($pjax_rel == 'next') {
            
            pjaxFinished($pjax_url, response);
            
            $('#content').animate({
              left: 0
            }, speed, $.easing.def, function() {
              $('#footer').fadeIn();
            });
            
          }
          
          if($pjax_rel == 'prev') {
            
            pjaxFinished($pjax_url, response);
            
            $('#content').animate({
              left: 0
            }, speed, $.easing.def, function() {
              $('#footer').fadeIn();
            });
            
          }
          
          textBreaks();
        
        }
      })
      
    });
    
    
  }
  
  var replaceContent = function(selector, content) {
    
    $(selector).html(
      $(content).find(selector)
    );
    
  }
  
  var pjaxFinished = function(url, response) {
 
    $(window)._scrollable().scrollTo(0, 0);
    $pjax_url = url;
    replaceContent('#content', response);
    replaceContent('#footer', response);
    document.title = $.trim(response.match(/<title>(.+)<\/title>/)[1]);
    window.history.pushState(null, document.title, $pjax_url);
    addOffsets();
    pjax();
    loadImages();
    lightbox.bind();
    fixHeight();
    
  }

  var revealScroll = function() {
    
    $('.reveal.scroll').parents('.col .gutter').append(
    
      $('<div />').addClass('controls').append(
        $('<a />').attr('href', '#').attr('rel', 'prev').html('&lt;').click(function(event) {
    
          event.preventDefault();
          $(this).parents('.col .gutter').find('.scroll').stop(true, true).scrollTo('-=450', speed, { axis: 'y', easing: $.easing.def });
    
        })
    
      ).append(
    
        $('<a />').attr('href', '#').attr('rel', 'next').html('&gt;').click(function(event) {
    
          event.preventDefault();
          $(this).parents('.col .gutter').find('.scroll').stop(true, true).scrollTo('+=450', speed, { axis: 'y', easing: $.easing.def });
    
        })
    
      )
    );
    
  }
  
  var pager = {
    
    go: function(where) {
      
      if($('body').hasClass('ready')) {
       
        $('span[rel="'+where+'"]').eq(0).parents('a').eq(0).click();
        
      }
      
    }
    
  }
  
  var addOffsets = function() {
    
    $('.post').each(function() {
      $(this).prepend(
        $('<div class="offset" />').html('&nbsp;')
      )
    });
    
  }
  
  var isotopeRelayout = function() {
    
    $('#masonry').isotope('reLayout');
    
  }
  
  var keyboardNavigation = function() {
    
    addOffsets();
    
    $(window).bind('keydown', function(event) {
      
      if($('.post.active').length != 1) {
        
        $('.post').each(function() {

          if($(window)._scrollable().scrollTop() >= $(this).position().top && $(window)._scrollable().scrollTop() <= ($(this).position().top + $(this).height())) {
            $(this).addClass('active');
          }

        });
        
      }

      if(event.keyCode == 40 && !$('#lightbox').is(':visible')) {

        // Next

        event.preventDefault();
          
        if($('.post.active').next().length != 1) {
          pager.go('next');
        }

        if($('.post.active').next().find('.offset').length == 1) {
          $(window)._scrollable().stop(true, true).scrollTo($('.post.active').next().find('.offset'), speed, { axis: 'y', easing: $.easing.def });
          $('.post.active').next().addClass('active').siblings().removeClass('active');
        }
        
        if($('body.home').length == 1) {
          
          $(window)._scrollable().stop(true, true).scrollTo('+=' + (390 - ($(window)._scrollable().scrollTop() - 30) % 390), speed, { axis: 'y', easing: $.easing.def });
          
        }

      }
      
      if(event.keyCode == 38 && !$('#lightbox').is(':visible')) {

        // Previous
        
        event.preventDefault();
        
         if($('.post.active').prev().length != 1) {
           pager.go('prev');
         }

        if($('.post.active').prev().find('.offset').length == 1) {
          $(window)._scrollable().stop(true, true).scrollTo($('.post.active').prev().find('.offset'), speed, { axis: 'y', easing: $.easing.def });
          $('.post.active').prev().addClass('active').siblings().removeClass('active');
         }
         
         if($('body.home').length == 1) {
           
           if($(window)._scrollable().scrollTop() < 500) {
             
             $(window)._scrollable().stop(true, true).scrollTo(0, speed, { axis: 'y', easing: $.easing.def });
             
           } else {
             
             $(window)._scrollable().stop(true, true).scrollTo('-=' + (390 + ($(window)._scrollable().scrollTop() - 30) % 390), speed, { axis: 'y', easing: $.easing.def });
             
           }
           
           
           
         }
      
      }
      
      if(event.keyCode == 39) {
        if($('#lightbox').is(':visible')) {
          lightbox.go('next');
        } else {
          pager.go('next');
        }
      }
      if(event.keyCode == 37) {
        if($('#lightbox').is(':visible')) {
          lightbox.go('prev');
        } else {
          pager.go('prev');
        }
      }
      
      if(event.keyCode == 27) {
        if($('#lightbox').is(':visible')) { lightbox.close(); }
      }
      
    });
    
  }
  
  var layout = function() {
    
    $('#header .toggle .reveal').css('height', $(window).height() - 40);

    if(document.documentElement.scrollHeight <= document.documentElement.clientHeight) {
      $('#endgroup').css('bottom', 25).css('position', 'fixed');
    } else {
      $('#endgroup').css('bottom', 'auto').css('position', 'relative');
    }
    
  }
  
  var archives = function() {
    
    $('ul.archives').each(function() {
      
      var range = []
      
      range['min'] = parseInt($(this).data('range').split('-')[0]);
      range['max'] = parseInt($(this).data('range').split('-')[1]);
      
      $(this).find('li').each(function() {
        
        currentYear = parseInt(/([\d]{4})/.exec($(this).text())[0]);
        
        if(currentYear != range['min'] &&  currentYear != range['max']) {
          $(this).remove();
        }
        
      })
      
    });
    
  }
  
  var home = {
    
    bind: function() {
      
      home.masonry();
      
      $('#masonry li').each(function() {
        if($(this).find('img').length < 1) {
          $(this).addClass('no-images');
        }
      });
      
      $('a[rel="chrono"]').bind('click', function(event) {
        event.preventDefault();
        $('#masonry').isotope({
          sortBy: 'date',
          sortAscending: false
        });
        isotopeRelayout();
        $.cookie('tld-home-order', 'chrono');
        $(this).addClass('active');
        $('a[rel="alpha"]').removeClass('active');
      });
      
      $('a[rel="alpha"]').bind('click', function(event) {
        event.preventDefault();
        $('#masonry').isotope({
          sortBy: 'title',
          sortAscending: true
        });
        isotopeRelayout();
        $.cookie('tld-home-order', 'alpha');
        $(this).addClass('active');
        $('a[rel="chrono"]').removeClass('active');
      });
      
      $('a[rel="chaos"]').bind('click', function(event) {
        event.preventDefault();
        $('#masonry li').each(function() {
          
          if(Math.random() > 0.8) {
            $(this).removeClass('one').addClass('two');
          } else {
            $(this).removeClass('two').addClass('one');
          }
          
        });
        isotopeRelayout();
        $.cookie('tld-home-style', 'chaos');
        $(this).addClass('active');
        $('a[rel="order"]').removeClass('active');
      });
      
      $('a[rel="order"]').bind('click', function(event) {
        event.preventDefault();
        $('#masonry li').removeClass('two').addClass('one');
        isotopeRelayout();
        $.cookie('tld-home-style', 'order');
        $(this).addClass('active');
        $('a[rel="chaos"]').removeClass('active');
      });
      
      if($.cookie('tld-home-style')) {
        if($.cookie('tld-home-style') == 'order') {
          $('a[rel="order"]').eq(0).click();
        }
        if($.cookie('tld-home-style') == 'chaos') {
          $('a[rel="chaos"]').eq(0).click();
        }
      } else {
        // $('a[rel="order"]').eq(0).click();
        $('a[rel="chaos"]').eq(0).click();
      }
      
      if($.cookie('tld-home-order')) {
        if($.cookie('tld-home-order') == 'alpha') {
          $('a[rel="alpha"]').eq(0).click();
        }
        if($.cookie('tld-home-order') == 'chrono') {
          $('a[rel="chrono"]').eq(0).click();
        }
      } else {
        $('a[rel="chrono"]').eq(0).click();
      }
      
    },
    
    masonry: function() {
      
      $('#masonry').isotope({
        masonry: {
          columnWidth: 175,
        },
        itemSelector: '.brick',
        layoutMode: 'masonry',
        sortBy: 'date',
        sortAscending: false,
        getSortData: {
          title: function($el) {
            return $el.data('tag');
          },
          date: function($el) {
            return $el.data('date');
          }
        }
      })
      
    }
    
  }
  
  var lightbox = {

    bind: function() {
      
      $('#lightbox ul').empty();
      
      i=0;
      
      $('#content a img').each(function() {
        
        i+=1;
        
        if($(this).parents('a').first().attr('href').match(/\.jpg|\.gif|\.png|\.jpeg/)) {
          
          $href = $(this).parents('a').first().attr('href');
          
          $('<li />').data('src', $href).append(
            $('<img />').attr('src', '#')
          ).addClass('inactive').addClass('image-'+i).data('caption', $(this).parents('.post').find('h3').first().text()).appendTo('#lightbox ul');
          
          $(this).parents('a').first().data('image', i).bind('click', function(event) {
            event.preventDefault();
            dataI = $(this).data('image');
            lightbox.open($('#lightbox li.image-'+dataI));
          });
          
        }
        
      })
      
      $('#lightbox a[rel="next"], #lightbox a[rel="prev"]').click(function(event) {
        event.preventDefault();
        lightbox.go($(this).attr('rel'));
      })
      
      $('#lightbox a[rel="close"]').click(function() { lightbox.close(); });
      
      $('#lightbox li').first().addClass('active');
      
    },
    
    open: function(el) {
      
      $('#lightbox li').hide();

      $('body').css('overflow-y', 'hidden');
      
      $('#lightbox').fadeIn(speed, function() {
        
        lightbox.show(el);
        
      });
      
    },
    
    show: function(el) {
      
      $('#lightbox .loader').fadeIn('fast');
      
      $('#lightbox li.active').siblings().hide().removeClass('active').addClass('inactive').attr('src', '#');
      
      $('#lightbox .caption').text($(el).data('caption'));
      
      $('#lightbox li.active').fadeTo(speed, 0, function() {
        
        $(this).hide().removeClass('active').addClass('inactive').attr('src', '#');
        $(el).show().fadeTo(0, 0).find('img').attr('src', $(el).data('src'));
        
        if($(el).find('img')[0].complete || $(el).find('img')[0].readyState == 4) {
          
          $('#lightbox .loader').fadeOut('slow');

          $(el).find('img').parents('li').first().fadeTo(speed, 1).addClass('active').removeClass('inactive');
        
          lightbox.nextPrev();
          
        } else {
          
          $(el).find('img').load(function() {

            $('#lightbox .loader').fadeOut('slow');

            $(this).parents('li').first().fadeTo(speed, 1).addClass('active').removeClass('inactive');
          
            lightbox.nextPrev();

          });
          
        }
        
      });
      
    },
    
    nextPrev: function() {
      
      if($('#lightbox ul li.active').next().length != 1) {
        $('#lightbox a[rel="next"]').hide();
      } else {
        $('#lightbox a[rel="next"]').show();
      }
      if($target = $('#lightbox ul li.active').prev().length != 1) {
        $('#lightbox a[rel="prev"]').hide();
      } else {
        $('#lightbox a[rel="prev"]').show();
      }
      
    },
    
    go: function(where) {
      
      if($('#lightbox ul li').length > 1) {
       
        if(where == 'next') {
          if($('#lightbox ul li.active').next().length == 1) {
            $target = $('#lightbox ul li.active').next(); 
            lightbox.show($target);
          }

        }
        if(where == 'prev') {
          if($target = $('#lightbox ul li.active').prev().length == 1) {
            $target = $('#lightbox ul li.active').prev();
            lightbox.show($target);
          }     
        }
        
      }
      
    },
    
    close: function() {
      
      $('#lightbox').fadeOut(speed);
      
      $('body').css('overflow-y', 'auto');
      
    }
    
  }
  
  $('#search input').data('placeholder', $('#search input').attr('value')).focus(function() {
    
    if($(this).attr('value') == $(this).data('placeholder')) {
      $(this).attr('value', '');
    }
    
  }).blur(function() {
    
    if($(this).attr('value') == '') {
      $(this).attr('value', $(this).data('placeholder'));
    }
    
  });
  
  $(document).ajaxStart(function() {
    $('body').removeClass('ready');
    $('#search input').attr('value', 'Loading...');
  }).ajaxComplete(function() {
    setTimeout(function() {
      $('body').addClass('ready');
    }, 500);
    $('#search input').attr('value', 'Search');
  });
  
  var fixHeight = function() {
    
    $.fn.reverse = [].reverse;
    
    $('.post').each(function() {
      $(this).find('.post-text .gutter p').reverse().eq(1).css('margin-bottom', 45);
    });
    
  }
  
  textBreaks();
  
  revealScroll();
  keyboardNavigation();
  archives();
  if($.support.pjax) {
    pjax();
  }
  
  lightbox.bind();
  
  $(window).bind('resize', function() { layout(); });
  
  layout();
  fixHeight();
  
  if($('#masonry').length == 1) {
    home.bind();
  }
  
  setTimeout(function() { layout(); }, 500);
  
  setTimeout(function() { layout(); }, 1500);

});
