$(document).ready(function() {
   
   // Useful variables
   // ___________________________________________________

   var _c = 4,                 // The column width used throughout the document.
       _title = $('#title'),     // The title
       _footer = $('#footer'),   // The footer
       History = window.History, // Reference to History.js
       enableHistory = !$('#outer-container').hasClass('no-history'); // Whether to enable History.
   
   jQuery.easing.def = 'easeOutQuint';
   
   // Hide project preview boxes.
   $('.snapshot').addClass('invis1');
   
   // Save original element order into a new invisible div and Sort using TinySort
   // http://tinysort.sjeiti.com/
   $('.snapshot').each(function(_i) {
      $(this).prepend("<div class=\"projectCat invis1\">"+_i+"</div>");
   });
   
   $('#snapshot-container').delegate('.snapshot', 'mouseenter', function() {
      $( this ).find( "img" ).stop( true, true ).animate({
         opacity: 0.8
       }, 200);
   });
   
   $('#snapshot-container').delegate('.snapshot', 'mouseleave', function() {
      $( this ).find( "img" ).stop( true, true ).animate({
         opacity: 1
      }, 400 );
   });
   
   // Initial sorting.
   // To specify a sorting method, edit _shared.txt in your
   // /content directory and choose between "date", "shuffle"
   // and "category".
   var sortingMode = $('#snapshot-container').attr('sorting');
   $('.sort-option').removeClass('current');
   if (sortingMode == "date") {
      $('#sbd').addClass('current');
      $('.snapshot').tsort('.projectDate', {order:'desc'});
   } else if (sortingMode == "shuffle") {
      $('#sbr').addClass('current');
      $('.snapshot:not(#control)').tsort("",{order:"rand"});
   }  else {
      $('#sbc').addClass('current');
   }
   
   // Pack project thumbnails using Freetile
   $('#snapshot-container').freetile({
      elementClass: '.snapshot:not(.nosort)',
      animate : true,
      columnWidth : _c,
      elementDelay : 25,
      forceWidth : true,
      callbk : function() {
         $('.snapshot').each(function(i) {
            // Sequential fade in effect. Be aware: the display property is used here to enable animation
            // because the removeClass() alone won't animate display changes. But display should be
            // unset at the object level in the end to enable the object to show/hide (eg for filtering)
            var $this = $(this);
            setTimeout(function() {
               $this.fadeIn(360).removeClass('invis1').css('display','');
               if (i == $('.snapshot').length - 1) {
                  _footer.add('.goto-top').fadeIn(500);
               }
            }, 40*i );
            
         });         
      },
      animationOptions : {duration : 500}
   }).show();
   
   // Re-calculate the widths of the title, description and footer after a window resize.
   // Please note that the 20 pixels subtracted from the width is beacuse of the
   // preview boxes' margins, so that it looks aligned.
   var resizeContainer = function() {
      $('#outer-container').each(function() {
         var _w = $(window).width() - 40,
            snapWidth = $('.snapshot').outerWidth(true),
            _n = parseInt(_w/snapWidth);
            $(this).width(_n*snapWidth);
      });
   };
   
   $('#snapshot-container').imagesLoaded(function() {
      resizeContainer();
   });
   
   $(window).resize(function() {
      var $this = $(this);
      clearTimeout($this.data("rsz"));
      $this.data("rsz", setTimeout(function() {
         resizeContainer();
      }, 200) );
   });
   
   $('.sort-option').pngFix();
   
   //
   // Set up History API if desired and available.
   // __________________________________________________
   
   if (enableHistory && History.enabled) {
      // Prepare Initial State.
      History.replaceState({state: $('.page-content').html(), currentid: $('.faded').attr('id')}, document.title, "");
      
      // Setup snapshot clicking delegate.
      // Clicking on snapshot fetches content using ajax and pushes the new
      // state to history if it is supported.
      $('#snapshot-container').delegate('.snapshot', 'click', function(e) {
         // Variables
         var $this = $(this),
             link = $this.find('.snapshot-link').attr('href');
         
         // Prevent default event (following link)
         e.preventDefault();
         
         if (!$this.hasClass('faded')) {
            
            // Scroll to top
            $('html, body').animate({scrollTop : 0},300);
            
            // If the link is not empty
            if (link) {
               // Insert ajax loader and fade in.
               $('#ajax-loader').appendTo($this).fadeIn(260);
               
               // Get the new data and push history state.
               $.get(link, {}, function(data) {
                  var   innerData = $(data).find('.page-content').html(),
                        titleText = $(data).find('title').html();
                  History.pushState({state: innerData, currentid: $this.attr('id')}, titleText, link);
               });
            }
         }
      });
      
      // Setup title clicking delegate.
      $('#title-link').add('#about-image').click(function(e) {
         
         var link = $(this).attr('href');
         
         // Prevent default event (following link)
         e.preventDefault();
         
         // Scroll to top
         $('html, body').animate({scrollTop : 0 },300);       
         // Get the new data and push history state.
         $.get(link, {}, function(data) {
            var   innerData = $(data).find('.page-content').html();
                  //titleText = $(data).find('title').html();
            History.pushState({state: innerData, currentid: ''}, '', link);
         });
      });
      
      History.Adapter.bind(window, 'statechange', function() {
         var State = History.getState();
         updatePageData(State.data.state || "", State.title, State.data.currentid);
      });
   }
});

