That script looks rather convoluted.
On first glance, I'd say you may have to initialise i again when you use that routine a second or third time.
Alternatively, turn it into a separate javascript, e.g. slideshow.js that you can call up, using different sets of pictures.