//window.addEventListener ? window.addEventListener('load', img_fade_init, false) : window.attachEvent('onload', img_fade_init);

var d=document, imgs = new Array(), zInterval = null, fadingTime = 2000, sequenceInterval = 6000, current=0, pause=false;
var fromIndex, toIndex, sequenceIndex = -1;

function img_fade_init()
{
	if(!d.getElementById || !d.createElement)
        return;

    imgs = d.getElementById("imageContainer").getElementsByTagName("img");

    for(i = 0; i < 3; i++)
    {
	    imgs[i].style.display = "block";
    	imgs[i].xOpacity = .99;
    }

    for(i = 3; i < 9; i++)
    	imgs[i].xOpacity = 0;

    anim_sequence();
}

function anim_sequence()
{
    var s = new Array();

    s.push(new Array(1, 4));
    s.push(new Array(2, 5));
    s.push(new Array(3, 6));
    s.push(new Array(4, 7));
    s.push(new Array(5, 8));
    s.push(new Array(6, 9));
    s.push(new Array(7, 1));
    s.push(new Array(8, 2));
    s.push(new Array(9, 3));

    if(sequenceIndex > -1)
        img_swap(s[sequenceIndex][0], s[sequenceIndex][1]);

    if(sequenceIndex < s.length - 1)
        sequenceIndex ++;
    else
        sequenceIndex = 0;

    setTimeout(anim_sequence, sequenceInterval);
}

function img_fade_start()
{
	if(!d.getElementById || !d.createElement)
        return;

	setTimeout(img_fade,fadingTime);
}

function img_swap(from, to)
{
    fromIndex = from - 1;
    toIndex = to - 1;
    current = fromIndex;
    img_fade();
}

function img_fade()
{
	cOpacity = imgs[current].xOpacity;

    //next index
    nIndex = current == fromIndex ? toIndex : fromIndex;

	nOpacity = imgs[nIndex].xOpacity;

	cOpacity-=.05;
	nOpacity+=.05;

	imgs[nIndex].style.display = "block";
	imgs[current].xOpacity = cOpacity;
	imgs[nIndex].xOpacity = nOpacity;

	setOpacity(imgs[current]);
	setOpacity(imgs[nIndex]);

	if(cOpacity<=0)
    {
		imgs[current].style.display = "none";
		current = nIndex;
	}
    else
		setTimeout(img_fade,50);
}

function setOpacity(obj)
{
    if(obj.xOpacity>.99)
    {
	    obj.xOpacity = .99;
    	return;
    }

    obj.style.opacity = obj.xOpacity;
    obj.style.MozOpacity = obj.xOpacity;
    obj.style.filter = "alpha(opacity=" + (obj.xOpacity*100) + ")";
}
