/**
 *
 * $Id: jquery.imagerotate.js 8312 2011-04-05 15:22:31Z josefzajac $
 * @author peter Vrba <phonkee@phonkee.eu>
 *
 * ImageRotate plugin for jQuery
 */
(function($)
{
    var ImageRotate = function(element, interval)
    {
        this.elem           = $(element);
        this.obj            = this;
        this.images         = [];
        this.index          = 0;
        this.intervalHandle = null;
        this.interval       = interval;

        this.addImage = function(image)
        {
            this.images.push(image);
            i       = new Image();
            i.src   = image;
        };

        this.setInterval = function(interval)
        {
            this.timeout = interval;
        };

        this.start = function()
        {
            if (this.intervalHandle != null)
            {
                return false;
            }
            var self = this;
            this.changeImage();
            this.intervalHandle = setInterval(function() {
                self.changeImage.apply(self);
            }, self.interval);

            return true;
        };

        this.stop = function()
        {
            clearInterval(this.intervalHandle);
            this.intervalHandle = null;
        };

        this.next = function()
        {
            if(this.intervalHandle != null)
            {
                this.stop();
                this.changeImage();
                this.start();
            }
            else
            {
                this.changeImage();
            }
        };

        this.setIndex = function(index)
        {
            if (index < this.images.length)
            {
                this.index = index;
            }
        }

        this.changeImage = function()
        {
            for(i = 0; i< this.images.length; i++)
                this.images[i].fadeOut(500);
            $('#rotate_1 a').eq(this.index).fadeIn(500);

            this.index += 1;
            if (this.index >= this.images.length)
            {
                this.index = 0;
            }
        }
    };

    $.fn.ImageRotate = function(interval)
    {
        return this.each(function()
        {
            var element = $(this);
            if (element.data('ImageRotate')) return;
            var imageRotate = new ImageRotate(this, interval);
            element.data('ImageRotate', imageRotate);
        });
    };
})(jQuery);

