;if (undefined === window.DEV) window.DEV = false;
window.log = function(){
  log.history = log.history || [];
  log.history.push(arguments);
  arguments.callee = arguments.callee.caller;
  if (DEV && this.console) console.log(Array.prototype.slice.call(arguments));
};
/******************************************************************************/
/*
Firefox super responsive scroll (c) Keith Clark - MIT Licensed
*/
(function(doc) {

  var root = doc.documentElement;

  // Not ideal, but better than UA sniffing.
  if ("MozAppearance" in root.style) {

    // determine the vertical scrollbar width
    var scrollbarWidth = root.clientWidth;
    root.style.overflow = "scroll";
    scrollbarWidth -= root.clientWidth;
    root.style.overflow = "";

    // create a synthetic scroll event
    var scrollEvent = doc.createEvent("UIEvent")
    scrollEvent.initEvent("scroll", true, true);

    // event dispatcher
    function scrollHandler() {
      doc.dispatchEvent(scrollEvent)
    }

    // detect mouse events in the document scrollbar track
    doc.addEventListener("mousedown", function(e) {
      if (e.clientX > root.clientWidth - scrollbarWidth) {
        doc.addEventListener("mousemove", scrollHandler, false);
        doc.addEventListener("mouseup", function() {
          doc.removeEventListener("mouseup", arguments.callee, false);
          doc.removeEventListener("mousemove", scrollHandler, false);
        }, false)
      }
    }, false)

    // override mouse wheel behaviour.
    doc.addEventListener("DOMMouseScroll", function(e) {
      // Don't disable hot key behaviours
      if (!e.ctrlKey && !e.shiftKey) {
        root.scrollTop += e.detail * 16;
        scrollHandler.call(this, e);
        e.preventDefault()
      }
    }, false)

  }
})(document);
/* */

var getElmHeight = function(elm) {
    var mt = elm.css('marginTop') ? parseInt((elm.css('marginTop')).replace('px', '')) : 0;
    var bt = elm.css('borderTopWidth') ? parseInt((elm.css('borderTopWidth')).replace('px', '')) : 0;
    var pt = elm.css('paddingTop') ? parseInt((elm.css('paddingTop')).replace('px', '')) : 0;
    var eh = elm.height();
    var pb = elm.css('paddingBottom') ? parseInt((elm.css('paddingBottom')).replace('px', '')) : 0;
    var bb = elm.css('borderBottomWidth') ? parseInt((elm.css('borderBottomWidth')).replace('px', '')) : 0;
    var mb = elm.css('marginBottom') ? parseInt((elm.css('marginBottom')).replace('px', '')) : 0;

    var total = mt + bt + pt + eh + pb + bb + mb;
    return(total);
};


