/* Henryboy parallax JavaScript */


String.prototype.rate = function() {
  return this.split(/,\s*/).map(function(s) {return parseFloat(s)})
}

String.prototype.pos = function() {
  return this.split(/,\s*/).map(function(s) {return s.split(/\s+/)})
}

$(document).ready(function() {
  var scrollHeight = 0
  function scrollSections() {
    scrollHeight = $(window).scrollTop()
    
    $('.parallax.inview, .inview .sprite').each(function() {
      var section = $(this)
      var style = section.hasClass('sprite') ? 'top' : 'backgroundPosition';
      adjustPosition(section, style)
    })
  }

  function adjustPosition(section, style) {
    var rate = section.attr('data-scroll-rate').rate()
    var init = section.data('initial')
    if (init == undefined) {
      init = section.css(style).pos()
      section.data('initial', init)
    }

    var ps = []
    for (var i = 0; i < init.length; i++) {
      if (init[i].length == 2) {
        var inity = parseInt(init[i][1])
        var initx = init[i][0]
      }
      else {
        inity = parseInt(init[i][0])
        initx = ''
      }
      var pos = scrollHeight * -rate[i] + inity
      ps.push(initx + ' ' + pos + 'px')
    }

    section.css(style, ps.join(','))
  }

  function markSectionInView(ev, inView) {
    if (inView) {
      $(this).addClass('inview')
    }
    else {
      // XXX this seems to happen too soon, better not use it
//      $(this).removeClass('inview')
    }
  }
  
  $(window).bind('scroll', scrollSections)
  $('.parallax, .sprite').bind('inview', markSectionInView)
});
