$(document).ready(function() {
	preload([
	  		'/img/pyramid-bottom-fill.png',
	 		'/img/pyramid-down-fill.png',
	 		'/img/pyramid-pgdn-fill.png',
	 		'/img/pyramid-pgup-fill.png',
	 		'/img/pyramid-top-fill.png',
	 		'/img/pyramid-up-fill.png',
	 		'/img/photo-biggerize.png',
	 		'/img/photo-biggerize-fill.png',
	 		'/img/photo-close.png',
	 		'/img/photo-close-fill.png',
	 		'/img/photo-flickr.png',
	 		'/img/photo-flickr-fill.png',
	 		'/img/rotate-cube.png'
	 	]);

    $('a').each(setExternalLink);

    $('#photos div a').bind('click', showPreview).bind('click', false);
    $('#loadingbox, #previewbox, #pclose').bind('click', closePreview);
    $('#previewstage').bind('click', false);
    $('#previewstage a').bind('click', function(e) {
        e.stopPropagation();
    });
    
    $('#pup').bind('click', {rows: 1}, photoUp).bind('click', false);
    $('#ppgup').bind('click', {rows: 4}, photoUp).bind('click', false);
    $('#ptop').bind('click', photoTop).bind('click', false);
    $('#pdown').bind('click', {rows: 1}, photoDown).bind('click', false);
    $('#ppgdn').bind('click', {rows: 4}, photoDown).bind('click', false);
    $('#pbottom').bind('click', photoBottom).bind('click', false);
    
    var rowheight = $('#photos div').height() + parseInt($('#photos div').css('margin-top'));
    
    function preload(imagearr) {
    	$(imagearr).each(function(){
    		(new Image()).src = this;
    	});
    }
    
    function setExternalLink() {
    	if ($(this).attr('href') && $(this).attr('rel') == 'external') {
    		$(this).attr('target', '_blank');
    	}
    }
    	
    function showPreview() {
        $('#photowrapper').animate({'opacity': .15});
        $('#loadingbox').fadeIn();
        var pid = $('img', this).attr('id').slice(5);
        $.getJSON('fetch/photo/' + pid, function(photo) {
            var newimg = new Image();
            newimg.src = photo.uri;
            newimg.onload = function() {
                $('#loadingbox').fadeOut(200, function() {
                    $('#preview').attr('src', photo.uri);
                    $('#pflickr').attr('href', 'http://flickr.com/photos/marcuskamps/' + pid);
                    $('#pbiggerize').attr('href', '/photo/' + pid);
                    $('#previewbox').fadeIn();
                });
            }
        });
    }
    
    function closePreview() {
        $('#loadingbox, #previewbox').fadeOut(200);
        $('#photowrapper').animate({'opacity': 1});
    }
    
    function unbindArrows() {
        $('#pup').unbind('click', photoUp);
        $('#ppgup').unbind('click', photoUp);
        $('#ptop').unbind('click', photoTop);
        $('#pdown').unbind('click', photoDown);
        $('#ppgdn').unbind('click', photoDown);
        $('#pbottom').unbind('click', photoBottom);
    }

    function photoTop() {
        unbindArrows();
        if (-parseInt($('#photos').css('top')) > 0) {
            doScroll(0);
        }
    }

    function photoBottom() {
        unbindArrows();
        var top = -parseInt($('#photos').css('top'));
        var maxtop = $('#photos').innerHeight() - $('#photobox').height()
        var nums = $('#photos div:last-child a:last-child img').attr('alt').split(' of ');

        if (maxtop - top > 0) {
            doScroll(parseInt(nums[0]) < parseInt(nums[1]) ? maxtop - rowheight : maxtop);
        }
    }

    function photoUp(e) {
        unbindArrows();
        var top = -parseInt($('#photos').css('top'));
        var rows = e.data.rows;

        // not at top: scroll up
        if (top > 0) {
            // less than the scroll distance from the top: just set top to zero
            doScroll(Math.max(top - rowheight * rows, 0));
        }
    }
    
    function photoDown(e) {
        unbindArrows();
        var top = -parseInt($('#photos').css('top'));
        var maxtop = $('#photos').innerHeight() - $('#photobox').height();
        var bottom = maxtop - top;
        var rows = e.data.rows;
        var nums = $('#photos div:last-child a:last-child img').attr('alt').split(' of ');

        // not at the bottom: scroll down
        if (bottom > 0) {
            var hiddenrows = bottom / rowheight;
            var hiddenmin = 1; // number of hidden rows before forcing a load
            var hiddenmax = 4; // number of hidden rows to aim for after a load
            // scroll distance plus preload exceeds amount hidden at bottom: fetch more images
            if (hiddenrows < (rows + hiddenmin) && parseInt(nums[0]) < parseInt(nums[1])) {
                var getrows = rows - hiddenrows + hiddenmax;
                $('.pscroll img').animate({'opacity': .5}, 150);
                $.get('/fetch/photos/rows/' + getrows + '/skip/' + nums[0], function(html) {
                    var newrows = $(html).filter('div').appendTo('#photos');
                    maxtop += rowheight + newrows.length;
                    var link = '/photos/skip/' + $('a:last-child img', newrows).attr('alt').split(' of ')[0];
                    $('#pdown').attr('href', link);
                    $('a', newrows).bind('click', showPreview).bind('click', false);
                    $('.pscroll img').animate({'opacity': 1}, 150);
                    // less than scroll distance from bottom: set top to maximum
                    doScroll(Math.min(top + rowheight * rows, maxtop));
                });
                
            } else {
                // less than scroll distance from bottom: set top to maximum
                doScroll(Math.min(top + rowheight * rows, maxtop));
            }
        }
    }
    
    function doScroll(top) {
        $('#photos').animate({'top': -top + 'px'}, 300, function() {
            // reached top: hide up arrows, else re-enable them
            if (top <= 0) {
                $('.pscrollup').fadeOut();
            } else {
                $('.pscrollup').fadeIn();
                $('#pup').bind('click', {rows: 1}, photoUp);
                $('#ppgup').bind('click', {rows: 4}, photoUp);
                $('#ptop').bind('click', photoTop);
            }

            // reached bottom: hide down arrows, else re-enable them
            if (top >= $('#photos').innerHeight() - $('#photobox').height()) {
                $('.pscrolldown').fadeOut();
            } else {
                $('.pscrolldown').fadeIn();
                $('#pdown').bind('click', {rows: 1}, photoDown);
                $('#ppgdn').bind('click', {rows: 4}, photoDown);
                $('#pbottom').bind('click', photoBottom);
            }
        });
    }
});

