/* Author: Cubic */
jQuery(function() 
{ 
  $(document).ready(function() 
  {
    var windowWidth, windowHeight;
    var documentWidth, documentHeight;
    var usableWidth, usableHeight, usableRatio;
    var body, header, footer;
    var slideshowExists, slideshowReady = false;
    var slides, numSlides, currentSlide, slideshowTimer;
    
    // Init
    function init() {
      body = $('body');
      header = $('header');
      footer = $('footer');
      
      // Fire a resize event
      $(window).resize();
      convertEmailSpans();
      setUpSlideshow();
      doMasonry();
      viewProject();
      slideshow();
    };
    
    function slideshow()
    {
      if($('#slides').length > 0)
      {
        var slideshow = $('#slides');
        var slides = $('#slides figure');
        var width = 720;
        var height = 440;
        
        // Start slideshow plugin
        slideshow.slides({
          play: 6000,
          generatePagination: false,
          bigTarget: true
        });
        
        // Make slideshow resize when window resizes
        $(window).resize(function(e)
        {
          var newWidth = slideshow.width();
          var ratio = newWidth/width;
          var newHeight = height*ratio;
          if(newHeight > height) newHeight = height;
          
          slides.css('width', newWidth);
          slideshow.css('height', newHeight);
        });

        $(window).resize();
      };
    };
    
    // Full project view
    function viewProject() {
      
      // Check for article
      if($('article.full').length > 0)
      {
        // Get amount of images
        var numFigures = $('article.full figure').length;
        
        $('article.full:not(#slides) figure').mouseenter(function(e)
        {
          $(this).children('#scroll-arrow').fadeIn('fast');
        });
        
        $('article.full:not(#slides) figure').mouseleave(function(e)
        {
          $(this).children('#scroll-arrow').fadeOut();
        });
        
        // Scroll to next when clicked
        $('article.full:not(#slides, .no-scroll) figure').click(function(e)
        {
          var figure = $(this);
          
          // Work out position
          var pos = 0;
          if(figure.index() < numFigures-1) 
          {
            var pos = figure.next('figure').offset().top-10;
          };
          
          // Do scroll
          $('html, body').animate({scrollTop: pos}, 1000);
        });
        
        // When open-close [+] button is clicked
        $('article.full .open-close').click(function(e)
        {
          var overlay = $(this).parent().children('.overlay');
          if($(this).hasClass('open'))
          {
            $(this).removeClass('open');
            overlay.removeClass('open');
          }
          else
          {
            $(this).addClass('open');
            overlay.addClass('open');
          };
        });
        
        // Share or tags toggle click
        $('.share-content, .tags-content').each(function(e)
        {
          $(this).css('height', $(this).height()).hide();
        });
        $('article.full .share, article.full .tags').click(function(e)
        {
          // Get content
          var content = $(this).parent().parent().children('.share-content');
          if($(this).hasClass('tags')) content = $(this).parent().parent().children('.tags-content');
          
          // Show or hide
          if($(this).hasClass('active'))
          {
            $(this).removeClass('active');
            content.slideUp();
            content.removeClass('active');
          }
          else
          {
            $('.headings .active').removeClass('active');
            $('.share-content.active, .tags-content.active').removeClass('active').hide();
            $(this).addClass('active');
            content.slideDown();
            content.addClass('active');
          };
        });
      };
    };
    
    // Masonry
    function doMasonry() {
      
      // Check for content
      if($('#content').length > 0)
      {
        var container = $('#content');
        container.imagesLoaded(function(){
          container.masonry({
            itemSelector : 'article:not(.full)',
            isAnimated: !Modernizr.csstransitions
          });
        });
        
        $('#content article img').load(function(e)
        {
          if(!$(this).parent().parent().hasClass('slides_control'))
          {
            $(this).parent().children('figcaption').css('min-height', $(this).height());
          }
          else
          {
            $(this).parent().children('figcaption').css('min-height', 'auto');
          }
        });
        
        if((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/iPad/i))) 
        {
          $('#content article:not(.single) figure').click(function(e)
          {
            // Show overlay
            var overlay = $(this).children('figcaption.overlay');
            if( !overlay.hasClass('open') )
            {
              overlay.addClass('open');
            }
            else
            {
              // Link whole box
              var href = $(this).find('a').attr('href');
              window.location.href = href;
            }
          });
        }
        else
        {
          $('#content article .overlay').click(function(e)
          {
            // Only if it isn'y a single
            if(!$(this).parent().parent().hasClass('single')) 
            {
              // Link whole box
              var href = $(this).find('a').attr('href');
              window.location.href = href;
            };
          });
        
          $('#content article:not(.single) figure').mouseenter(function(e)
          {
            // Show overlay
            var overlay = $(this).children('figcaption.overlay');
            overlay.addClass('open');
          });
        }
          
        $('#content article:not(.single) figure').mouseleave(function(e)
        {
          // Hide overlay
          var overlay = $(this).children('figcaption.overlay');
          overlay.removeClass('open');
        });
        
      };
    };
    
    // dewisott
    function convertEmailSpans() 
    {
      $('.emli').each(function() 
      {
        var content = $(this).html();
        var link = content;
        link = link.replace(/ dot /gi, '.');
        link = link.replace(/ at /gi, '@' );
        var a = '<a href="mailto:'+link+'">'+link+'</a>';
        $(this).after(a);
        $(this).remove();
      });
    };
    
    function setUpSlideshow()
    {
      // Check for a slideshow
      if($('#slideshow').length > 0) 
      {
        slideshowExists = true;
        slides = $('#slideshow figure');
        numSlides = slides.length;
        
        // Get first img
        var firstImg = $('#slideshow figure.active img');
        var fiSrc = $('#slideshow figure.active img').attr('src');
        firstImg.parent().hide();
        firstImg.attr('src', '#');
        
        firstImg.load(function(e)
        {          
          // FadeIn
          $(this).parent().fadeIn();
          var color = $(this).parent().attr('data-color');
          setPageColor(color);
          
          slideshowReady = true;
          
          if(numSlides > 1)
          {
            // Start timer
            slideshowTimer = setTimeout(nextImage, 10000);
          };
          
          // Fire another resize event
          $(window).resize();
        });
          
        // Listen for the first img to load
        setTimeout(function(e){ firstImg.attr('src', fiSrc); }, 300);
      };
    };
    
    // Slideshow to next image
    function nextImage()
    {
      clearTimeout(slideshowTimer);
      
      // Get currently showing slide
      currentSlide = $('#slideshow figure.active');
      
      // Get next slide to show
      var nextSlide = currentSlide.index()+1;
      if(currentSlide.index() == numSlides-1) nextSlide = 0;
      nextSlide = $(slides[nextSlide]);
      
      // Set up z-indexes
      currentSlide.removeClass('active').css('z-index', 9);
      nextSlide.addClass('active').css('z-index', 10);
      
      // Fade in new
      nextSlide.fadeIn(function() 
      { 
        currentSlide.hide();
        
        var color = $(this).attr('data-color');
        setPageColor(color);
        
      });
      
      // Fire another resize event
      $(window).resize();
      
      // Reset timer
      slideshowTimer = setTimeout(nextImage, 7000);
    };
    
    // Handle switching the page colour
    function setPageColor(color) {
      
      if(color == 'dark') 
      {
        $('body').addClass('dark');
        $('body').removeClass('light');
      }
      else if(color == 'light') 
      {
        $('body').addClass('light');
        $('body').removeClass('dark');
      };
    };
    
    // Listen for window resize
    $(window).resize(function(e)
    {
      // Get measurements
      windowWidth     = $(this).width();
      windowHeight    = $(this).height();
      documentWidth   = $(this).width();
      documentHeight  = $(this).height();
      
      // Resize document to correct height
      if(documentHeight > 580) {
        body.css('min-height', documentHeight-30);
        footer.removeClass('static').addClass('fixed');
      } 
      else
      { 
        body.css('min-height', 580);
        documentHeight = 580;
      };
      
      // Work out which dimensions to use
      usableWidth     = (documentWidth > windowWidth) ? documentWidth : windowWidth;
      usableHeight    = (documentHeight > windowHeight) ? documentHeight : windowHeight;
      usableRatio     = usableWidth / usableHeight;
      
      // If there is a slideshow then scale the currently active slide
      if(slideshowExists) 
      {
        // Set the slideshow container to the exact window size
        $('#slideshow').width(windowWidth).height(windowHeight);
        $('#slideshow figure.active').each(function(e)
        {
          // Get img 
          var img = $(this).children('img');
          
          // Calculate img ratio
          var imgHeight = img.height();
          var imgWidth  = img.width();
          var imgRatio  = imgWidth / imgHeight;
          
          // Scale img
          if(imgRatio < usableRatio){ // Width less than height
            img.css({ width: (usableWidth+20), height: (usableWidth+20) * (1/imgRatio) });
          } else if(imgRatio >= usableRatio){ // Height less than width
            img.css({ width: (usableHeight+20) * imgRatio, height: (usableHeight+20) });
          };
          
          // Re-calculate sizes to enable centering
          imgHeight = img.height();
          imgWidth  = img.width();
          
          // Center img
          var offsetLeft = (usableWidth-imgWidth)*0.5;
          var offsetTop  = (usableHeight-imgHeight)*0.5;
          if(offsetLeft < 0) img.css('left', offsetLeft);
          if(offsetTop < 0) img.css('top', offsetTop);
        
        });
      };
      
      // Resize overlay if neccessary 
      $('figcaption.overlay').each(function(e)
      {
        $(this).css('min-height', $(this).parent().children('img').height());
      });
    });
    
    // Init
    init();
  });
});
