/* 
 *	Ghost Street http://www.ghoststreet.co.nz
 *	Copyright 2011
 *	Except the bits that aren't
 *
 */



var ScrollMenu = function (_menu, _section, _margin) {


    // 
    // PROPERTIES
    //

    // jQ binders
    var $m = $(_menu + " a"),
        $s = $(_section),
        $w = $(window);

    // List of menu items by ref name
    var menuItems = {};
    var scrollBezFn = $.bez([0.5, 0, 0.5, 1]);
    var currentActiveMenu = "";
    var offset = _margin || 0;

   


    // 
    // METHODS
    //

    function setActiveMenu (_name) {

        $m.removeClass('active');
        menuItems[_name].addClass('active');
        
        currentActiveMenu = _name;

    }

    function onScroll () { 
            
        var windowTop   = $w.scrollTop(),
            thisSection = "";

        $s.each(function () { 
            if (windowTop >= $(this).offset().top - offset) { thisSection = this.id; } 
        });

        if (thisSection !== currentActiveMenu) { setActiveMenu("#" + thisSection); }
    
    };




    // 
    // LISTENERS
    //

    // Bind to window scroll event
    $w.bind('scroll', onScroll);
   

    // Move content when nav clicked
    $("nav a").click(function () {

        var $this  = $(this),
            target = $this.data('scroll');

        // Dont flick thru menu active states while scrolling
        $w.unbind('scroll', onScroll);

        // Set active state manually instead
        setActiveMenu(target);

        // Move the content. Afterwards, re-endable menu active state detection
        $.scrollTo(
            
            "#" + $this.data('scroll'), 
            800, 
            { 
                offset  : -30, 
                easing  : scrollBezFn,
                onAfter : function () { $w.bind('scroll', onScroll); } 
            }
        );

    });



    //
    // INIT
    //

    // Compile list of menu items
    $m.each(function () { menuItems[$(this).data('scroll')] = $(this) });

    // Set to current element
    $w.trigger('scroll'); //setActiveMenu($m.first().data('scroll'));


    // 
    // EXPORT
    //

    return this;

}





$(function () {

    // Maintain correct window height
    padBottom('#contact');

    // Fancy scrolly menu
    var scrollMenu = new ScrollMenu("nav", "section", 30);

});




/*
 * Keep enough space at the bottom that the last 
 * content section can always scroll to the top.
 *
 * _lastSection - 
 *
 */

function padBottom (_lastSection) {

    var $w = $(window),
        $m = $("#main"),
        $c = $(_lastSection);

    function update () {

        var x = $w.height() - $c.outerHeight();

        // 90 = $m.paddingTop + $m.paddingBottom + scrollOffsetValue. (30 + 30 + 30)
        $m.css('padding-bottom', x - 90);   
        
    }

    // Bind to window resize
    $w.resize(update);

    // Trigger once
    update();

}




/*
 * Bez | (c) Robert Dallas Grey ARR | FreeBSD License | Credit to Nikolay Nemshilov
 *
 * http://github.com/rdallasgray/bez
 *
 */

jQuery.extend({ bez: function(coOrdArray) {
	var encodedFuncName = "bez_" + $.makeArray(arguments).join("_").replace(".", "p");
	if (typeof jQuery.easing[encodedFuncName] !== "function") {
		var	polyBez = function(p1, p2) {
			var A = [null, null], B = [null, null], C = [null, null],
				bezCoOrd = function(t, ax) {
					C[ax] = 3 * p1[ax], B[ax] = 3 * (p2[ax] - p1[ax]) - C[ax], A[ax] = 1 - C[ax] - B[ax];
					return t * (C[ax] + t * (B[ax] + t * A[ax]));
				},
				xDeriv = function(t) {
					return C[0] + t * (2 * B[0] + 3 * A[0] * t);
				},
				xForT = function(t) {
					var x = t, i = 0, z;
					while (++i < 14) {
						z = bezCoOrd(x, 0) - t;
						if (Math.abs(z) < 1e-3) break;
						x -= z / xDeriv(x);
					}
					return x;
				};
				return function(t) {
					return bezCoOrd(xForT(t), 1);
				}
		};
		jQuery.easing[encodedFuncName] = function(x, t, b, c, d) {
			return c * polyBez([coOrdArray[0], coOrdArray[1]], [coOrdArray[2], coOrdArray[3]])(t/d) + b;
		}
	}
	return encodedFuncName;
}});





