/* slideshow.js
 * Controller for Javascript-only image slide show
 * Depends on: jQuery 1.3.2
 * Copyright 2009 Jason Stitt. All rights reserved.
 */
 
/* Create the DOM elements for a slide show as the last child of parentElement,
 * start preloading the images in imageUrls, and display the first.
 */
function SlideShow(parentElement, imageUrls, delay) {
    /* DOM element setup */
    var obj = this;
    this.root = $('<div>').addClass('jss-slideshow');
    this.control = $('<div>').addClass('jss-slideshow-control');
    this.imgContainer = $('<div>').addClass('jss-slideshow-pic');
    this.startStopBtn = textBtn('Start slideshow', function() {
        obj.toggle();
        return false;
    });
    this.prevBtn = textBtn('Prev', function() {
        obj.prev();
        obj.stop();
        return false;
    });
    this.nextBtn = textBtn('Next', function() {
        obj.next();
        obj.stop();
        return false;
    });
    this.placeDisp = $('<span>');
    this.control.append(this.startStopBtn);
    this.control.append(this.prevBtn);
    this.control.append(this.placeDisp);
    this.control.append(this.nextBtn);
    this.imgContainer.append($('<img>'));
    this.root.append(this.control);
    this.root.append(this.imgContainer);
    
    
    /* Internal setup */
    this.images = new Array();
    this.index = 0;
    this.delay = delay;
    this.running = false;
    this.timer = null;
    for(i = 0; i < imageUrls.length; i++) {
        this.images.push($('<img>').attr('src', imageUrls[i]));
    }
    parentElement.append(this.root);
}

SlideShow.prototype.next = function() {
    if(0 < this.images.length) {
        this.index = (this.index + 1) % this.images.length;
        this.update();
    }
};

SlideShow.prototype.prev = function() {
    if(0 < this.images.length) {
        this.index--;
        if(0 > this.index) {
            this.index = this.images.length - 1;
        }
        this.update();
    }
};

SlideShow.prototype.update = function() {
    if(-1 < this.index && this.index < this.images.length) {
        this.imgContainer.children('img').replaceWith(this.images[this.index]);
        this.placeDisp.text('' + (this.index + 1) + ' of ' + this.images.length);
    }
};

SlideShow.prototype.run = function() {
    this.stop();
    obj = this;
    this.startStopBtn.text('Stop slideshow');
    this.timer = window.setInterval(function() {
        obj.next();
    }, this.delay);
};

SlideShow.prototype.stop = function() {  
    if(this.timer) {
        window.clearInterval(this.timer);
        this.timer = null;
        this.startStopBtn.text('Start slideshow');
    }
};

SlideShow.prototype.toggle = function() {
    if(this.timer) {
        this.stop();
        return 0;
    } else {
        this.run();
        return 1;
    }
};

function textBtn(text, func) {
    return $('<a>').attr('href', '#').text(text).bind('click', func);
};
