Modernizr.addTest("positionfixed", function()
{
    if (navigator.userAgent.match(/AppleWebKit\/(.*)Mobile\//)) return false;
    if (navigator.userAgent.match(/Android(.*)Mobile/)) return false;

    var test = document.createElement("div"),
        control = test.cloneNode(false),
        fake = false,
        root = document.body || (function()
        {
            fake = true;
            return document.documentElement.appendChild(document.createElement("body"));
        }());

    var oldCssText = root.style.cssText;
    root.style.cssText = "padding:0;margin:0";
    test.style.cssText = "position:fixed;top:42px";
    root.appendChild(test);
    root.appendChild(control);

    var ret = test.offsetTop !== control.offsetTop;

    root.removeChild(test);
    root.removeChild(control);
    root.style.cssText = oldCssText;

    if (fake) document.documentElement.removeChild(root);

    return ret;
});

$(document).ready(function()
{
    var current = "overview";
    var autoSelectActive = true;

    $.fn.startWebkitAnimation = function(name)
    {
        var element = $(this);
        if (!element.hasClass(name))
        {
            element.addClass(name);
        }
        else
        {
            element.css("-webkit-animation-name", "none");
            setTimeout(function() {
                element.css("-webkit-animation-name", name);
            }, 0);
        }
        return $(this);
    }

    $.fn.vAlign = function(offset)
    {
        if (offset == undefined) offset = 0;
        return this.each(function(i)
        {
            var diff = Math.abs($(this).height() + offset - $(this).parent().height()) / 2;
            if (diff > 0)
            {
                $(this).css("margin-top", diff);
            }
        });
    }

    $.isMobileSafari = function(){ return navigator.userAgent.match(/AppleWebKit\/(.*)Mobile\//); }

    $.getInternetExplorerVersion = function ()
    {
        var rv = -1,
            ua = navigator.userAgent,
            re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
        if (navigator.appName == 'Microsoft Internet Explorer')
        {
            if (re.exec(ua) != null) rv = parseFloat(RegExp.$1);
        }
        return rv;
    }

    var maxOpacity = 0.9,
        maxDashOpacity = 0.3,
        maxScroll = 125;

    $(window).bind("scroll resize", function(event)
    {
        var scrollTop = ($(document).scrollTop()),
            windowHeight = Math.round($(window).height()),
            percentScrolled = scrollTop/maxScroll,
            opacity = maxOpacity,
            dashOpacity = maxDashOpacity;

        if (!Modernizr.positionfixed || !Modernizr.rgba)
        {
        }
        else
        {
            if (scrollTop < maxScroll)
            {
                opacity = percentScrolled * maxOpacity;
                dashOpacity = percentScrolled * dashOpacity;
                $("header").css("background", "rgba(0,0,0," + opacity + ")")
                           .css("border-bottom", "1px dashed rgba(3,255,193," + dashOpacity + ")");
            }
            else
            {
                $("header").css("background", "rgba(0,0,0," + maxOpacity + ")")
                           .css("border-bottom", "1px dashed rgba(3,255,193," + maxDashOpacity + ")");
            }
        }

        if (autoSelectActive)
        {
            var nav = ["overview", "mobile-apps", "featured-work", "about-us"];
            var cur = nav[0];

            for (var k in nav)
            {
                var sec = nav[k];
                var name = "#" + sec;
                var top = $(name).offset().top;
                if (scrollTop + (windowHeight/2) - 50 > top) cur = sec;
            }

            if (current != cur)
            {
                current = cur;
                $("nav li").removeClass("active");
                $("#nav-" + current).addClass("active");
            }
        }
    });

    $.gotoPositionWithPath = function(path, animate)
    {
        var path = path.replace(/^\//, "");
        if (!path.length && $("body").hasClass("index")) path = "overview";

        var $target = $("#" + path),
            $navItem = $("#nav-" + path);
            scrollTop = $target.length ? $target.offset().top : 0,
            animate = (animate == undefined) ? true : animate;

        $("nav li").removeClass("active");
        $navItem.addClass("active");

        $.address.title("Typeoneerror - " + $navItem.find("a").attr("title"));

        if (animate)
        {
            autoSelectActive = false;
            $("body,html").stop().animate({scrollTop:scrollTop}, 750, 'swing', function()
            {
                autoSelectActive = true;
            });
        }
        else
        {
            $("body,html").scrollTop(scrollTop);
        }
    }

    var interval;

    if ($("body").hasClass("index"))
    {
        $.address.init(function(event) {
            $.gotoPositionWithPath(event.path, false);
        }).externalChange(function(event) {
            $.gotoPositionWithPath(event.path, false);
        }).internalChange(function(event) {
            $.gotoPositionWithPath(event.path, true);
        });

        $.address.crawlable(true);
        interval = setInterval(nextSlide, 7500);
    }
    else if ($('#work-grid').length)
    {
        var handler = function(event)
        {
            var path = event.path.replace(/^\//, "");
            if (path.length)
            {
                var category = 'work-category-' + path,
                    $links = $('#work-grid .sidebar a'),
                    li = '.item-' + category + ' a',
                    $tag = $('.project-tags ' + li);

                $links.removeClass('selected');
                $tag.addClass('selected')
                $.filterIsotope('.' + category);
            }
        }
        autoSelectActive = false;
        $.address.init(handler).change(handler);
    }
    else
    {
        autoSelectActive = false;
    }

    $("nav a").click(function(event)
    {
        var href = $(this).attr("href"),
            id = href.replace(/^\/#/, "");
        if (href.indexOf("#") != -1)
        {
            event.preventDefault();
            if ($("body").hasClass("index"))
            {
                _gaq.push(["_trackPageview", "/#!/" + id]);
                $.address.value(id);
            }
            else
            {
                window.location = "/#!/" + id;
            }
        }
    });

    $("a._blank").click(function(event)
    {
        event.preventDefault();
        window.open(this.href);
    });

    $("pre:not(.no-syntax)").addClass("prettyprint");

    $(".clicks a").click(function(event)
    {
        event.preventDefault();
        clearInterval(interval);
        var index = $(".clicks a").index(this);
        showFeatureAtIndex(index);
    });

    function showFeatureAtIndex(index)
    {
        var offsetX = -(index * 960);
        var offsetY = -(index * 45);

        $("#feature-container").stop().animate({left:offsetX}, 500);
        $("#feature-data-articles").stop().animate({top:offsetY});

        $(".clicks a").removeClass("active");
        $(".clicks a:eq(" + index + ")").addClass("active");
    }

    var direction = 0,
        position = 0,
        numSlides = $(".clicks a").length;

    function nextSlide()
    {
        if (!direction) position++;
        else position--;

        if (position >= numSlides - 1)
        {
            direction = 1;
        }
        else if (position == 0)
        {
            direction = 0;
        }

        showFeatureAtIndex(position);
    }

    $(window).blur(function(event)
    {
        clearInterval(interval);
    })

    $.filterIsotope = function(filter)
    {
        _gaq.push(["_trackPageview", "/#!/" + filter]);
        $iso.isotope({ filter:filter });
    }

    $('#work-grid .sidebar a').click(function(event){
        $("body,html").animate({scrollTop:125});
        event.preventDefault();
        var cat = $(this).attr('data-filter'),
            $links = $('#work-grid .sidebar a:not(.all)'),
            filter = "";
        if (cat == 'all')
        {
            $links.removeClass('selected');
        }
        else
        {
            $('#work-grid .sidebar a.all').removeClass('selected');
        }
        $(this).toggleClass('selected');
        $links.each(function(index){
            if ($(this).hasClass('selected'))
            {
                if (filter.length) filter += ", ";
                filter += $(this).attr('data-filter');
            }
        });
        if (filter == "") $('#work-grid .sidebar a.all').addClass('selected');
        $.filterIsotope(filter);
    })

});

