// Copyright (c) 2006 - 2007 Global Relay Communications, Inc. All Rights Reserved.
function rotator() {
    this.interval = 3500;

    var images_index = 0;
    var images = new Array();

    var start = true;
    var index = 0;

    function callRotate(eleId, last) {
        this.rotateImage(eleId, last);
    }

    function firstImage() {
        index = randomNumber(0, images_index - 1);
	    return images[index];
    }

    function imageLoaded(img) {
        if (!img.complete) {
            return false;
        } else if (typeof img.naturalWidth != "undefined" && img.naturalWidth == 0) {
            return false;
        } else {
            return true;
        }
    }

    function newImage(src) {
        var img = new Image();
        img.src = src;
        return img;
    }

    function nextImage() {
        index++;
        if (index > images_index - 1) {
            index = 0;
        }
	    return images[index];
    }

    function randomNumber(x, y) {
	    var range = y - x + 1;
	    return Math.floor(Math.random() * range) + x;
    }    

    this.addImage = function addImage(url) {
        images[images_index++] = newImage(url);
    }

    this.rotateImage = function rotateImage(eleId, last) {
        var me = this;

        var img = document.getElementById(eleId);    
        if (start) {
            var nxt = firstImage();
            start = false;
        } else {
            var nxt = nextImage();
            $(img).hide();
        }
        if (imageLoaded(nxt)) {
            img.width = nxt.width;
            img.height = nxt.height;
            img.src = nxt.src;
            $(img).fadeIn(250);//(this.interval);
        }
        setTimeout(function () { me.rotateImage(eleId, last); }, this.interval);
    }
}