$(function() {
    var content = $("#content").css('visibility', 'hidden').imagesLoaded(function(){
        content.masonry({itemSelector : 'img', columnWidth: 328, gutterWidth: 10, isAnimated: true});
        content.css('visibility', 'visible').hide().fadeIn('fast');
        if(window.location.pathname && window.location.pathname.match(/\/photo\/[0-9]+/)) {
            var id = window.location.pathname.match(/([0-9]+)/);
            $('#p' + id[0]).click();
        }
    });
    
    var active = false,
        loader = $("<div />").addClass('loading');
        current = false,
        lightbox = $("#lightbox").click(function(e) {
        if(e.currentTarget.nodeName != 'img') {
            active = false;
            lightbox.fadeOut('fast');
        }
    });
    content.on('click', 'img', function() {
        var height = $(window).height() - 76;
        current = $(this);
        active = true;
        lightbox.show().html(loader.clone());
        $('<img />').hide().attr('src', current.data('normal')).on('load', function() {
            var img = $(this);
            img.fadeIn('fast').css('marginTop', 10 + Math.round((height - img.height()) / 2));
            lightbox.append('<div class="fb-like" data-href="http://brendanpikefilms.com/photo/' + current.data('id') + '" data-send="false" data-layout="button_count" data-show-faces="false" data-colorscheme="dark"></div>');
            FB.XFBML.parse(lightbox[0]);
        }).appendTo(lightbox).css('maxHeight', height);
    });
    
    $(window).on('resize', function() {
        if(active) {
            var height = $(window).height() - 76;
            var img = $("#lightbox img");
            img.css('marginTop', 10 + Math.round((height - img.height()) / 2)).css('maxHeight', height);
        }
    });
    
    $('body').keydown(function(e) {
        if(active) {
            e.preventDefault();
            switch(e.which) {
                case 39:
                    current.next().click();
                break;
                case 37:
                    current.prev().click();
                break;
                case 27:
                    lightbox.click();
                break;
            }
        }
    });
});
