﻿function ImageRotator()
{
    //images used in rotation.
    this.images = new Array();
    //killswitch
    this.rotationStarted = false;
    //current position in the image list
    this.currentImage = 0;
    //target container
    this.target = null;
    //animation speed
    this.fadeSpeed="fast";
}

//starts the image rotation. This must be called first.
ImageRotator.prototype.startRotation = function(target, images, interval)
{
    //can't restart rotation
    if (!this.rotationStarted)
    {
        var nextImg=this.nextImage;   
        //set our target jquery object
        this.target=target;
        //sort the images randomly.
        this.images = this.shuffle(images);
        //set killswitch
        this.rotationStarted=true;
        //show the first image
        this.showNextImage();
        //fire off rotation
        var ir = this;
        //start image rotation
        setInterval(function() { ir.showNextImage(); }, interval);
    }  
}

//Shows the next image.
ImageRotator.prototype.showNextImage=function()
{
    if (!this.rotationStarted)
    {
        throw "Rotation must be started by calling startRotation(jquery, array, int);";
    }
    //make sure we don't go past the bounds of our images array
    if (this.currentImage + 1 > this.images.length)
    {
        //cycle back to zero
        this.currentImage = 0;
    }
    var ir=this;
    this.target.fadeOut(this.fadeSpeed,
    function()
    {
        ir.target.html(ir.images[ir.currentImage++].getImageText());
        ir.target.fadeIn(ir.fadeSpeed);
    });
}

//shuffles a given array.
ImageRotator.prototype.shuffle=function(o)
{
    for(var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
	return o;
}

//data object for our rotating images
function ImageData(url, altText, link)
{
    this.url=url;
    this.altText=altText;
    this.link=link;
}

//returns a html serialied version of this image data.
ImageData.prototype.getImageText = function()
{
    var ret='<a href="_LINK_" target="_blank"><img src="_URL_" alt="_ALT_" /></a>';
    ret = ret.replace("_LINK_", this.link);
    ret = ret.replace("_URL_", this.url);
    ret = ret.replace("_ALT_", this.altText);
    return ret;
}