$(document).ready(function(){
  // Menu Distribution
  var totalWidth = 700;
  var aTotalWidth = 0;
  var elementCount = 0;
  var fromHome = false;
  var ref = document.referrer;
  if (ref == 'http://www.bendinglight.org/' || ref == 'http://www.bendinglight.org/home') {
    fromHome = true;
  }
  
  $("#menu a").each(function(){
    var aCurWidth = $(this).width();
    aTotalWidth = aTotalWidth + aCurWidth;
    elementCount ++;
  });
 

  

  var newMargin = (totalWidth - aTotalWidth) / (elementCount - 1)
  
  $("#menu a").css('margin-right', newMargin+'px');
  
  // Vortex Initialization
  var active = $("#menu div.active a:first");

  var activePos = active.position();

  if (activePos) {
    var activeLeft = activePos.left;    
    var activeWidth = active.width();   
    var activeGoal = activeLeft - 40 + activeWidth / 2;
    $('#vortex').css('left', activeGoal);
  } else {
    activeGoal = -150;
  }

  // Menu Hover -> Vortex Move
  var menuHover = false;
  $("#menu").hover(function(){

  },function(){
    $('#vortex').stop(true, false);
    $('#vortex').animate({
      left: activeGoal,
    }, 500, 'easeOutSine', function() {
      //animation done
    });
  })
  $("#menu a").hover(function() {
    $('#vortex').stop(true, false);
    var curPos = $(this).position();
    var curLeft = curPos.left;
    var curWidth = $(this).width();
    var curGoal = curLeft - 40 + curWidth / 2;
    $('#vortex').animate({
      left: curGoal,
    }, 500, 'easeOutSine', function() {
      //animation done
    });
  },function() {
    
  });
  
  // Head Movement
  
  if (fromHome) {
    $('#menu').css('bottom','-5px');
    $('#head').css('top','-40px');
    $('#head').animate({
      top: -100,
    }, 1000, 'easeOutSine', function() {
      //animation done
    });
    $('#menu').animate({
      bottom: -15,
    }, 1000, 'easeOutSine', function() {
      //animation done
    });
  } else {
    $("#trigger").hover(function() {
      $('#head').stop(true, false); 
      $('#menu').stop(true, false);
      $('#head').animate({
        top: -40,
      }, 500, 'easeOutSine', function() {
        //animation done
      });
      $('#menu').animate({
        bottom: -3,
      }, 500, 'easeOutSine', function() {
        //animation done
      });
    },function() { 
      $('#head').stop(true, false);
      $('#menu').stop(true, false);
      $('#head').animate({
        top: -100,
      }, 500, 'easeOutSine', function() {
        //animation done
      });
      $('#menu').animate({
        bottom: -15,
      }, 500, 'easeOutSine', function() {
        //animation done
      });
    }); 
  }
});
