var setup = function()
{
    $('prev').addEvent('click', function(e) {
	e = new Event(e).stop();
	var theUrl  = $('prev').href + '&json=1';
	var request = new Request.JSON({url: theUrl,
			onComplete: function(jsonObj) { replace(jsonObj, 1); }
		      }).send();
    });
    $('next').addEvent('click', function(e) {
	e = new Event(e).stop();
	var theUrl  = $('next').href + '&json=1';
	var request = new Request.JSON({url: theUrl,
			onComplete: function(jsonObj) { replace(jsonObj, 0); }
		      }).send();
    });
}
var processList = function(thumbs, jsonObj, reverse)
{
    var image;
    var images = [];
    if (reverse) image = jsonObj.thumbs.pop();
    else         image = jsonObj.thumbs.shift();
    while (image) {
	var el = new Element('div', {'class': 'thumbnail'});
	var a  = new Element('a', {'href': image.href, 'class': 'lightbox', 'rel': 'gallery', 'title': image.title}).set('html',
			     '<img src="'+image.src+'" class="thumbimg">').injectInside(el);
	images.push(el);
	lightbox.addAnchor(a);
	if (reverse) image = jsonObj.thumbs.pop();
	else	     image = jsonObj.thumbs.shift();
    }
    images.each(function(img) {
//	img.set('opacity', 0.5);
	if (reverse) img.injectTop(thumbs);
	else	     img.inject(thumbs);
//	new Fx.Style(img, 'opacity').start(0.5,1);
//	img.get('opacity').start(0.5,1);
    });
}
var replace = function(jsonObj, reverse)
{
    if (!jsonObj) return;
    if (jsonObj.prev > 0) {
	$('prev').href = '?page='+jsonObj.prev;
	$('prev').set('html', '&lang;&lang;&lang;');
    } else {
	$('prev').href = '#';
	$('prev').set('html', '<font color="#eee">&lt;&lt;&lt;</font>');
    }
    if (jsonObj.next > 0) {
	$('next').href = '?page='+jsonObj.next;
	$('next').set('html', '&rang;&rang;&rang;');
    } else {
	$('next').href = '#';
	$('next').set('html', '');
    }
    $('results').set('html', 'Results '+jsonObj.start+'-'+jsonObj.last+' of '+jsonObj.total);
    $('dates').set('html', jsonObj.dates);
    var thumbs   = $('thumbs');
    var currImgs = $$('#thumbs .thumbnail');
    var calledProcess = false;
    currImgs.each(function(img) {
//	img.get('opacity').start(1,0.5).chain(function() {
	    img.dispose();
	    if (!calledProcess) {
		calledProcess = true;
		processList(thumbs, jsonObj, reverse);
	    }
//	});
    });
}
window.addEvent('domready', setup);
