

/*
 * jQuery history plugin
 * Copyright (c) 2006 Taku Sano (Mikage Sawatari)
 * Licensed under the MIT License:
 *   http://www.opensource.org/licenses/mit-license.php
 */

(function(b){function a(){this._curHash="";this._callback=function(c){}}b.extend(a.prototype,{init:function(d){this._callback=d;this._curHash=location.hash;if(b.browser.msie){if(this._curHash==""){this._curHash="#"}b("body").prepend('<iframe id="jQuery_history" style="display: none;"></iframe>');var c=b("#jQuery_history")[0].contentWindow.document;c.open();c.close();c.location.hash=this._curHash}else{if(b.browser.safari){this._historyBackStack=[];this._historyBackStack.length=history.length;this._historyForwardStack=[];this._isFirst=true;this._dontCheck=false}}this._callback(this._curHash.replace(/^#/,""));setInterval(this._check,100)},add:function(c){this._historyBackStack.push(c);this._historyForwardStack.length=0;this._isFirst=true},_check:function(){if(b.browser.msie){var c=b("#jQuery_history")[0];var f=c.contentDocument||c.contentWindow.document;var h=f.location.hash;if(h!=b.history._curHash){location.hash=h;b.history._curHash=h;b.history._callback(h.replace(/^#/,""))}}else{if(b.browser.safari){if(!b.history._dontCheck){var d=history.length-b.history._historyBackStack.length;if(d){b.history._isFirst=false;if(d<0){for(var e=0;e<Math.abs(d);e++){b.history._historyForwardStack.unshift(b.history._historyBackStack.pop())}}else{for(var e=0;e<d;e++){b.history._historyBackStack.push(b.history._historyForwardStack.shift())}}var g=b.history._historyBackStack[b.history._historyBackStack.length-1];if(g!=undefined){b.history._curHash=location.hash;b.history._callback(g)}}else{if(b.history._historyBackStack[b.history._historyBackStack.length-1]==undefined&&!b.history._isFirst){if(document.URL.indexOf("#")>=0){b.history._callback(document.URL.split("#")[1])}else{b.history._callback("")}b.history._isFirst=true}}}}else{var h=location.hash;if(h!=b.history._curHash){b.history._curHash=h;b.history._callback(h.replace(/^#/,""))}}}},load:function(f){var g;if(b.browser.safari){g=f}else{g="#"+f;location.hash=g}this._curHash=g;if(b.browser.msie){var c=b("#jQuery_history")[0];var e=c.contentWindow.document;e.open();e.close();e.location.hash=g;this._callback(f)}else{if(b.browser.safari){this._dontCheck=true;this.add(f);var d=function(){b.history._dontCheck=false};window.setTimeout(d,200);this._callback(f);location.hash=g}else{this._callback(f)}}}});b(document).ready(function(){b.history=new a()})})(jQuery);

/* Inspire-Results CUSTOM */

Array.prototype.indexOf = Array.prototype.indexOf || function(elt /*, from*/) {
    
    var len = this.length >>> 0,
        from = +arguments[1] || 0;
        
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
         
    if (from < 0) {
        from += len;
    }

    for ( ; from < len; from++ ) {
        if (from in this && this[from] === elt) {
            return from;
        }
    }
    
    return -1;

};

$(function(){
    
    function animatableWrapper(contentWrap, css) {
        /* Clone content area - create absolutely positioned element */
        return contentWrap.clone().css({position: 'absolute'}).css(css);
    }
    
    function wrapContent(context) {
        
        /* Wraps content into one element so it's easier to animate */
        
        var wrapper = $('<div/>').insertAfter(
            $('h1', context)
        )
        
        wrapper.append($('h1, #content, #side', context));
        
        return wrapper;
    
    }
    
    function imgDimensions(src, callback) {
        
        var img = $('<img/>').css({
                position: 'absolute',
                top: -9999,
                left: -9999,
                display: 'block'
            }).appendTo('body');
        
        img.load(function(){
            callback({
                height: img.height(),
                width: img.width()
            });
            img.remove();
        });
        
        img.attr('src', src/* + '?' + +new Date()*/);
    
    }
    
    
    /* Setup the blank filler (n:contentWrapper) */
    
    var contentWrapper, contentPosition, currentContent,
        body = $('body'),
        docEl = $(document.documentElement),
        navAnchors = $('#nav a'),
        order = 'inspire,team-results,individual-results,case-studies,about-us,get-in-touch,terms'.split(','),
        activeRequest = false,
        activeLoad = false,
        offToLeft = true,
        currentHash = 'index',
        initialLoad = true;
    
    contentWrapper = wrapContent(body);
    contentWrapper.css('overflow', 'hidden');
    contentWrapper.height(
        /* *Explicitely* set the height */
        contentWrapper.height()
    );
    
    contentPosition = {
        top: contentWrapper.offset().top,
        left: contentWrapper.offset().left,
        width: contentWrapper.width(),
        height: contentWrapper.height()
    };
    
    $(window).resize(function(){
        
        var left = contentWrapper.offset().left;
        
        if (currentContent) {
            currentContent.css('left', left);
        }
        
        contentPosition.left = left;
        
    });
    
    currentContent = animatableWrapper(contentWrapper, contentPosition).appendTo('body');
    
    contentWrapper.empty();
    contentWrapper.css('opacity', 0).css('background', 'url(img/loading.gif) center no-repeat');
    
    if ( !/\w/.test(window.location.hash) ) {
        window.location = '#index';
    }
    
    $.history.init( loadContent );
    
    function loadContent(hash) {
        
        /* If content is currently being loaded then abandon this
          and let it finish... */
        if (activeLoad) { return; }
        activeLoad = true;
        
        var anchor = navAnchors.filter(function(){
                return this.href.indexOf(hash + '.html') > -1;
            });
            
        navAnchors.removeClass('active');
        anchor.addClass('active');
        
        contentWrapper.animate({opacity:1});
        
        /* Hacky way of determining whether to exit to the left or right
         (this logic is only useful with links in the top navigation bar) */
        offToLeft = order.indexOf(hash) > order.indexOf(currentHash);
        
        if (initialLoad) {
            
            currentContent.remove();
            
        } else {
            
            currentContent.animate({
                left: offToLeft ? -currentContent.width() : $(window).width()
            }, {
                duration: 600,
                complete: function(){
                    $(this).remove();
                }
                
            });
            
        }
        
        $.ajax({
            url: hash + '.html',
            success: function(html) {
                
                contentWrapper.css({opacity:0});
                
                var tempDiv = $('<div/>').append(html.replace(/<script(.|\s)*?\/script>/g, '')),
                    newContent = animatableWrapper(wrapContent(tempDiv)),
                    newHash = html.match(/<body.+?section\-([A-Z\-]+)/i)[1],
                    newClass = 'section-' + newHash,
                    newID = 'page-' + newHash,
                    h1Title = $('h1', newContent),
                    animateCallback = function() {
                        
                        currentHash = hash;
                        
                        /* Animate main title up-from-border
                         - First we need to gain the natural-height of the
                           background image - images are asyncronously loaded
                           so we have to pass a callback
                      */
                        imgDimensions(h1Title.css('backgroundImage').match(/url\(['"]?(.+?)['"]?\)/)[1], function(dim){
                            $({pos:dim.height}).animate({pos: h1Title.height() - dim.height}, {
                                step: function() {
                                    h1Title[0].style.backgroundPosition = '0 ' + this.pos + 'px';
                                }
                            });
                            activeLoad = false;
                        });
                        
                        contentWrapper.css('opacity', 0)
                        document.documentElement.className = '';
                        activeRequest = false;
                        docEl.css('overflow', 'auto');
                        body.attr({
                            'class': newClass,
                            'id': newID
                        });
                        
                    };
                
                currentContent.attr('class', 'section-' + (currentHash==='index'?'inspire':currentHash));
                body[0].className = body[0].className.replace(/section[\-A-Z]+/i, '');
                
                docEl.css('overflow', 'hidden');
                
                newContent
                    /* Apply ID so BG-images changed properly */
                    .attr('class', newClass)
                    .css(contentPosition)
                    .css({
                        left: offToLeft ? $(window).width() : -contentPosition.width,
                        height: 'auto'
                    })
                    .appendTo(body);
                    
                contentWrapper.css({height:newContent.height()});
                
                /* Make h1 bg invisible - ready for animation */
                h1Title.css('backgroundPosition', '0 -999px');
                
                if (initialLoad) {
                    newContent.css({left: contentPosition.left});
                    animateCallback();
                } else {
                    newContent.animate({left: contentPosition.left}, {
                        duration: 600,
                        complete: animateCallback
                    });
                }
                
                currentContent = newContent;
                
            }
        });
        
        initialLoad = false;
        
    }
    
    $(document).bind('click', function(e){
        
        if (e.button === undefined || e.button !== 0) {
            return true;
        }
        
        var target = e.target,
            isAnchor = !!( target.nodeName.toLowerCase() === 'a' || $(target).parents('a')[0] ),
            href = isAnchor && (target.href || $(target).parents('a')[0].href),
            anchor;
            
        if (activeRequest) {
            e.preventDefault();
            return false;
        }
        
        if (isAnchor && RegExp('(' + order.join('|') + '|index)\.html$').test(href)) {
            
            e.preventDefault();
            anchor = $( $(target).closest('a')[0] || target );
            
            try {
                anchor.blur();
            } catch(e) {
                /* IE throws error, no blur() action */
            }
            
            activeRequest = true;
            
            navAnchors.removeClass('active').addClass('inactive');
            anchor.addClass('active');
            
            $.history.load( href.match(/([\-A-Z]+).html$/i)[1] );
            
        }
        
    });
    
    $('#nav a').hover(function(){
        $(this).stop().animate({paddingTop:10}, 100);
    }, function() {
        $(this).stop().animate({paddingTop:0}, 200);
    });
    
});
