
require ('./transitions.css');
var VnNode = require ('./node');

var transition = checkTransitions ();

module.exports = {
	transition: transition,
	slide: slide,
	move: move
};

/**
 * Checks for transition support.
 * 
 * @return {String} The transition end event name, or %null if no support
 */
function checkTransitions ()
{
	var el = document.createElement ('div');
	var transitionEndNames = {
		 transition       : 'transitionend'
		,OTransition      : 'oTransitionEnd'
		,MozTransition    : 'transitionend'
		,WebkitTransition : 'webkitTransitionEnd'
	};

	for (var name in transitionEndNames)
	if (el.style[name] !== undefined)
		return transitionEndNames[name];

	return null;
}

/**
 * Slides an element.
 * 
 * @param {Node} node The element to slide
 * @param {String} way The slide way: 'left' or 'right'
 * @param {Function} cb The callback to call when transition ends
 */
function slide (node, way, cb)
{
	if (transition === null)
	{
		if (cb) cb();
		return;
	}

	var inverseWay = way == 'left' ? 'right' : 'left';

	VnNode.addClass (node, 'slide slide-'+ way);
	node.addEventListener (transition, slideStart);

	function slideStart ()
	{
		node.removeEventListener (transition, slideStart);
		VnNode.removeClass (node, 'slide');
		VnNode.removeClass (node, 'slide-'+ way);
		VnNode.addClass (node, 'slide-'+ inverseWay);
		cb ();
		setTimeout (slideReturn, 20);
	}

	function slideReturn ()
	{
		VnNode.addClass (node, 'slide');
		VnNode.removeClass (node, 'slide-'+ inverseWay);
		node.addEventListener (transition, slideEnd);
	}

	function slideEnd ()
	{
		node.removeEventListener (transition, slideEnd);
		VnNode.removeClass (node, 'slide');
	}
}

/**
 * Moves an element.
 * 
 * @param {Node} node The element to move
 */
function move (node)
{
	if (transition === null)
		return;

	Vn.Node.addClass (node, 'move-start');
	setTimeout (slideTimeout, 20);

	function slideTimeout ()
	{
		Vn.Node.removeClass (node, 'move-start');
		Vn.Node.addClass (node, 'move-end move');
		node.addEventListener ('transitionend', onTransitionEnd);
	}

	function onTransitionEnd ()
	{
		Vn.Node.removeClass (node, 'move-end');
		Vn.Node.removeClass (node, 'move');
	}
}
