if(!window['haskell']) {
    window['haskell'] = {};
    var haskell = window['haskell'];
}

(function($){
    
    $(document).ready(function() {
        $('body').addClass('scripted');
        haskell.homepage();
        haskell.portfolio();
//        haskell.subnavs();
        haskell.maps();
//        haskell.scroller();
    });
    
    $(window).load(function() {
        if(! $('body').is('.do-animation') ) {
            haskell.heroshots();
        }
    });
    
    haskell.portfolio = function() {
        if(!$('body').is('.portfolio')) { return; }
        
        $.fn.reverse = [].reverse;

        var overlay = $('#overlay').size() ? $('#overlay') : $('<div id="overlay" />').hide().appendTo($('body'));
        var container = $('#lightbox').size() ? $('#lightbox') : $('<div id="lightbox" />').hide().appendTo($('body'));
        var target = container.find('.target').size() ? container.find('.target') : $('<div class="target" />').appendTo(container);
        var linkProto = $('<a />');
        var prev = linkProto.clone().attr({'class': 'prev', 'href': '#previous'}).text('« Back');
        var next = linkProto.clone().attr({'class': 'next', 'href': '#next'}).text('Next »');
        var close = linkProto.clone().attr({'class': 'close', 'href': '#close'}).text('Close');
        var actions = container.find('.actions').size() ? container.find('.actions') : $('<div class="actions" />');
        actions.empty().append(prev).append(close).append(next).appendTo(container);
        var ajaxTemp = $('<div />');

        var thumbs = $('#full .thumbs a:has(img)');

        close.add(overlay).click(function(c) {
            c.preventDefault();
            if($.browser.msie) {
                overlay.hide();
            } else {
                overlay.fadeOut(1000);
            }
            container.fadeOut(1000);
            haskell.heroshots.go();
        });
        
        container.click(function(c) {
            c.stopPropagation();
        });
        
        prev.click(function(c) {
            c.preventDefault();
            var thumb = false;
            try {
                var rel = target.find('.content .thumbs a').eq(0).attr('rel');
                if(thumbs.filter('[rel=' + rel + ']').eq(0).parent('li').prev('li').find('a').size()) {
                    thumb = thumbs.filter('[rel=' + rel + ']').eq(0).parent('li').prev('li').find('a');
                } else if(thumbs.filter('[rel=' + rel + ']').eq(0).parents('.room').prev('.room').find('.thumbs li:first-child a').size()) {
                    thumb = thumbs.filter('[rel=' + rel + ']').eq(0).parents('.room').prev('.room').find('.thumbs li:first-child a');
                }
            } catch(e) {
            }
            
            if(thumb) {
                target.fadeOut(1000,
                    function() {
                        thumb.click();
                    }
                );
            }
        });

        next.click(function(c) {
            c.preventDefault();
            var thumb = false;
            try {
                var rel = target.find('.content .thumbs a').eq(0).attr('rel');
                var subthumbs = thumbs.filter('[rel=' + rel + ']');
                if(subthumbs.eq(subthumbs.size() - 1).parent('li').next('li').find('a').size()) {
                    thumb = subthumbs.eq(subthumbs.size() - 1).parent('li').next('li').find('a');
                } else if(subthumbs.eq(subthumbs.size() - 1).parents('.room').next('.room').find('.thumbs li:first-child a').size()) {
                    thumb = subthumbs.eq(subthumbs.size() - 1).parents('.room').next('.room').find('.thumbs li:first-child a');
                }
            } catch(e) {
            }
            
            if(thumb) {
                target.fadeOut(1000,
                    function() {
                        thumb.click();
                    }
                );
            }
        });
        
        thumbs.parents('.project,.room').find('h2').each(function() {
            var h2 = $(this);
            var link = h2.find('a');
            h2.attr({'rel': link.attr('href')}).html(link.html());
        });
        
        thumbs.each(function(index) {
            var thumb = $(this);
            thumb.click(function(c) {
                c.preventDefault();
                clearInterval(haskell.heroshots.interval);
                var h2 = thumb.parents('.project,.room').find('h2');
                ajaxTemp.load(
                    h2.attr('rel'),
                    function() {
                        var newContent = ajaxTemp.find('#room-' + thumb.attr('rel'));
                        newContent.find('h2').text(h2.text());
                        target.empty().append($('<div class="content" />').append(newContent)).append($('<div class="big-image" />').append($('<img src="' + thumb.attr('href') + '" />')));
                        target.find('.content .room').children('.description').html(thumb.siblings('.description').html())
                        if( ! target.is(':visible') ) {
                            target.fadeIn(1000);
                        }
                        target.find('.thumbs a:has(img)').click(function(c) {
                            c.preventDefault();
                            var link = $(this);
                            var currentImage = target.find('.big-image img');
                            if ( currentImage.attr('src') != link.attr('href') ) {
                                currentImage.fadeOut(1000, function() {
                                    var img = new Image();
                                    img.onload = function() {
                                        img.style.display = 'none';
                                        currentImage.parent().append($(img));
                                        $(img).fadeIn(1000);
                                        currentImage.remove();
                                    };
                                    img.src = link.attr('href');
                                    target.find('.content .room').children('.description').html(link.siblings('.description').html());
                                });
                            }
                        });
                        if ( ! overlay.is(':visible') ) {
                            if($.browser.msie) {
                                overlay.show();
                            } else {
                                overlay.fadeIn(1000);
                            }
                        }
                        if ( ! container.is(':visible') ) {
                            container.fadeIn(1000);
                        }
                    }
                );
            });
        });
        
    }
    
    haskell.subnavs = function() {
        var subnavs = $('#subnav ul.sub');
        subnavs.each(function() {
            var subnav = $(this);
            var parentLink = subnav.siblings('a');
            if( ! parentLink.is('.ancestor') && ! parentLink.is('.selected') && ! parentLink.is('[href*=personnel]') ) {
                subnav.hide();
                parentLink.click(function(c) {
                    c.preventDefault();
                    if(subnav.is(':visible')) {
                        window.location = parentLink.attr('href');
                    } else {
                        subnav.slideDown(1000);
                    }
                });
            }
        });
    }
    
    haskell.heroshots = function() {
        var heroshot = $('.heroshot-animated');
        
        var fade = parseInt( heroshot.attr('data-transition'), 10 ) * 1000;
        var dur = parseInt( heroshot.attr('data-show'), 10) * 1000;
        
        var images = heroshot.find('img');
        if( images.size() < 2 ) { return; }
        var extraImage = images.eq(0).clone();
        
        var wrapper = $('<div class="heroshot-wrapper" />');
        wrapper.height(heroshot.height()).css({'white-space': 'nowrap', 'top': 0, 'left': 0, 'position': 'relative'});
        wrapper.appendTo(heroshot).append(images).append(extraImage).width(0);
        images = images.add(extraImage);
        images.each(function() {
            wrapper.width( wrapper.width() + $(this).width() );
        });
        var targetWidth = wrapper.width() - images.eq(images.size() - 1).width();
        
        haskell.heroshots.go = function() {
            haskell.heroshots.interval = setInterval(function(){
                wrapper.animate({
                        'left': (parseInt( wrapper.css('left'), 10 ) - heroshot.width()) + 'px'
                    },
                    fade,
                    'easeInOutSine',
                    function() {
                        if( (Math.abs(parseInt(wrapper.css('left'),10)) == targetWidth) ) {
                            wrapper.css({'left': 0});
                        }
                    }
                );
            }, fade + dur);
        }
        haskell.heroshots.go();
    }
    
    haskell.homepage = function() {
        if( ! $('body').is('.do-animation') ) { return; }
        
        var wrapper = $('#wrapper');
        wrapper.width(wrapper.width()).height(wrapper.height()).hide();
        
        var footer = $('#ft');
        footer.hide();
        
        var header = $('#hd');
        var sb = $('#sb');
        var callout = $('.callout');
        var main = $('#main');
        
        header.add(sb).add(callout).add(main).hide();
        $(window).load(function() {
            wrapper.fadeIn(1000,function(){
                callout.css({'position': 'relative', 'top': '100px'}).show();
                header.css({'position': 'relative', 'top': '-200px'}).show();
                header.animate({'top': 0}, 1000, function(){
                    setTimeout(function(){
                        sb.fadeIn(1000, function() {
                            main.fadeIn(1000, function() {
                                callout.animate({'top': 0}, 1000);
                                haskell.heroshots();
                                footer.fadeIn(3000);
                            });
                        });
                    },500);
                });
            });
        });
    }
    
    haskell.maps = function() {
        var mapHolder = $('#map');
        if( ! mapHolder.size() ) { return; }

        var gmaps = google.maps;

        var latLng = new gmaps.LatLng(35.159846,-84.874942);

        haskell.geocoder = new gmaps.Geocoder() // Init the geocoder
        if ( ! haskell.geocoder ) { return false; } // bail, none of this will work
        var map;

        haskell.geocoder.geocode(
            { 'latLng': latLng },
            function( results, status ) {
                if ( status != gmaps.GeocoderStatus.OK ) { return; }
                map = new gmaps.Map(mapHolder[0], {
                    'zoom': 7,
                    'center': results[0].geometry.location,
                    'mapTypeId': gmaps.MapTypeId.ROADMAP,
                    'scrollwheel': false,
                    'disableDefaultUI': true,
                    'navigationControl': true
                }); // Set up the map
                map.fitBounds( results[0].geometry.viewport );
                var marker = new gmaps.Marker({
                    'map': map,
                    'position': results[0].geometry.location
                });
            }
        );
        
        haskell.routeFinder = new gmaps.DirectionsService();
        haskell.routeMaker = new gmaps.DirectionsRenderer();
        if( ! haskell.routeFinder || ! haskell.routeMaker ) { return; }
        var form = $('#directions');
        var directionsPanel = $('<div class="route"></div>');
        form.append(directionsPanel);
        form.submit(function(s) {
            s.preventDefault();
            var request = {
                'destination': latLng,
                'origin': form.find('input[name=saddr]').val(),
                'travelMode': gmaps.DirectionsTravelMode.DRIVING
            };
            haskell.routeFinder.route(
                request,
                function(response, status) {
                    if( status == gmaps.DirectionsStatus.OK ) {
                        haskell.routeMaker.setMap(map);
                        haskell.routeMaker.setPanel(directionsPanel[0]);
                        haskell.routeMaker.setDirections(response);
                    } else {
                        alert('We could not find your directions.');
                    }
                }
            )
        });
    }
    
    haskell.scroller = function() {
        $('.link-list').each(function() {
            var list = $(this);
            if( ! list.size() ) { return; }

            var slider = $('<div class="slider"></div>');
            var wrapper = $('<div class="slider-wrapper"></div>');
//            wrapper.appendTo(list.parent()).append(list).wrap(slider);
            list.after(slider.append(wrapper));
            wrapper.append(list);

            var slideBy = wrapper.width();

            var items = list.children();
            var listWidth = 0;
            items.each(function() {
                listWidth += $(this).outerWidth(true);
                if($(this).outerHeight(true) > wrapper.height()) {
                    wrapper.height($(this).outerHeight(true));
                }
            });
            list.width(listWidth);
            listWidth = 0 - listWidth;

            var prev = $('<a href="#previous" title="Go Back" class="prev">Go Back</a>');
            var next = $('<a href="#next" title="Go Forward" class="next">Go Forward</a>');
            prev.addClass('disabled');
            if(list.width() < wrapper.width()) {
                next.addClass('disabled');
            }

            prev.add(next).appendTo(wrapper).click(function(c) {
                c.preventDefault();
                if($(this).is('.disabled')) { return; }
                prev.add(next).removeClass('disabled');
                var currentLeft = parseInt(list.css('left'), 10);
                if( isNaN(currentLeft) ) {
                    currentLeft = 0;
                }
                var nextLeft = $(this).is('.prev') ? currentLeft + slideBy : currentLeft - slideBy;
                if( $(this).is('.prev') && nextLeft >= 0 ) {
                    nextLeft = 0;
                    prev.addClass('disabled');
                } else if( $(this).is('.next') && nextLeft <= (listWidth + slideBy) ) {
                    nextLeft = listWidth + slideBy;
                    next.addClass('disabled');
                }
                list.animate({
                    'left': nextLeft + 'px'
                }, 2000, 'easeInOutSine');
            });
        });
    }
    
    
})(jQuery);