/**
 * Maciej Lebkowski. Creative Commons - Attribution - Share Alike - Non Commercial 3.0
 * http://uxpatterns.pl
 **/

(function () {

	var nlScript = document.getElementsByTagName('script'), s = nlScript[nlScript.length-1];
	var c = eval(s.innerHTML);


	var sInitStyles = {
		position: 'relative',
		overflow: 'hidden'
	}
	if (c.height) sInitStyles.height = c.height;
	if (c.width)  sInitStyles.width  = c.width;

	c.animationTime = parseInt(({
		'slow': 100,
		'normal': 30,
		'fast': 2
	})[c.animationTime])||30;
	

	while ((s = s.previousSibling) && !s.tagName); 
	var nlElements = [];
	for(var e = s.firstChild; e; e = e.nextSibling) {
		if (e.tagName) {
			nlElements.push(e);
			e.style.position = ['relative', 'absolute'][1];
			e.style.left= '-1000px';
		}
	}

	c.start = parseInt(c.start) || 0;
	var mo, cur, prev = nlElements[c.start%nlElements.length];

	s.onmouseover = function () { mo = true; }
	s.onmouseout = function () { mo = false; }

	
	for (var i in sInitStyles) s.style[i] = sInitStyles[i];

	var activate = function (num, fast) {
		num = num % nlElements.length;
		var percent = fast ? 100 : 0, e = nlElements[num];
		
		var trans = {};
		if (!c.height) trans.height = [s.clientHeight, e.clientHeight, 'px', 2];
		if (!c.width)  trans.width  = [s.clientWidth,  e.clientWidth, 'px', 2];
		switch (c.slideEffect) {
			case 'horizontal': trans.left = [s.clientWidth, 0, 'px', 1]; break;
			case 'vertical': trans.top = [s.clientHeight, 0, 'px', 1]; break;
			case 'fade': trans.opacity = [0, 1, '', 1];
		}
		for(var i = 0; i < nlElements.length; i++) {
			nlElements[i].style.zIndex = Math.max(0, parseInt(nlElements[i].style.zIndex-1));
		}
		prev=cur;
		cur = e;
		cur.style.left = 0;


		setTimeout(function () {
			var val, m;
			for (var i in trans) {
				val = trans[i][0] + (trans[i][1] - trans[i][0]) * percent / 100;
				m = trans[i][2] || '';
//				console.log(i + ": " + val + m);
				if (trans[i][3] & 1) cur.style[i] = val + m;
				if (trans[i][3] & 2) s.style[i] = val + m;
				if (i == 'top') if (prev) prev.style.top = val - prev.clientHeight + m;
				if (i == 'left') if (prev) prev.style.left = val - prev.clientWidth + m;
				cur.style.zIndex = nlElements.length;
			}

			if (percent < 100) setTimeout(arguments.callee, c.animationTime);
			else if (prev) prev.style.left = '-1000px';
			percent = Math.min(100, percent + 10);
		}, fast ? 0 : c.animationTime);
	}
	activate(c.start, true);

	setInterval(function () {
		mo || activate(++c.start);
	}, c.time * 1000);


})();
