Refactored version based on blueimp Gallery.