var g_viewer;
function update()
{
    g_viewer.update();
}

function setupViewer()
{
    g_debug = document.getElementById("debug");
    var viewerObj = new Viewer();
    viewerObj.element = document.getElementById("imageviewer");
    viewerObj.count = 8;
    viewerObj.start();
    g_viewer = viewerObj;
}

function Viewer()
{
    this.element = null;
    this.img = null;
    this.path = "";
    this.count = 0;
    this.current = 0;
    this.state = 0;
    this.t = 0;
    this.fadeFrames = 10;

    this.start = function()
    {
        this.t = 0;
        this.img = this.getImageForIndex(0);
        this.img.style.display = "";
        this.img.style.opacity = 1;
        setInterval(update, 100);
    }
    this.stop = function()
    {
    }
    this.update = function()
    {
        this.t++;

		if (this.state == 0)
		{
			if (this.t > 40)
			{
				// fade out
				// 
	        	this.img.style.opacity = 1-(this.t-40)/this.fadeFrames;
				if (this.t >= 40+this.fadeFrames)
				{
					this.img.style.display = "none";
					this.img = this.getImageForIndex(this.current);

					this.state = 1;
		            this.current++;
		            if (this.current >= this.count)
		                this.current = 0;

					this.img = this.getImageForIndex(this.current);
					this.img.style.display = "";
					this.img.style.opacity = 0;
		            this.t = 0;
		            return;
				}
			}
		}
		else if (this.state == 1)
		{
			// fade in
			this.img.style.opacity = this.t/this.fadeFrames;
			if (this.t >= this.fadeFrames)
			{
				this.state = 0;
				this.t = 0;
			}
		}
    }
    this.getImageForIndex = function(index)
    {
    	var curElem = this.element.firstChild;
    	var curIndex = 0;
    	while (curElem != null)
    	{
    		if (curElem.tagName == "IMG" || curElem.tagName == "A")
    		{
				if (curIndex == index)
				{
					if (curElem.tagName == "A")
						curElem = curElem.firstChild;
				
					break;
				}
    			curIndex++;
    		}
    		curElem = curElem.nextSibling;
    	}
        return curElem;
    }
    return this;
}