/*
 * ImagesLoaded | Paul Irish | 2010 | MIT License | Credit to Oren Solomianik
 *
 */

jQuery.fn.imagesLoaded = function(callback){
  var elems = this.filter('img'),
      len   = elems.length,
      blank = "data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==";
      
  elems.bind('load.imgloaded',function(){
      if (--len <= 0 && this.src !== blank){ 
        elems.unbind('load.imgloaded');
        callback.call(elems,this); 
      }
  }).each(function(){
     // cached images don't fire load sometimes, so we reset src.
     if (this.complete || this.complete === undefined){
        var src = this.src;
        // webkit hack from http://groups.google.com/group/jquery-dev/browse_thread/thread/eee6ab7b2da50e1f
        // data uri bypasses webkit log warning (thx doug jones)
        this.src = blank;
        this.src = src;
     }  
  }); 

  return this;
};




/*
 * jQuery.ScrollTo 1.4.2 | (c) 2007-2009 Ariel Flesler | MIT + GPL
 *
 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
 *
 */

(function(d){var k=d.scrollTo=function(a,i,e){d(window).scrollTo(a,i,e)};k.defaults={axis:'xy',duration:parseFloat(d.fn.jquery)>=1.3?0:1};k.window=function(a){return d(window)._scrollable()};d.fn._scrollable=function(){return this.map(function(){var a=this,i=!a.nodeName||d.inArray(a.nodeName.toLowerCase(),['iframe','#document','html','body'])!=-1;if(!i)return a;var e=(a.contentWindow||a).document||a.ownerDocument||a;return d.browser.safari||e.compatMode=='BackCompat'?e.body:e.documentElement})};d.fn.scrollTo=function(n,j,b){if(typeof j=='object'){b=j;j=0}if(typeof b=='function')b={onAfter:b};if(n=='max')n=9e9;b=d.extend({},k.defaults,b);j=j||b.speed||b.duration;b.queue=b.queue&&b.axis.length>1;if(b.queue)j/=2;b.offset=p(b.offset);b.over=p(b.over);return this._scrollable().each(function(){var q=this,r=d(q),f=n,s,g={},u=r.is('html,body');switch(typeof f){case'number':case'string':if(/^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(f)){f=p(f);break}f=d(f,this);case'object':if(f.is||f.style)s=(f=d(f)).offset()}d.each(b.axis.split(''),function(a,i){var e=i=='x'?'Left':'Top',h=e.toLowerCase(),c='scroll'+e,l=q[c],m=k.max(q,i);if(s){g[c]=s[h]+(u?0:l-r.offset()[h]);if(b.margin){g[c]-=parseInt(f.css('margin'+e))||0;g[c]-=parseInt(f.css('border'+e+'Width'))||0}g[c]+=b.offset[h]||0;if(b.over[h])g[c]+=f[i=='x'?'width':'height']()*b.over[h]}else{var o=f[h];g[c]=o.slice&&o.slice(-1)=='%'?parseFloat(o)/100*m:o}if(/^\d+$/.test(g[c]))g[c]=g[c]<=0?0:Math.min(g[c],m);if(!a&&b.queue){if(l!=g[c])t(b.onAfterFirst);delete g[c]}});t(b.onAfter);function t(a){r.animate(g,j,b.easing,a&&function(){a.call(this,n,b)})}}).end()};k.max=function(a,i){var e=i=='x'?'Width':'Height',h='scroll'+e;if(!d(a).is('html,body'))return a[h]-d(a)[e.toLowerCase()]();var c='client'+e,l=a.ownerDocument.documentElement,m=a.ownerDocument.body;return Math.max(l[h],m[h])-Math.min(l[c],m[c])};function p(a){return typeof a=='object'?a:{top:a,left:a}}})(jQuery);


