/* Author: Kalley

*/
Modernizr.addTest("boxsizing",function(){
    return Modernizr.testAllProps("boxSizing");
});
var root = $(document).bind('ready', function() {
        var mainNav = $('#main-nav'),
            contentDiv = $('#content'),
            contentDivPos = contentDiv.position(),
            transitionDiv = $('<div>', {
                css: {
                    left: contentDivPos.left-10,
                    top: contentDivPos.top-parseInt(contentDiv.css('padding-top'))
                },
                height: contentDiv.outerHeight(),
                html: '<div>',
                id: 'transition-overlay',
                width: contentDiv.outerWidth()
            }),
            requestAnimationFrame = window.webkitRequestAnimationFrame ||
                window.mozRequestAnimationFrame ||
                window.oRequestAnimationFrame,
            transition = {
                duration: requestAnimationFrame ? 200 : 400,
                interval: null,
                reset: function() {
                    $('#main').removeClass('changing');
                    transitionDiv.css('background-image', '').detach();
                    clearInterval(transition.interval);
                    transition.interval = null;
                },
                start: function(inbetween) {
                    transition.reset();
                    $('#main').addClass('changing').append(transitionDiv);
                    var pct = 0, opacity = 0, oStart, oState, raf, startTime = $.now(), t = function() {
                        var now = $.now(), state = (now-startTime)/transition.duration;
                        pct = ((100*state)+(70*state)) > 100 ? 100 : ((100*state)+(63*state));
                        transitionDiv.css('background-image', 'linear-gradient(right top, #fff, rgba(255,255,255,0) '+pct+'%)')
                            .css('-pie-background-image', 'linear-gradient(right top, #fff, rgba(255,255,255,0) '+pct+'%)');
                        if(state > .7) {
                            if( ! oStart) {
                                oStart = $.now();
                            }
                            oState = (now-oStart)/(transition.duration-(oStart-startTime));
                            opacity = oState > 1 ? 1 : oState;
                            transitionDiv.css('background-image', 'linear-gradient(right top, #fff, rgba(255,255,255,'+opacity+') 100%)')
                                .css('-pie-background-image', 'linear-gradient(right top, #fff, rgba(255,255,255,'+opacity+') 100%)');
                            if(state > 1) {
                                clearInterval(transition.interval);
                                transition.interval = null;
                                inbetween && inbetween();
                                transition.end();
                            }
                        }
                    };
                    if(requestAnimationFrame) {
                        transition.interval = 1;
                        raf = function() {
                                if ( transition.interval ) {
                                        requestAnimationFrame( raf );
                                        t();
                                }
                        };
                        requestAnimationFrame( raf );
                    } else {
                        transition.interval = setInterval(function() {
                            t();
                        }, 13);
                    }
                },
                end: function() {
                    var pct = 0, opacity = 1, raf, startTime = $.now(), pStart, pState, t = function() {
                        var now = $.now(), state = (now-startTime)/transition.duration;
                        opacity = 1 - state*4 < 0 ? 0 : 1-state*4;
                        transitionDiv.css('background-image', 'linear-gradient(right top, rgba(255,255,255,'+opacity+') 0, #fff)')
                            .css('-pie-background-image', 'linear-gradient(right top, rgba(255,255,255,'+opacity+') 0, #fff)');
                        if(state > .2) {
                            if( ! pStart) {
                                pStart = $.now();
                            }
                            pState = (now-pStart)/(transition.duration-(pStart-startTime));
                            pct = ((100*pState)+(70*pState)) > 100 ? 100 : ((100*pState)+(63*pState));
                            transitionDiv.css('background-image', 'linear-gradient(right top, rgba(255,255,255,0) '+pct+'%, #fff)')
                                .css('-pie-background-image', 'linear-gradient(right top, rgba(255,255,255,0) '+pct+'%, #fff)');
                            if(state > 1) {
                                transition.reset();
                            }
                        }
                    };
                    transitionDiv.addClass('end').removeClass('start middle');
                    if(requestAnimationFrame) {
                        transition.interval = 1;
                        raf = function() {
                            if( transition.interval ) {
                                requestAnimationFrame( raf );
                                t();
                            }
                        }
                        requestAnimationFrame( raf );
                    } else {
                        transition.interval = setInterval(function() {
                            t();
                        }, 13);
                    }
                }
            };
        var states = {}, clicked = true, currentURL = window.location.pathname,
            callbacks = {
                mainNav: function(data) {
                    transition.start(function() {
                        mainNav.find('a.active').removeClass('active');
                        mainNav.find('a[href$="'+window.location.pathname+'"]').addClass('active');
                        contentDiv.html(innerShiv(data.content, false)).attr('class', data.className)
                            .filter('.home').find('h2:not(".filtered")').lettering('lines');
                        });
                },
                serviceNav: function(data) {
                    var content = $(innerShiv(data.content, false));
                    var length = content.length;
                    $('#content.services nav').find('a.active').removeClass('active').end()
                        .find('a[href$="'+window.location.pathname+'"]').addClass('active');
                    $('#service-content').wrapInner('<div class=fade-out>').prepend(
                            $(content[length-1]).wrapInner('<div class=fade-in>').children().css('opacity', 0)
                        ).children().each(function() {
                            var div = $(this), fadeIn = div.is('.fade-in');
                            div.fadeTo(500, fadeIn, function() {
                                fadeIn ? div.replaceWith(div.children()) : div.remove();
                            });
                        });
                }
            };
        setTimeout(function() {clicked = false;}, 13);
        $.pathchange.init({
            interceptLinks: false
        });
        /* */
        $(window).bind('pathchange', function(e) {
            if( ! clicked) {
                updateURL(function(content) {
                    if(currentURL.match('services') && window.location.pathname.match('services')) {
                        callbacks.serviceNav(content);
                    } else {
                        callbacks.mainNav(content);
                    }
                });
            }
            clicked = false;
        });
        /* */
        contentDiv.filter('.home').find('h2').lettering('lines').addClass('filtered');
        $.storage(window.location.pathname, {
            title: document.title,
            content: contentDiv.html(),
            className: contentDiv.attr('class').replace('clearfix', '')
        })
        function updateURL(callback) {
            var state = $.storage(window.location.pathname);
            if( ! state) {
                $.ajax({
                    data: {format: 'json'},
                    dataType: 'json',
                    success: function(data) {
                        doAlways(data, state, callback);
                    },
                    url: window.location
                });
            } else {
                doAlways(state, state, callback);
            }
            clicked = false;
            function doAlways(data, state, callback) {
                ! state && $.storage(window.location.pathname, data);
                states[window.location] = $.storage(window.location.pathname);
                document.title = data.title;
                callback(data);
                // Inform Google Analytics of the change
                if ( typeof _gaq !== 'undefined' ) {
                    _gaq.push(['_trackPageview', window.location.pathname]);
                }
                currentURL = window.location.pathname;
            }
        }
        mainNav.find('a').bind('click', function(ev) {
            if( ! Modernizr.history) return true;
            clicked = true;
            $.pathchange.changeTo($(this).attr('href'));
            updateURL(callbacks.mainNav);
            ev.preventDefault();
        });
        $('#logo').bind('click', function(ev) {
            if( ! Modernizr.history) return true;
            clicked = true;
            $.pathchange.changeTo($(this).attr('href'));
            updateURL(callbacks.mainNav);
            ev.preventDefault();
        });
        root.delegate('#content.services nav a:not(.serv-a-hover)', 'click mouseenter mouseleave', function(ev) {
            var link = $(this), w = link.width();
            if(ev.type == 'click') {
                if( ! Modernizr.history) return true;
                clicked = true;
                link.siblings().remove();
                $.pathchange.changeTo($(this).attr('href'));
                updateURL(callbacks.serviceNav);
                ev.preventDefault();
            } else {
                if( ! link.is('.active') && ! Modernizr.touch) {
                    if(ev.type == 'mouseenter') {
                        link.siblings().remove();
                        link.clone(false).css({
                            opacity: 0,
                            right: w/2
                        }).wrapInner('<span>').prependTo(this.parentNode).addClass('serv-a-hover active').animate({
                            opacity: 1,
                            right: 0,
                            width: w
                        }, 200);
                    } else {
                        link.siblings().animate({
                            opacity: 0,
                            right: w/2,
                            width: 0
                        }, 200, function() {
                            link.siblings().remove();
                        });
                    }
                }
            }
        });
});























