/*
 * Usage:
 *
 * var rotator = null;
 * jQuery(document).ready(function() {
 *     rotator = new ImageRotator('#HomeColumnRight img', '.slideshowStatusBar .slideshowItem');
 * });
 *
 */

var rotator = null;
jQuery(document).ready(function() {
        rotator = new ImageRotator('.slideshow');
});


function ImageRotator(imageSelector, statusSelector) {
    var _this = this;

    this.init = function(imageSelector, statusSelector) {
        this.images = jQuery(imageSelector);
        this.statusIcons = jQuery(statusSelector);

        this.currentImage = 0;

        this.autoRotateSpeed = 5000;
        this.interval = null;
        if (this.images.length) {
            this.addEventListeners();
            this.autoRotate();
        }
    }
	


    this.addEventListeners = function() {
        this.statusIcons.each(function(i) {
            jQuery(this).click(function(event) {
                _this.switchImage(i);
                if (_this.interval != null) {
                    clearInterval(_this.interval);
                }
            });
        });
    }



    this.switchImage = function(index) {
        if (index != this.currentImage) {
            jQuery(this.images.get(this.currentImage)).fadeOut(1600);
            jQuery(this.statusIcons.get(this.currentImage)).removeClass('selected');

            this.currentImage = index;

            jQuery(this.images.get(this.currentImage)).fadeIn(1600);
            jQuery(this.statusIcons.get(this.currentImage)).addClass('selected');
        }
    }



    this.autoRotate = function() {
        this.interval = setInterval(function() {
            var nextImage = _this.currentImage + 1;
            if (nextImage == _this.images.length) {
                nextImage = 0;
            }
            _this.switchImage(nextImage);
        }, this.autoRotateSpeed);
    }



    this.init(imageSelector, statusSelector);

}