function initScroll () {
  var h = 0;
  $('div.wrapper section').each(function(i) {
    $(this).css({
      position: 'absolute',
      top: h
      // minHeight: $(window).height()
      // zIndex: 1000+i
    }).data({
      originalTop: h
    });
    h += $(this).height();
  });
  
  $('div.wrapper').height(h);
}

function scrollStack(e) {
  $('div.wrapper section').each(function() {
    var wh = $(window).height(), wt = $(window).scrollTop(),
        th = $(this).height(), ot = $(this).data('originalTop');
    
    if (wh >= th) {
      if (wt > ot) {
        $(this).css({
          position: 'fixed',
          top: 0
        });
      } else {
        $(this).css({
          position: 'absolute',
          top: ot
        });
      }
    } else {
      if (wt > ot+(th-wh)) {
        // section is larger than viewport & section bottom is in window
        $(this).css({
          position: 'fixed',
          top: wh-th
        });
      } else {
        $(this).css({
          position: 'absolute',
          top: ot
        });
      }
    }
    
    if (wt >= ot) {
      $(this).find('.denza').not(':visible,:animated').fadeIn(600, 'easeInQuad');

      $('nav#main li').removeClass('here');
      $('#nav-'+$(this).attr('id')).addClass('here');
    } else {
      $(this).find('.denza:visible').not(':animated').fadeOut();
    }

  });
}

function sectionScroll(e) {
  if (this.nodeName == 'A') {
    var id = this.href.match(/#\/(\w+)/).pop();
  } else {
    var id = location.hash.replace(/^#\//, '');
  }
  
  $.scrollTo($('#'+id).data('originalTop'), { 
    axis:'y',
    duration:800,
    easing:'easeInOutQuad'
  });
}

function initSectionScroll() {
  if (window.location.hash != null && window.location.hash != '') {
    var id = window.location.hash.match(/#\/(\w+)/).pop();
    $.scrollTo($('#'+id).data('originalTop'), { 
      axis:'y',
      duration:800,
      easing:'easeInOutQuad'
    });
  }
}

function initMap () {
  var coords = new google.maps.LatLng(51.510372,-0.137190);
  var opts = {
    zoom:15,
    center: coords,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  var map = new google.maps.Map($('#googlemap')[0], opts);
  var marker = new google.maps.Marker({position:coords, map:map});
}

$(document).ready(function() {
  initScroll();
  initMap();
  initSectionScroll();
  
  $('a').filter(function() {
    return /#\//.test($(this).attr('href'));
  }).bind('click', sectionScroll);
  $(window).bind('scroll', scrollStack);
  
  $('a[rel="popup"]').click(function(e) {
    e.preventDefault();
    window.open(this.href, '_blank', 'height=600,width=650');
  });
  
  // position nav
  $('nav#main').css('left', ($(window).width() / 2) - (960/2));
});