$(function() {
    var $window = $(window),
        windowHeight = $window.height(),

        sections = [],
        scaledImageHeight = imageHeight = 900,
        defaultSectionHeight,
        scrolldownHeight = getElmHeight($('#scrolldown'));

    log('boot');
    log(windowHeight, 'windowHeight');
    log(imageHeight, 'imageHeight');
    log(scaledImageHeight, 'scaledImageHeight');

    var bgPos = function(x, divHeight, scrollTop, offset, mul, reset) {
        var pos = (((divHeight - scaledImageHeight) / 2) + offset - scrollTop + ((scrollTop - offset) * (divHeight / scaledImageHeight)));
        return(reset ?
            x + '% 0' :
            x + '% ' + pos + 'px'
        );
    };

    var fitSectionsToWindow = function() {
        log('fitSectionsToWindow');
        log(windowHeight, 'windowHeight');
        log(defaultSectionHeight, 'defaultSectionHeight');

        if (windowHeight > defaultSectionHeight) {
            log('windowHeight > defaultSectionHeight');
//            scaledImageHeight = windowHeight + (imageHeight - defaultSectionHeight); // 200
            scaledImageHeight = Math.round(windowHeight * 1.2);
            $.each(sections, function(i, section) {
                var bgSize = 'auto ' + scaledImageHeight + 'px';
                section.section.css({
                    height: windowHeight + 'px',
                    '-webkit-background-size': bgSize,
                    '-moz-background-size': bgSize,
                    '-o-background-size': bgSize,
                    backgroundSize: bgSize
                });
                
                section.height  = windowHeight;
                section.top     = section.section.offset().top;
                section.acceleration = 1;
            });
        } else {
            log('windowHeight <= defaultSectionHeight');
            $.each(sections, function(i, section) {
                section.section.css({
                    height: defaultSectionHeight + 'px',
                    backgroundSize: 'auto ' + imageHeight + 'px'
                });
                section.height  = defaultSectionHeight;
                section.top     = section.section.offset().top;
                section.acceleration = (windowHeight < defaultSectionHeight) ? 1 - ((defaultSectionHeight - windowHeight) / windowHeight) : 1;
            });
        }
        log(sections, 'sections');
    };

    var setLastSectionToWindowHeight = function() {
        log('setLastSectionToWindowHeight');

        if (windowHeight < defaultSectionHeight) {
            log('windowHeight < defaultSectionHeight');
            var minSectionHeight = getElmHeight($('.content', sections[sections.length - 1].section));
            log(minSectionHeight, 'minSectionHeight');

            if (windowHeight < minSectionHeight) {
                sections[sections.length - 1].height = minSectionHeight;
            } else {
                sections[sections.length - 1].height = windowHeight;
            }
        } else {
            log('windowHeight >= defaultSectionHeight');
            sections[sections.length - 1].height = windowHeight;
        }
        sections[sections.length - 1].acceleration = (windowHeight < imageHeight) ? 1 - ((imageHeight - windowHeight) / windowHeight) : 0,
        sections[sections.length - 1].section.css({
            height: sections[sections.length - 1].height + 'px'
        });
    };

    var positionScrolldown = function() {
        $('#scrolldown').css({
            top: (windowHeight - Math.round(scrolldownHeight / 2)) + 'px'
        });
    };

    var fadeContent = function($elm, o) {
        var s = 800;
        if (o < s) {
            $elm.css({
                opacity: (s - o) / s
            });
        } else {
		$elm.css({
                opacity: 0.0
            });
        }
    };


    $window.scroll(function () {
        var scrollTop = $window.scrollTop();

        $.each(sections, function (i, section) {
            if ((scrollTop > (section.top + section.height)) || ((scrollTop + windowHeight) < section.top)) {
                section.inview = false;
            } else if (scrollTop < (section.top + section.height)) {
                section.inview = true;
            }

            if (section.inview) {
                var bgp = bgPos(50, section.height, scrollTop, section.top, section.acceleration, false);
				section.section.css({
                    backgroundPosition: bgp
                });
                if (i > 0) {
                    fadeContent(section.content, Math.abs(scrollTop - section.top));
                }
            }
        });
    });

    $window.resize(function() {
        windowHeight = $window.height();

        fitSectionsToWindow();
        positionScrolldown();
        setLastSectionToWindowHeight();

        $window.scroll();
    });

    $('a[rel=external]').live('click', function(event) {
        event.preventDefault();
        window.open($(this).attr('href'));
        $(this).blur();
    });

    $.localScroll();


    $.each($('.section'), function() {
        var $section = $(this);
        var sectionHeight = defaultSectionHeight = getElmHeight($section);
        sections[sections.length] = {
            section:    $section,
			duration:	10000,
            content:    $('.content:first', $section),
            height:     sectionHeight,
            top:        $section.offset().top,
            acceleration: (windowHeight < sectionHeight) ? 1 - ((sectionHeight - windowHeight) / windowHeight) : 1,
            inview:     false
        };
    });
    log(sections, 'sections');
    log(defaultSectionHeight, 'defaultSectionHeight');

    fitSectionsToWindow();
    positionScrolldown();
    setLastSectionToWindowHeight();

    $window.scroll();
});

