/*
 * Created on 03.05.2011
 * Copyright (c) Andreas Bauer <andreas.bauer@creaktif.de>
 */

var _container;
var _timer;
var _delay = 3.0;
var _childWidth;
var _current = 1;
var _previous = 2;

function InitDivSliding(element, childWidth)
{
	_container = document.getElementById(element);
	_childWidth = childWidth;
	
	// Weitere Werte zurücksetzen
	_timer = null;
	_delay = 3.0;
	_current = 1;
	_previous = 2;
	
	MoveNth(_current);
	
	// Berechnet die Breite des darüber liegenden Div-Containers
	_container.style.width = childWidth * CountChilds() + "px";
}

function MoveNth(divNth)
{
	// Den Container mit den Childs an eine bestimmte Position bewegen
	var newPos = _childWidth * (divNth - 1);
	_container.style.left = -newPos + "px";
	
	_current = divNth;
}

function MoveNext()
{
	// Den Container mit den Childs nach links bewegen
	var curPos = parseInt(_container.style.left);
	var newPos = curPos - _childWidth;
	var count = CountChilds();
	
	if (isNaN(newPos))
	{
		curPos = 0;
		newPos = -_childWidth;
	}
	
	if (_current < count)
	{
		_previous = _current;
		_current++;
		
		MoveX(curPos, newPos, 12);
	}
}

function MoveBack()
{
	// Den Container mit den Childs nach rechts bewegen
	var curPos = parseInt(_container.style.left);
	var newPos = curPos + _childWidth;
	
	if (curPos < 0)
	{
		_previous = _current;
		_current--;
		
		MoveX(curPos, newPos, 12);
	}
}

function CountChilds()
{
	var i = 0;
	var ret = 0;
	var items = _container.childNodes.length;
	
	// Über alle Child Items iterieren und alle auf der nächsten Ebene
	// zusammen zählen und den Wert zurückgeben
	while (i < items)
	{
		if (_container.childNodes[i].nodeType != 3)
			ret++;
		
		i++;
	}
	
	return ret;
}

function MoveX(startPos, endPos, speed)
{
	// Bewege den Container solange die Schlussposition nicht erreicht ist
	var newPos = 0;
	if ((startPos > endPos && _current > _previous) || (startPos < endPos && _current < _previous))
	{
		if (_current < _previous)
			newPos = (startPos + speed);
		else
			newPos = (startPos - speed);
		
		_container.style.left = newPos + "px";
		_timer = setTimeout(function() { MoveX(parseInt(_container.style.left), endPos, speed); }, _delay);
	}
	else
	{
		// Den Timer beenden und löschen
		clearTimeout(_timer);

		// Am Tween-Ende muss der MovieClip exakt auf die Zielposition verschoben werden
		_container.style.left = endPos + "px";
	}
}
