setupGallery = function(container, options) { var gallery = Ojay(container), options = options || {}, galleryItems = gallery.descendants('.gallery-item').setStyle({opacity: 0}).hide(), current = galleryItems.at(0).setStyle({opacity: 1}).show(); var sequence = function() { var args = arguments; return function() { for (var i = 0, n = args.length; i < n; i += 1) args[i](); }; }; var index = 0, lock = false; var update = function(idx) { if (lock) return; var next = galleryItems.at(idx); lock = true; next.show().setStyle({zIndex: 4}) .animate({opacity: {to: 1}}, 1.5) ._(function() { current.hide().setStyle({opacity: 0}); next.setStyle({zIndex: 0}); current = next; index = idx; lock = false; }); }; var next = function() { if (lock) return; index = (index + 1) % galleryItems.length; update(index); }; var previous = function() { if (lock) return; index -= 1; if (index < 0) index = galleryItems.length - 1; update(index); }; var previousBtn = Ojay(Ojay.HTML.div({className: 'previous'}, 'Previous')), nextBtn = Ojay(Ojay.HTML.div({className: 'next'}, 'Next')); gallery.insert(previousBtn, 'after') .insert(nextBtn, 'after'); previousBtn.on('click', sequence(previous)); nextBtn.on('click', sequence(next)); }