// Update page data and complete the transition.
var updatePageData = function(data, title, currentid, callback) {
   
   var h = 0,
       wrapper = $('#page-wrapper'),
       offset = wrapper.offset(),
       oldcontent = wrapper.find('.page-content'),
       newcontent = $('<div class="new-content" style="display: none;"></div>').append(data);
   
   
   newcontent.imagesLoaded(function() {
      
      // Set real height.
      wrapper.css({ height : wrapper.height() + 'px'});
      
      // Attach new data to document
      wrapper.append(newcontent);
      
      // Swap classes in new content
      newcontent.removeClass('new-content').addClass('page-content');
      
      // Show new content if it is not empty.
      // Also fade it if old content is not empty.
      if (newcontent.is(':not(:empty)')) {
         if (oldcontent.is(':not(:empty)')) {
            newcontent.fadeIn({
               delay : 200,
               easing : "linear"
            });
         } else {
            newcontent.show();
         }
      }
      
      // Apply style to old content
      oldcontent.css({position: 'absolute', left: '0px', top: '0px'});
      
      // Fade old content out and remove
      oldcontent.fadeOut({
         delay : 200,
         easing : "linear",
         complete: function() {
            $(this).remove();
            if (callback && callback.type == 'function') callback();
         }
      });
      
      // Get height of new div
      h = newcontent.outerHeight(true);
      if (h <= 30) h = 0;
      
      // Animate to new height.
      // Don't forget to re-set height to auto
      // after the animation completes.
      wrapper.animate({ height : h + 'px' }, 600, 'swing', function() {
         wrapper.css({ height : 'auto' });
      });

      
      // Change document title
      document.title = title;
      
      // Fade ajax loader out
      $('#ajax-loader').fadeOut(400);
         
      // Remove faded class from all snapshots
      $('.snapshot').removeClass('faded');
         
      // Fade current
      if ($('#' + currentid).length) $('#' + currentid).addClass('faded');
   });
}

// http://stackoverflow.com/questions/1251416/png-transparency-problems-in-ie8
$.fn.pngFix = function() {
  if (!$.browser.msie || $.browser.version >= 9) { return $(this); }

  return $(this).each(function() {
    var img = $(this),
        src = img.attr('src');

    img.attr('src', '/images/general/transparent.gif')
        .css('filter', "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled='true',sizingMethod='crop',src='" + src + "')");
  });
};

// Scrolling event for setting title properties.
/**$.fn.scrollEvent = function() {
   var $this = $(this),
       pagedummy = $this.find('.page-title-dummy'),
       dummytop = pagedummy.length ? pagedummy.offset().top : 0,
       dummyheight = pagedummy.outerHeight(true),
       pagetitle = $this.find('.page-title');
       scrollPos = $(window).scrollTop();

   if (scrollPos > $('#tags').offset().top) {
      pagetitle.addClass('page-title-fixed').css({
            top : 0
         });
   } else if (scrollPos > $('#tags').offset().top - dummyheight) {
      pagetitle.addClass('page-title-fixed').css({
            top : $('#page-wrapper').outerHeight(true) - dummyheight
         });
   } else if (scrollPos > dummytop) {
      pagetitle.addClass('page-title-fixed').css({
            top : scrollPos - dummytop
         });
   } else {
      pagetitle.removeClass('page-title-fixed').css({
            top : 0
         });
   }
}

// Replace the in-line title with a dummy div and set the title to
// a relative position
$.fn.titleReplace = function() {
   var $this = $(this),
       pagetitle = $this.find('.page-title');
   if (pagetitle.length && !$this.find('.page-title-dummy').length) {
      pagetitle.before($('<div class="page-title-dummy"></div>'));
      pagetitle.css({ position : 'absolute', left : '0px', top : '0px', width : '100%'});
      $this.find('.page-title-dummy').css({ height : pagetitle.outerHeight(true), width : '100%'});
   }
}*/
