Emotion = {};

Emotion.init = function ()
{
	Emotion._enabled = true;
	Emotion.sx = -1;
	Emotion.sy = -1;
	Emotion.cx = 0;
	Emotion.cy = 0;

	Emotion.sens = 5;

	Emotion.layers = [
		{
			"lay" : $( "site-img05" ),
			"x" : -100,
			"speed" : 1,
			"skew" : -2 
		},
		{ 
			"lay" : $( "site-img04" ),
			"x" : -100,
			"speed" : 1.5,
			"skew" : 0
		},
		{
			"lay" : $( "site-img03" ),
			"x" : 160,
			"speed" : 2,
			"skew" : 0
		},
		{
			"lay" : $( "site-img02" ),
			"x" : -100,
			"speed" : 2.5,
			"skew" :15 
		},
		{
			"lay" : $( "site-img01" ),
			"x" : -200,
			"speed" : 3.5,
			"skew" : 0
		}
	];

	Emotion.layers.iterate ( function ( l )
	{
		l [ 'lay' ].style.left = l [ 'x' ] + "px";
		l [ 'x' ] = 0;
		l [ 'sx' ] = 0;
	} );
};

Emotion.set_enabled = function ( val )
{
	Emotion._enabled = val ;
};

Emotion._mousemove = function ( e )
{
	e.stopPropagation ();

	if ( Emotion.sx == -1 )
	{
		Emotion.sx = e.clientX;
		Emotion.sy = e.clientY;
	}

	Emotion.cx = e.clientX;
	Emotion.cy = e.clientY;

	var dx = ( Emotion.sx - Emotion.cx ) / 5;
	var dy = ( Emotion.sy - Emotion.cy ) / 5;

	Emotion._calc_layers ( dx, dy );
};

Emotion._mouseout = function ( ev )
{
	if ( ev ) 
	{
		if ( Emotion._is_child_of ( ev.currentTarget, ev.relatedTarget ) )
			return false;
	}
	Emotion.sx = -1;
};

Emotion._calc_layers = function ( dx, dy )
{
	var sx, dct, style;
	dx = dx / Emotion.sens;

	Emotion.layers.iterate ( function ( l )
	{
		l [ 'x' ] = l [ 'sx' ] + ( l [ 'speed' ] * dx );
		sx = l [ 'skew' ];
		if ( dx > 0 )
			sx = Math.min ( ( sx * dx ) / 25, 20 );
		else
			sx = Math.max ( ( sx * dx ) / 25, -20 );
		

		dct = { translate: [ l [ 'x' ], 0 ] };

		if ( sx ) dct [ 'skew' ] = [ sx, 0 ];
		
		// console.debug ( sx );
		liwe.fx.animate ( l [ 'lay' ], dct, null, 0, "default" );
	} );
};

Emotion._tilt = function ( e )
{
	if ( ! Emotion._enabled ) return;
	var dx;

	if ( touch.get_orientation () == "landscape" )
		dx = e.accelerationIncludingGravity.y;
	else
		dx = e.accelerationIncludingGravity.x;

	if ( Math.abs ( Emotion._tilt.dx - dx ) < 0.07 ) return;

	Emotion._calc_layers ( dx * 25, 0 );
	Emotion._tilt.dx = dx;

	// $( "x", dx );
};

Emotion._is_child_of = function ( parent, child )
{
	if( child != null )
	{			
		while( child.parentNode )
		{
			if( ( child = child.parentNode ) == parent )
			{
				return true;
			}
		}
	}
	return false;
}

