
// Image navigation and sizing
var ImageNav = function() {
    return this.init.apply(this, arguments);
};

ImageNav.prototype = {
    currentImage: 0,
    height: 0,

    init: function (container) {
        var self = this;
        self.container = container;
        var $container = $(container);
        self.image_links = $image_links = $('.images', container).find('> a');
        
        if ($image_links.length < 1) return;

        // Navigation controls
        self.nav = $nav = $('<div class="image-nav wrapper"></div>').insertAfter($container.find('h2'));
    
        $prevImage = $('<a>&lt;</a>').addClass('prev-image').click(function() {
            self.prevImage();
        });
        $nextImage = $('<a>&gt;</a>').addClass('image-next').click(function() {
            self.nextImage();
        });
        $('<span class="nav-arrows"></span>').appendTo($nav).append($prevImage).append($nextImage);
        $('<span class="image-count"></span>').prependTo($nav);

        if ($image_links.length < 2) $nav.hide();

        
        $image_links.each(function(i) {
            /*// Add image number button
            $('<a>' + (i+1) + '</a>').addClass('nav-num').click(function() {
                self.loadImage(i);
            }).appendTo($nav);*/
        }).slice(1).hide();

        // Add caption
        self.caption = $('<div class="image-caption"></div>').insertAfter($container.find('.images'));

        self.loadImage(0);
    },

    imageResize: function(img) {
        var self = this;
        var $$ = $(img);

        // Set up image dimensions based on parent container
        var x = $$.parent().width();
        var y = $$.parent().height();
        var imageWidth = $$.width();
        var imageHeight = $$.height();
        if (!imageWidth || !imageHeight) return; 

        if (imageWidth > x) {
            imageHeight = imageHeight * (x / imageWidth); 
            imageWidth = x; 
            if (imageHeight > y) { 
                imageWidth = imageWidth * (y / imageHeight); 
                imageHeight = y; 
            }
        } else if (imageHeight > y) { 
            imageWidth = imageWidth * (y / imageHeight); 
            imageHeight = y; 
            if (imageWidth > x) { 
                imageHeight = imageHeight * (x / imageWidth); 
                imageWidth = x;
            }
        } 
        $$.attr({width: imageWidth, height: imageHeight});
    },

    loadImage: function(i) {
        var self = this;
        self.currentImage = i;
        var $link = self.image_links.hide().slice(i, i+1).show();

        // here's where we load the actual image based on the link
        // but only if it isn't loaded yet
        if (! $link.find('> img').length) {
            var src = $link.attr('href').replace(/.*media\//,'');
            src = webroot + 'img/thumbnail.php?img=' + src + '&w=500&h=500';

            // We keep track of the parent height, 
            // so when the image loads we can make more room if need be.
            // But the parent container height should only be able to 
            // grow, not shrink
            var $parent = $link.parent();
            $('<img>').appendTo($link).one('load', function() {
                var h = this.height;
                if (h > self.height ) {
                    self.height = h;
                    $parent.height(h);
                }
            }).attr('src', src);            
        }

        self.caption.html(unescape($link.attr('caption')));
        self.nav.find('a.nav-num').removeClass('hover').slice(i, i+1).addClass('hover');
        self.nav.find('.image-count').text( (i+1) + ' of ' + self.image_links.length);
    },

    rotateImage: function(direction) {
        var self = this;
        direction = parseInt(direction);
        var i = ((direction + self.currentImage) + self.image_links.length)%self.image_links.length;
        self.loadImage(i);        
    },

    prevImage: function() {
        var self = this;
        self.rotateImage(-1);
    },
    nextImage: function() {
        var self = this;
        self.rotateImage(1);
    }
};


// Collections navigation
var Collections = {
    now_scrolling: false,
    scrollPositions: [],

    init: function() {
        var self = this;
        var hash = window.location.hash.replace(/^#/,'');
        var $container = $('#content');
        self.container = $container[0];

        // Set images containers to take up % of window height
        // This is used to size the images within
        /*$('.collection').height( $(window).height() * .95 ).
            width( ($(window).width() - 240) * .8);*/

        // Portfolio filtering
        $collection_links = $('.collection-filters dd a');
        $collection_links.click(function() {
            self.filterCollections($(this).text(), true);
        });
        var c = $.cookie('collection_filter');
        if (c) { self.filterCollections(c); }

        // Filter menu hide/show
        $('.collection-filters').each(function() {
            var $filters = $(this).find('dd');
            var $trigger = $(this).find('dt');
            $trigger.click( function() {
                var $filters = $(this).next();
                if ($filters.is(':visible')) {
                    $filters.hide('slide', {direction: 'up'});
                }
                else {
                    $filters.show('slide', {direction: 'up'});
                }            
            });
            $filters.hide();
            $(this).hover(
                function() {
                    if (self.collection_filter_timeout) 
                        window.clearTimeout(self.collection_filter_timeout);
                    $(this).show();
                },
                function() {
                    self.collection_filter_timeout = window.setTimeout(function() {
                        $filters.filter(':visible').hide('slide', {direction: 'up'});
                        self.collection_filter_timeout = null;
                    }, 4000);
                }
            );
        });
        
        // Detect scrolling and highlight the collection icon
        // for the one shown in the viewport
        $(window).load(function() {
            self.savePositions();
            window.setInterval(function() {
                if (self.now_scrolling) return;            
                var s = (document.body.scrollTop ||  document.documentElement.scrollTop ) + 10; 
                var n = self.scrollPositions.length - 1;
                for ( ; n >= 0 ; n--) {
                    p1 = self.scrollPositions[n].top;
                    delta = self.scrollPositions[n].height / 3;
                    if ( (s+delta) >= p1) { break; }
                }
                var $current = $('#collection-menu li a:visible').each(function(i){
                    if (i == n) $(this).addClass('hover');
                    else $(this).removeClass('hover');
                });
            }, 500);
        });
                
        // Collection menu event
        $('#collection-menu a').click(function(e) {
            self.viewCollection(this); 
            
            // Return false from the event if we're on the collections page.
            if ($('.collection-list').length) return false;         
            return true;
        });

        // Set up images
        $('.collection').each(function() {
            var imageNav = new ImageNav(this);
        });
        
        // Here we look at the window.location.hash to see which,
        // if any, collection to show upon load
        $(window).load(function() {
            if (hash) $('#collection-menu a[rel=' + hash + ']').click();
        });

        // ie6 needs some help with the sidebar since there's
        // no position: fixed
        if( $.browser.msie && $.browser.version < 7) {
            window.setInterval(function() {
                if (self.now_scrolling) return;
                var offset = document.documentElement.scrollTop;
                $('#header').animate({'top': offset}, 100);
            }, 300);
        }
    },

    filterCollections: function(category) {
        var self = this;
        
        if (category == 'all') {
            $('#collection-menu a').css('visibility', 'visible').slice(0,1).click();
            $('.collection-list li').show();
        }
        else {
            /* Show/Hide menu icons */
            $('#collection-menu a').css('visibility', 'hidden');
            $('#collection-menu a.'+category).css('visibility', 'visible').slice(0,1).click();

            /* Show/Hide collections */
            $('.collection-list li:not(.'+category+')').hide();
            $('.collection-list li.'+category).show();
        }

        /* Highlight selected filter */
        $('.collection-filters a').removeClass('hover');
        $('.collection-filters a.filter-'+category).addClass('hover');

        $.cookie('collection_filter', category, {path: '/'});

        // Recalculate scroll positions
        window.setTimeout(function(){self.savePositions()}, 100);
    },

    // Saves the scroll positions of each collection container
    savePositions: function() {
        var self = this;
        self.scrollPositions = [];
        $('.collection:visible').each(function() {
            var offset = $(this).offset();
            self.scrollPositions.push({
                top: offset.top,
                height: $(this).height()
            });
        });
    },

    // Select a container based on the link
    viewCollection: function(link) {
        var self = this;
        var name = $(link).attr('rel');
        var $container = $(self.container);

        // Highlight the proper menu link
        $('#collection-menu a').removeClass('hover');
        $(link).addClass('hover');

        // Scoll the container to show the selected collection
        var offset = $('.collections a[name='+name+']').offset();        
        if (offset) {
            offset = offset.top;
            self.now_scrolling = true;
            $('body, html').animate({
                scrollTop: offset
            }, 600, 'swing', function() {
                self.now_scrolling = false;
                window.location.hash = name;
            });
        }        
    }
};


// Page navigation
var Pages = {
    init: function() {
        var self = this;
        var hash = window.location.hash.replace(/^#/, '');
        
        // Home page effect
        if (window.location.pathname == webroot && !hash ) {
            var $header = $('#header');
            var $overlay = $('<div id="homepage-overlay"></div>').appendTo(document.body);
            $header.find('>h1').click(function() {
                $overlay.animate({
                    width: 240 
                }, 1300, 'swing', function() {$(this).remove()});
                return false;
            });
        }

        // Pages menu
        Cufon.replace('.pages-menu a', {
            fontSize: '15px',
            hover: true
        });
        var $page_links = $('.pages-menu a');
        $page_links.each(function() {
            $(this).css('width', $(this).width() + 10);
        }).click(function() {
            var name = $(this).attr('href').replace(/^#/,'');
            $('.page').hide();
            var $link = $('.page a[name='+name+']');
            $link.parent().show();
            $('.pages-menu a').removeClass('hover');
            $(this).addClass('hover');
            Cufon.refresh('.pages-menu a');

            // This prevents the autoscrolling to the named link after the click
            $link.attr('name', '');            
            window.setTimeout(function(){$link.attr('name', name)}, 200);            
        });
        
        // See which page to show on load
        $requested_page = $('.pages-menu a[rel='+hash+']');
        if ($requested_page.length ) $requested_page.click();
        else $page_links.slice(0,1).click();        
    }
};

$(function() {
    Pages.init();
    Collections.init();    
});
