/*
Developed by Kyle Somogyi
*/
function fade(_so)
{
	var me = this;
	
	me.so = _so;
	me.mc = $(me.so.mainElement);
	me.imc = $(me.so.mainElement).children().not('button');
	me.ia = [];
	me.ci = 0;
	me.z_index = 10;
	me.deferClick = false;

	var tE = me.imc.children(),
		j = tE.length - 1;
	do
	{
		$(tE[j]).attr('shiftrIndex', j).css('z-index', me.z_index);
		me.z_index++;
	} while(j--);

	// Manually set styles
	me.mc.css(
	{
		'overflow': 'hidden',
		'position': 'relative'
	});
	me.imc.css(
	{
		'position': 'absolute',
		'top': '0px',
		'left': '0px'
	});
	me.imc.children().css(
	{
		'position': 'absolute',
		'top': '0px',
		'left': '0px'
	});
}
fade.prototype.next = function()
{
	var me = this,
		imc = me.imc;
	
	if(me.deferClick != true)
	{
		imc.children().stop(true, true);
		imc.find(':first').stop(true, true).animate(
		{
			'opacity': 0
		}, function()
		{
			imc.find(':first').detach().appendTo(imc);
			imc.children().last().css('opacity', 1);
			me.ci = imc.find(':first').attr('shiftrIndex');

			me.reIndex();
		});
	}
};
fade.prototype.prev = function()
{
	var me = this,
		imc = me.imc;

	if(me.deferClick != true)
	{
		imc.children().stop(true, true).last().css('opacity', 0).detach().prependTo(imc);
		me.reIndex();
		imc.find(':first').stop(true, true).animate(
		{
			'opacity': 1
		}, function()
		{
			me.ci = imc.find(':first').attr('shiftrIndex');
		});
	}
};
fade.prototype.reIndex = function()
{
	var me = this,
		tE = me.imc.children(),
		j = tE.length;

	me.z_index = 0;
	do
	{
		$(tE[j]).css({'z-index': me.z_index});
		me.z_index++;
	} while(j--);
};
fade.prototype.reIndexWithOpacity = function()
{
	var me = this,
		tE = me.imc.children(),
		j = tE.length;

	me.z_index = 0;
	do
	{
		$(tE[j]).css({'z-index': me.z_index, 'opacity': 1});
		me.z_index++;
	} while(j--);
};
fade.prototype.scrollTo = function(sIndex)
{
	var me = this,
		fin = false,
		imc = me.imc,
		tE = imc.children();
	
	if($(tE[0]).attr('shiftrIndex') != sIndex)
	{
		$nx = me.getByIndex(sIndex);
		$nx.detach();
		$nx.insertAfter($(tE[0]));
		me.reIndexWithOpacity();

		imc.children().stop(true, true);
		imc.find(':first').stop(true, true).animate(
		{
			'opacity': 0
		}, function()
		{
			me.ci = imc.find(':first').attr('shiftrIndex');

			me.reShuffle(sIndex);
		});
	}
};
fade.prototype.getByIndex = function(index)
{
	var me = this,
		tE = me.imc.children(),
		j = tE.length,
		ret = undefined;

	do
	{
		if($(tE[j]).attr('shiftrindex') == index)
		{
			ret = $(tE[j]);
			break;
		}
	} while(j--);

	return ret;
};
fade.prototype.reShuffle = function(start)
{
	var me = this,
		tE = me.imc.children(),
		j = tE.length-1,
		v = parseInt(start)+1;
	$pE = me.getByIndex(start);
	
	while(v != start)
	{
		$nx = me.getByIndex(v);
		$nx.insertAfter($pE);
		$pE = $nx;
		if(v < j)
			v++;
		else
			v = 0;
	}

	me.reIndexWithOpacity();
};
