$(document).ready(function(){
  $('.tooltip').hide();
  $('ul li').hide();
  var media = $(window).width();

  bindTooltips(media);

  $(window).resize(function() {
    media = $(window).width();
    bindTooltips(media);
  });

  $('header').hide().fadeIn(1000, function(){
    bindStack("#photo-stack li");
    $('#social li').each(function(){
      $(this).fadeIn(200);
    });
    stackPhotos($("#photo-stack li").get());
  });
});

bindTooltips = function(media){
  if (media > 770) {
    $('.tooltip').siblings('a').unbind().bind('mouseenter', function() {
      $(this).siblings('.tooltip').stop(true, true).fadeTo(200, 1);
    }).bind('mouseleave', function(){
      $(this).siblings('.tooltip').stop(true, true).fadeTo(200, 0);
    });
  }
  else {
    $('.tooltip').siblings('a').unbind();
  }  
};

stackPhotos = function(stack, index){
  if (!index) index = 0;
  var percentage = (100 - (stack.length - index -1)) / 100;
  var self = this;

  this.number = stack.length;
  this.distance = 3;

  if (index < stack.length) {
    $(stack[index]).css({'top': (index * self.distance * -1), 'left': 0, 'z-index': 100}).scale(percentage).fadeIn(200, function(){
      var t = setTimeout(function(){
        stackPhotos(stack, index+1);
      }, 400);
    });
  } 
};

bindStack = function(items) {
  $(items).click(function(e){
    var onTop = false;

    if( $(items).filter(':last').is(this) ) {
      onTop = true;
    }
    animateStack(this, onTop);
/*    e.preventDefault(); */
  });
};

animateStack = function(item, onTop) {
  var self = this;
  var topPosition = '+=0';
  var scalePercentage = '+=0';
  var moveTo = '0px';
  var position = $(item).closest('ul').find('li').last().position();
  var degrees = '=12deg';

  $(item).animate({rotate: '-'+degrees, left: '-170px'}, 200, function(){
    if (onTop) {
      var percentage = (100 - self.number + 1) / 100; 
      $(this).scale(percentage).closest('ul').prepend(this);
      topPosition = '-='+self.distance+'px';
      scalePercentage = '+=0.01';
      moveTo = '0px';
    }
    else {
      $(this).scale(1).closest('ul').append(this);
      topPosition = '+='+self.distance+'px';
      scalePercentage = '-=0.01';
      moveTo = position.top+'px';
    }
    var t = setTimeout(function(){ 
      $(item).animate({rotate: '+'+degrees, left: '0px', top: moveTo}, 200).siblings().each(function(){
        $(this).animate({scale: scalePercentage, top: topPosition}, 100);
      });
    }, 200); 
  }); 
};
