$.fn.splitList = function(n, options){
    settings = $.extend({
        wrapClass: false,
        splitInto: 'cols'
    }, options);
    return this.each(function(){
        var intoCols = (settings['splitInto'] == 'cols');
        $lis = jQuery(this).find("> li");       
        $inc = intoCols ? parseInt(($lis.length/n) + ($lis.length % n > 0 )) : n;
        var w = '<div' + (settings['wrapClass'] ? ' class="' + settings['wrapClass'] + '"' : '' ) + '></div>';
        for(var i=0; i<(intoCols ? n : Math.ceil($lis.length/n)); i++)
            $lis.slice($inc*i, $inc*(i+1)).wrapAll(w);
    });
};


// Used for animation easing
jQuery.extend(jQuery.easing, {
    easeInQuad: function (x, t, b, c, d) {
        return c*(t/=d)*t + b;
    },
    easeOutQuad: function (x, t, b, c, d) {
        return -c *(t/=d)*(t-2) + b;
    },
    easeInOutQuad: function (x, t, b, c, d) {
        if ((t/=d/2) < 1) return c/2*t*t + b;
        return -c/2 * ((--t)*(t-2) - 1) + b;
    }
});

function speed(n){
    return ($.browser.msie) ? 0 : n;
}


$(document).ready(function(){
    
    var oldGecko = (parseFloat($.browser.version) < 1.9) && $.browser.mozilla;
    
    if($.browser.msie || oldGecko){
        $.fx.off = true;
    }
    
    // Tests for browser support
    var support = (function(){
        var b = document.body;
        var p = '-moz- -ms- -webkit- -o-'.split(' ');
        var r = {};
        var addClass = function(c){
            b.className = (!b.className) ? c : b.className + ' ' + c;
        };
        var tests = {
            'displayTable': function(){
                // Tests for support of the CSS display: table properties
                var e = document.createElement('div');
                
                if(e && b){ 
                    try{
                        e.style.display = 'table-cell';
                        return (e.style.display == 'table-cell') && (($.browser.webkit) ? (parseInt($.browser.version) >= 526) : true);
                    }catch(err){
                        return false;
                    }
                }
                return false;
            }
        }
        for(var i in tests){
            var t = tests[i]();
            addClass(((t) ? 'has-' : 'no-') + i);
            r[i] = t;
        }
        return r;
    })();
    
    // Very unscientific method of checking for common mobile UserAgents.
    // This should only be used to gracefully degrade the mobile experience,
    // NOT to provide mobile-specific enhancements.
    var mobile = (function(){
        var uas = ['webOS', 'Mobile Safari', 'iPhone', 'Android', 'AppleWebKit'];
        if((screen.width < 640) || (screen.height < 640)){
            for(ua in uas){
                if(navigator.userAgent.match(ua)) return true;
            }
        }
        return false;
    }());
    
    
    // Twitter viewer toggle
    var twitter = (mobile) ? { 
        'init': function(){ 
            return;
        } 
    } : {
        'container': $('#twitter').eq(0).addClass('activated'),
        'toggle': $('<a href="#" id="toggle">Toggle</a>').appendTo('#twitter'),
        'first': $('#twitter li:first-child'),
        'notFirst': $('#twitter li:not(:first-child)'),
        'allTweets': $('#twitter li'),
        'speed': speed(250),
        'open': false,
        'openHeight': false,
        'closedheight': false,
        'hide': function(speed){
        
            // Collapse the Twitter viewer
            twitter.allTweets.animate({'opacity': 0}, twitter.speed, function(){
                twitter.container.animate({
                    'height': twitter.closedHeight
                }, twitter.speed, 'easeInOutQuad', function(){
                    twitter.notFirst.hide();
                    twitter.first.animate({'opacity': 1}, twitter.speed);
                    twitter.open = false;
                }).removeClass('open');
            });
            if($.browser.msie) $(twitter.allTweets).css('filter', false);

        },
        'show': function(speed){
        
            // Expand the Twitter viewer
            twitter.first.animate({'opacity': 0}, speed, function(){
                twitter.container.animate({'height': twitter.openHeight}, speed, 'easeInOutQuad', function(){
                    twitter.allTweets.show().css('opacity',0).animate({'opacity': 1}, speed);
                    twitter.open = true;
                    if($.browser.msie) $(twitter.allTweets).css('filter', false);
                }).addClass('open');
            });
        
        },
        'init': function(){
        
            // Initialize the Twitter viewer
            if(twitter.container.length > 0){
                twitter.openHeight = this.container.height();
                twitter.notFirst.hide();
                twitter.closedHeight = this.container.height();
                twitter.toggle.click(function(event){
                    event.preventDefault();
                    if(twitter.open) twitter.hide(twitter.speed);
                    else twitter.show(twitter.speed);
                })
            }
        
        }
    }


    // Case study listing toggle
    var caseStudies = {
        'open': false,
        'speed': speed(300),
        'buttonText': {
            'open': 'Close',
            'closed': 'Selected Work'
        },
        'list': $('#selected-works ul').eq(0).splitList(4, { 'wrapClass': 'col' }).hide(),
        'listHeight': $('#selected-works ul').eq(0).height(),
        'button': $('#selected-works h3 a').eq(0),
        'init': function(blocks){

            // Initialize list of case studies
            if($('body').attr('id') == 'case-study'){
                this.list.css({
                    'height': 0,
                    'opacity': 0
                });
                this.button.click(function(e){
                    e.preventDefault();
                    if(caseStudies.open){
                    
                        // Open the list
                        caseStudies.list.show().stop().animate({
                            'height': 0,
                            'opacity': 0
                        }, caseStudies.speed, 'easeInOutQuad', function(){
                            $(this).hide()
                        });
                        caseStudies.button.removeClass('open').text(caseStudies.buttonText.closed);
                        caseStudies.open = false;
                    
                    }else{
                    
                        // Close the list
                        caseStudies.list.show().stop().animate({
                            'height': caseStudies.listHeight,
                            'opacity': 1
                        }, caseStudies.speed, 'easeInOutQuad');
                        caseStudies.button.addClass('open').text(caseStudies.buttonText.open);
                        caseStudies.open = true;
                    
                    }
                });
            }
    
        }
    }


    // Case study screenshot slideshow
    var slideshow = {
        'container': $('#content'),
        'slides': [],
        'slideContainer': $('<div id="slideshow"><h3>Screenshots</h3></div>').hide().appendTo('#content'),
        'slideClose': $('<a href="#" id="slide-close">Close</a>').appendTo($('#slideshow')),
        'slidePrev': $('<div id="slide-prev"><a href="#">Previous</a></div>').appendTo($('#slideshow')),
        'slideNext': $('<div id="slide-next"><a href="#">Next</a></div>').appendTo($('#slideshow')),
        'slideList': $('<ul id="slides"></ul>').appendTo($('#slideshow')),
        'currentSlide': -1,
        'firstSlide': 0,
        'lastSlide': 0,
        'nonSlide': $('#content > :not(#masthead, #slideshow), #masthead > :not(h2)'),
        'speed': speed(350),
        'visible': false,
        'emptyEvent': function(e){
            e.preventDefault();
        },
        'stick': {
            'upperBound': 547,
            'offset': false,
            'listener': false,
            'check': function(){
            
                if($.browser.mozilla){
            
                    // Adjust the scroll-sensitive values
                    slideshow.stick.lowerBound = $(document).height()-350;
                    slideshow.stick.offset = slideshow.stick.listener.offset().top;
                
                    // Calculate the window midpoint
                    var mid = ($(window).height() - parseInt($(slideshow.stick.elems[0]).find('a').css('height')))/2;
                
                    if(slideshow.stick.offset + mid > slideshow.stick.upperBound){
                    
                        // Stick the prev/next buttons
                        $('#slide-prev').addClass('fixed').css({
                            'left': slideshow.slideContainer.offset().left,
                            'top': mid-151
                        });
                        $('#slide-next').addClass('fixed').css({
                            'right': slideshow.slideContainer.offset().left,
                            'top': mid-151
                        });
                    
                    }else{
                    
                        // Unstick the prev/next buttons
                        $('#slide-prev').removeClass('fixed').css({
                            'left': 0,
                            'top': 165
                        });
                        $('#slide-next').removeClass('fixed').css({
                            'right': 0,
                            'top': 165
                        });
                    
                    }
                
                }
    
            },
            'init': function(){
            
                // Initialize sticky buttons
                if($.browser.mozilla){
                    slideshow.stick.elems = slideshow.slideNext.add(slideshow.slidePrev);
                    slideshow.stick.listener = $('<div id="listener">&nbsp;</div>').appendTo('body');
                    $(window).bind('scroll', slideshow.stick.check);
                    slideshow.stick.check();
                }
            
            }
        },
        'toggle': function(e){
            e.preventDefault();
            if(slideshow.visible){
            
                slideshow.visible = false;
                slideshow.slideClose.unbind('click').click(slideshow.emptyEvent);
            
                // Show the slideshow
                slideshow.container.css('height', 'auto');
                slideshow.slideContainer.animate({ 'opacity': 0 }, slideshow.speed, function(){
                    $(this).hide();
                });
            
                // Hide everything else
                slideshow.nonSlide.show().css('opacity', 0).animate({ 'opacity': 1 }, slideshow.speed, function(){
                    $(this).css('filter', false);
                });
            

            }else{
            
                slideshow.visible = true;
                slideshow.slideClose.unbind('click').click(slideshow.toggle);
            
                // Hide the slideshow 
                slideshow.container.css('height', 1036);
                slideshow.slideContainer.show().css('opacity', 0).animate({ 'opacity': 1 }, slideshow.speed, function(){
                    $(this).css('filter', false);
                });
            
                // Show everything else
                slideshow.nonSlide.animate({ 'opacity': 0 }, slideshow.speed, function(){
                    $(this).hide();
                });
            
            }
        
            slideshow.stick.check();
        
        },
        'goToSlide': function(n){
        
            // Hide old slide
            if(this.currentSlide >= 0){
                this.slides[this.currentSlide].stop().animate({
                    'opacity': 0
                }, this.speed, function(){
                    $(this).hide();
                });
            }

            // Show new slide
            this.slides[n].show().css('opacity', 0).animate({
                'opacity': 1
            }, this.speed, function(){
                $(this).css('filter', false);
            });
            this.currentSlide = n;

            // Adjust behavior/appearance of 'previous' button
            if(n != this.firstSlide){
            
                // If it's hidden and needed, fade it in
                if(!this.slidePrev.is(':visible')){
                    this.slidePrev.stop().show().css('opacity', 0).animate({
                        'opacity': 1
                    }, this.speed);
                }
            
                // Change slide to move to
                this.slidePrev.find('a').unbind('click').click(function(e){
                    e.preventDefault();
                    slideshow.goToSlide(n-1);
                });
            
            }else{
            
                // If it's no longer needed, fade it out
                this.slidePrev.animate({
                    'opacity': 0
                }, this.speed, function(){
                    $(this).hide();
                }).find('a').unbind('click');
            
            }
        
            // Adjust behavior/appearance of 'next' button
            if(n != this.lastSlide){
            
                // If it's hidden and needed, fade it in
                if(this.slideNext.is(':hidden')){
                    this.slideNext.stop().show().css('opacity', 0).animate({
                        'opacity': 1
                    }, this.speed);
                }

                // Change slide to move to
                this.slideNext.show().find('a').unbind('click').click(function(e){
                    e.preventDefault()
                    slideshow.goToSlide(n+1);
                });
            
        
            }else{

                // If it's no longer needed, fade it out
                this.slideNext.animate({
                    'opacity': 0
                }, this.speed, function(){
                    $(this).hide();
                }).find('a').unbind('click');

            }
        
            slideshow.stick.check();
        
        },
        
        '_load_slide': function(index, src) {
            var slide = $("#slide-" + index + " img").attr("src", src)
            if (index === slideshow.lastSlide) {
                var self = this;
                slide.load(function () { 
                    self.button.removeClass('loading');
                    self.button.find("a").html(self.button_ready_text);
                });
            }            
        },
        
        'init': function(list){
        
            if( $('body').attr('id') == 'case-study' && !mobile ){
            
                // Set up close button
                this.slideClose.click(slideshow.toggle);
            
                // Set up slides
                var self = this;
                list.addClass('active').find('li a').each(function(index, elem){
                    slideshow.slides[index] = slideshow.slideList.append('<li id="slide-' + index + '" class="slide"><h4>' + $(this).text() + '</h4><div class="slide-image"><img src="" alt="' + $(this).text() + '" /></div></li>').find('#slide-' + index).hide();
                    var href = $(this).attr('href');
                    $(window).load(function() {
                        self._load_slide.apply(self, [index, href]);
                    });
                    slideshow.lastSlide = index;
                });
            
                // Set up toggle
                var loading = '';
                this.button = list.find('h3').eq(0).addClass('loading');
                this.button_ready_text = this.button.text();
                this.button.wrapInner('<a href="#screenshots"></a>').find('a').html("loading screens...").click(function(e){
                    e.preventDefault();
                    slideshow.toggle(e);
                    if(slideshow.currentSlide == -1) slideshow.goToSlide(0);
                });
                
                this.stick.init();
            
            }
        
        }
    }


    // Homepage billboard
    var highlights = (mobile || !support.displayTable || oldGecko) ? { 
        'init': function(){ 
            return;
        } 
    } : {
        'slideContainer': $('#highlights'),
        'currentSlide': 0,
        'first': true,
        'firstSlide': 0,
        'lastSlide': 0,
        'slideWidth': 940,
        'slideHeight': 369,
        'distance': 500,
        'speed': speed(300),
        'slides': [],
        'emptyEvent': function(e){
            e.preventDefault();
        },
        'slidePrev': $('<div id="highlights-prev"><a href="#">Previous</a></div>').appendTo($('#highlights')),
        'slideNext': $('<div id="highlights-next"><a href="#">Next</a></div>').appendTo($('#highlights')),
        'slideNav': $('<ul id="highlights-nav"></ul>').appendTo($('#highlights')),
        'adjustNav': function(n){
        
            this.slideNav.find('li').removeClass('active').eq(n).addClass('active');
        
            // Adjust 'previous slide' button
            if(this.currentSlide == this.firstSlide) this.slidePrev.fadeIn(this.speed);
            if(n == this.firstSlide){
                var s = this.first ? 0 : this.speed
                this.slidePrev.unbind('click').click(this.emptyEvent).fadeOut(s);
            }else{
                this.slidePrev.find('a').eq(0).unbind('click').click(function(e){
                    e.preventDefault;
                    highlights.goToSlide(n-1);
                });
            }
        
            // Adjust 'next slide' button
            if(this.currentSlide == this.lastSlide) this.slideNext.fadeIn(this.speed);
            if(n == this.lastSlide){
                this.slideNext.unbind('click').click(this.emptyEvent).fadeOut(this.speed);
            }else{
                this.slideNext.find('a').eq(0).unbind('click').click(function(e){
                    e.preventDefault;
                    highlights.goToSlide(n+1);
                });
            }
        
        },
        'goToSlide': function(n){
        
            // Animate from the right
            if(this.currentSlide < n){
            
                // Move old slide out
                this.slides[this.currentSlide].stop().animate({
                    'left': ($.browser.msie) ? 0 : '-=' + this.distance + 'px',
                    'opacity': 0
                }, (this.speed*0.75), 'easeInQuad', function(){
                    $(this).hide();
                });
            
                // Move new slide in
                this.slides[n].css({
                    'left': ($.browser.msie) ? 0 : this.distance,
                    'opacity': 0
                }).show().delay(this.speed).animate({
                    'left': 0,
                    'opacity': 1
                }, this.speed, 'easeOutQuad', function(){
                    $(this).css('filter', false);
                });
        
            // Animate from the left
            }else if(this.currentSlide > n){
            
                // Move old slide out
                this.slides[this.currentSlide].stop().animate({
                    'left': ($.browser.msie) ? 0 : '+=' + this.distance + 'px',
                    'opacity': 0
                }, (this.speed*0.75), 'easeInQuad', function(){
                    $(this).hide();
                });
            
                // Move new slide in
                this.slides[n].css({
                    'left': (this.distance*-1),
                    'opacity': 0
                }).show().delay(this.speed).animate({
                    'left': 0,
                    'opacity': 1
                }, this.speed, 'easeOutQuad', function(){
                    $(this).css('filter', false);
                });
            
            }
        
            // Adjust navigation
            if(this.currentSlide != n){
                this.adjustNav(n);
                this.currentSlide = n;
            }
            
        },
        'init': function(){
        
            if( this.slideContainer.length ){
            
                // Activate this thing
                $('#billboard').addClass('active');
            
                // Set up slides
                this.slideContainer.find('li').each(function(index, elem){
                
                    highlights.slides[index] = $(elem);
                    highlights.lastSlide = index;
                
                    // Create dot navigation
                    $(highlights.slideNav).append('<li id="hnav-' + index + '"><a href="">Slide ' + (index+1) + '</a></li>');
                    $('#hnav-' + index + ' a').data('slideNo', index).click(function(e){
                        e.preventDefault();
                        highlights.goToSlide($(this).data('slideNo'));
                    });
                
                }).hide().eq(0).show();
            
                // Finsih setup
                this.slideNext.add(this.slidePrev).click(this.emptyEvent);
                this.adjustNav(0);
                this.first = false;
            
            }
        
        }
    }


    var facts = {
        'slideContainer': $('#facts ul'),
        'currentSlide': -1,
        'first': true,
        'firstSlide': 0,
        'lastSlide': 0,
        'speed': speed(500),
        'slides': [],
        'slideNav': $('<ul id="facts-nav"></ul>').appendTo($('#facts')),
        'goToSlide': function(n){
        
            if(n != facts.currentSlide){
                if(facts.currentSlide >= 0) facts.slides[facts.currentSlide].fadeOut(facts.speed);
                facts.slides[n].fadeIn(facts.speed);
                facts.slideNav.find('li').removeClass('active').eq(n).addClass('active');
                facts.currentSlide = n;
            }
        
        },
        'init': function(){
        
            if( facts.slideContainer.length && support.displayTable && !mobile ){
            
                // Activate this thing
                $('#facts').addClass('active');
            
                // Set up slides
                facts.slideContainer.find('li').each(function(index, elem){
                
                    facts.slides[index] = $(elem);
                    facts.lastSlide = index;
                
                    // Create dot navigation
                    $(facts.slideNav).append('<li id="fnav-' + index + '"><a href="">Fact ' + (index+1) + '</a></li>');
                    $('#fnav-' + index + ' a').data('slideNo', index).click(function(e){
                        e.preventDefault();
                        facts.goToSlide($(this).data('slideNo'));
                    });
                
                }).hide().eq(0).show();
            
                // Finish setup
                facts.goToSlide(0);
                facts.first = false;
            
            }
        }
    }


    if(typeof(GMap2) !== "undefined" && !mobile){
        
        var map = {
            'map': new GMap2(document.getElementById("map_canvas")),
            'pointList': $('#threespots'),
            'pointSets': [],
            'currentSet': -1,
            'speed': speed(400),
            'threespot': new GLatLng(38.931036, -77.032647),
            'defaultCenter': new GLatLng(38.929705, -77.032539),
            'defaultZoom': 16,
            'iconFactory': function(n){
                var baseIcon = new GIcon();
                baseIcon.image = (!!n) ? site_media_url + 'images/map/flag' + n + '.png' : site_media_url + 'images/map/ts.png';
                baseIcon.shadow = site_media_url + ((!!n) ? "images/map/shadow.png" : "images/map/ts_shadow.png");
                baseIcon.iconSize = (!!n) ? new GSize(20, 23) : new GSize(55, 23);
                baseIcon.shadowSize = (!!n) ? new GSize(31, 25) : new GSize(66, 25);
                baseIcon.iconAnchor = new GPoint(0, 23);
                return baseIcon;
            },
            'infoWindowHtml': '<div id="infowindow"><div id="infowindow-threespot">Threespot</div><div id="infowindow-addr">3333 14th Street NW, Suite 300 <br />Washington, DC 20010</div><div id="infowindow-dirs"><label for="saddr">Get directions from:</label></div><form action="http://maps.google.com/maps" method="get"><input type="text" name="saddr" id="saddr" value=""><button type="submit">Go</button><input type="hidden" name="daddr" value="3333 14th Street Northwest, Washington, DC 20010"><input type="hidden" name="hl" value="en"></form></div>',
            'infoWindow': function(){
                map.map.openInfoWindowHtml(map.threespot, map.infoWindowHtml, {
                    'pixelOffset': new GSize(55, -23)
                });
            },
            'changeSet': function(n){

                // Hide current set
                if( this.currentSet >= 0){
                    for(var i=0; i<this.pointSets[this.currentSet].length; i++){
                        this.pointSets[this.currentSet][i].marker.hide();
                    }
                    this.pointList.children('li').eq(this.currentSet).addClass('hidden').find('ul').animate({
                        'height': 0,
                        'opacity': 0
                    }, this.speed, function(){
                        $(this).hide();
                    });
                }


                if(n != this.currentSet){
                
                    // Show new set, recenter and zoom to fit
                    var b = new GLatLngBounds();
                    var pad = 0.001;
                    b.extend(this.threespot);
                    for(var i=0; i<this.pointSets[n].length; i++){
                        var p = this.pointSets[n][i];
                    
                        p.marker.show();
                    
                        // Give a 0.001 pad
                        var x = (p.longitude > this.threespot.x) ? p.longitude + pad : p.longitude - pad;
                        var y = (p.latitude > this.threespot.y) ? p.latitude + pad : p.latitude - pad;
                        b.extend(new GLatLng(y, x));
                    
                    }
                    this.map.setZoom(this.map.getBoundsZoomLevel(b));
                    this.map.setCenter(b.getCenter());
                
                    var l = this.pointList.children('li').eq(n).removeClass('hidden').find('ul');
                    l.show().animate({
                        'height': l.data('orig'),
                        'opacity': 1
                    }, this.speed, function(){
                        if($.browser.msie) $(this).css('filter', false);
                    });
                
                    this.currentSet = n;
                
                }else{
                
                    this.map.setCenter(this.defaultCenter, this.defaultZoom);
                    this.currentSet = -1;
                
                }


            },
            'init': function(){

                this.map.setCenter(this.defaultCenter, this.defaultZoom);
                this.map.setUIToDefault();


                if(!$.browser.msie || ($.browser.msie && $.browser.version > 7)){
                    
                    this.pointList.addClass('active');

                    if($.browser.msie && $.browser.version > 7) this.pointList.addClass('newie');

                    
                    // Load point sets into an object
                    this.pointList.children().each(function(index, element){
                        var parent = {
                            'i': index,
                            'e': element
                        };
                        map.pointSets[parent.i] = [];
                        $(element).find('li').each(function(index, element){
                            var l = $(element).attr('title').split(', ');
                            map.pointSets[parent.i][index] = {
                                'element': element,
                                'name': $(element).text(),
                                'latitude': parseFloat(l[0]),
                                'longitude': parseFloat(l[1]),
                                'parent': parent,
                                'latLng': new GLatLng(parseFloat(l[0]), parseFloat(l[1])),
                                'marker': false
                            };
                            map.pointSets[parent.i][index].marker = new GMarker(map.pointSets[parent.i][index].latLng, {
                                'icon': map.iconFactory(index+1),
                                'clickable': false
                            });
                            map.map.addOverlay(map.pointSets[parent.i][index].marker);
                            map.pointSets[parent.i][index].marker.hide();
                        });

                        var l = $(this).addClass('hidden').children('ul')
                        l.data('orig', l.height()).css({
                            'height': 0,
                            'opacity': 0
                        }).hide();
                        $(this).children('h3').click(function(e){
                            e.preventDefault();
                            map.changeSet(index);
                        });
                    });
                }

                this.threespotMarker = new GMarker(this.threespot, {
                    'icon': this.iconFactory()
                })
                this.map.addOverlay(this.threespotMarker);
                GEvent.addListener(this.threespotMarker, "click", this.infoWindow);

            }
        }

    }


    // Services show/hide
    var services = {
        'list': $('#services ul').eq(0),
        'init': function(){
            var l = services.list.find('> li');
            l.each(function(){
                $(this).find('h4').mouseenter(function(){
                    var m = $('<div id="service-overlay">' + $(this).parent().html() + '</div>').appendTo($(this));
                    var i = (l.index($(this).parent()) + 1);
                    m.css('top', -1 * (m.height()/2) + parseInt(m.css('padding-top')));
                    if(i==1) m.css('left', 0);
                    else if(i==l.length) m.css('right', 0);
                    else m.css('left', -1 * ((m.width() - $(this).parent().width())/2));
                    $(this).closest('li').addClass('top');
                }).mouseleave(function(){
                    $('#service-overlay').remove();
                    $(this).closest('li').removeClass('top');
                });
            });
            
        }
    }


    // Case study pager (used on 'What We Do' landing page)
    var studies = (mobile) ? { 
        'init': function(){ 
            return;
        } 
    } : {
        'list': $('#case-studies .portfolio'),
        'currentSlide': 0,
        'lastSlide': 0,
        'width': 940,
        'speed': speed(300),
        'distance': 500,
        'first': true,
        'emptyEvent': function(e){
            e.preventDefault();
        },
        'slideNav': $('<div id="s-nav">&nbsp;of&nbsp;</div>').appendTo('#case-studies'),
        'slideCount': $('<span id="s-count"></span>').appendTo('#s-nav'),
        'slideN': $('<span id="s-n">1</span>').prependTo('#s-nav'),
        'slidePrev': $('<a id="s-next" href="">&laquo; Previous</a>').prependTo('#s-nav'),
        'slideNext': $('<a id="s-prev" href="">Next &raquo;</a>').appendTo('#s-nav'),
        'goToSlide': function(n, fromLeft){
            
            var newSlide = studies.list.children().eq(n);
            var oldSlide = studies.list.children().eq(studies.currentSlide);
            
            // First time through
            if(studies.first){
            
                newSlide.show();
                this.first = false;
            
            // Coming in from the right
            }else if(!fromLeft){
            
                // Bring the new slide in
                newSlide.delay(speed(250)).show().css({
                    'left': ($.browser.msie) ? 0 : studies.distance,
                    'opacity': 0
                }).animate({
                    'left': 0,
                    'opacity': 1
                }, studies.speed, 'easeOutQuad');
            
                // Send the old slide out
                oldSlide.stop().animate({
                    'left': studies.distance*-1,
                    'opacity': 0
                }, studies.speed, 'easeInQuad', function(){
                    $(this).hide();
                });
            
            
            // Coming in from the left
            }else if(fromLeft){
            
                // Bring the new slide in
                newSlide.delay(speed(250)).show().css({
                    'left': ($.browser.msie) ? 0 : -1*studies.distance,
                    'opacity': 0
                }).animate({
                    'left': 0,
                    'opacity': 1
                }, studies.speed, 'easeOutQuad');
            
                // Send the old slide out
                oldSlide.stop().animate({
                    'left': studies.distance,
                    'opacity': 0
                }, studies.speed, 'easeInQuad', function(){
                    $(this).hide();
                });
            
            }
            
            // Update variables and text
            studies.currentSlide = n;
            studies.slideN.text(studies.currentSlide+1);
            
        },
        'init': function(){
            
            // Wrap each chunk of 6 items in a div, then wrap each chunk of three in another (for visual display)
            if($('#case-studies .portfolio').length){
                this.list.splitList(6, {'wrapClass': 'block', 'splitInto': 'rows'}).find('.block').each(function(){
                    $(this).splitList(3, {'wrapClass': 'row', 'splitInto': 'rows'});
                });
            }
            
            // Make sure the container is as tall as the tallest block of 6
            studies.list.css('height', $('.block').eq(0).height());
            $('.block').each(function(){
                if(studies.list.css('height') < $(this).height()) studies.list.css('height', $(this).height());
            });
            
            // Finish setup
            this.list.addClass('active').children().hide();
            this.lastSlide = studies.list.children().length - 1;
            this.slideCount.text(studies.list.children().length);
            this.goToSlide(this.currentSlide);
            
            // Update the prev/next buttons
            studies.slidePrev.click(function(e){ 
                e.preventDefault();
                studies.goToSlide((!studies.currentSlide) ? studies.lastSlide : studies.currentSlide-1, true);
            });
            studies.slideNext.unbind('click').click(function(e){
                e.preventDefault();
                studies.goToSlide((studies.currentSlide==studies.lastSlide) ? 0 : studies.currentSlide+1, false);
            });
            
        }
    }
    
    var blockLink = {
        'defaultCSSClass': 'hover',
        'defaultLink': 'a:eq(0)',
        'defaultCursor': 'pointer',
        'defaultClick': function(ev, o, el){
            window.location.href = $(el).find(o.link).attr('href');
        },
        'init': function(elems){
            for(var i=0; i < elems.length; i++){
                var el = (elems[i] instanceof jQuery) ? elems[i] : elems[i].elem;
                var o = {
                    'link': (typeof(elems.link) !== "undefined") ? elems.link : blockLink.defaultLink,
                    'CSSClass': (typeof(elems.CSSClass) !== "undefined") ? elems.cssClass : blockLink.defaultCSSClass,
                    'cursor': (typeof(elems.cursor) !== "undefined") ? elems.cursor : blockLink.defaultCursor,
                    'click': (typeof(elems.click) !== "undefined") ? elems.click : blockLink.defaultClick
                };
                $(el).each(function(){
                    $(this).css('cursor', o['cursor']).click(function(ev){
                        o.click(ev, o, this);
                    }).hover(function(){
                        $(this).addClass(o.CSSClass);
                    }, function(){
                        $(this).removeClass(o.CSSClass);
                    });
                });
            }
        }
    };
    
    // Initialize everything
    highlights.init();
    twitter.init();
    caseStudies.init();
    slideshow.init($('#case-study #images'));
    facts.init();
    services.init();
    if(typeof(map) !== "undefined") map.init();
    studies.init();
    blockLink.init([
        $('.portfolio li')
    ]);
    
    $('#clients ul').splitList(3);
    
    $('#footer #social-media li:last-child, #threespots li:last-child, #threespots.active li li:last-child, #services li:last-child, #case-studies .active li:last-child, #clients div:last-child, #sidebar #facts li:last-child, #case-study #selected-works li:last-child').addClass('last');
    $('#portfolio-promo .portfolio li:first-child, #threespots.active li li:first-child, #contact dt:first-child, #sidebar :first-child, #sidebar #facts li:first-child, #twitter li:first-child, #header #nav li:first-child').addClass('first');
    
    if($.browser.webkit && (parseInt($.browser.version) <= 526)) $('#container').css('overflow', 'hidden');
    
});
if ($.browser.webkit && parseFloat($.browser.version) < 524) {
    $(window).load(function() {} );
}

if($.browser.msie && parseFloat($.browser.version) < 7) { 
    $(document).ready(function() { 
        $("#facts li").css({'position': 'relative' });
        $(".jobposting").css({'width': '100%'}).append($('<br clear="both"/>'));
    })
}

