long method in scripts/gallery.js refactored