﻿//Root level javascript namespace
TicketingHelper.Rotator = function (timeToKeepItemActive) {
	var itemActiveTime = timeToKeepItemActive;
	var currentItemIndex = 0;
	var nextRotateTimeout = null;
	var itemActiveTime = timeToKeepItemActive;
	var itemsRotateRef = new Array();
	var isRotatingPaused = false;
	//this'll set a container element where we can generate the nav items
	var navItemsElementRef;


	this.addItemToRotate = function (itemId) {
		this.addItemToRotateByRef($get(itemId));
	}


	this.addItemToRotateByRef = function (itemRef) {
		itemsRotateRef.push(itemRef);

		itemRef.style.display = "none";

		itemRef.onmouseover = pauseRotating;
		itemRef.onmouseout = resumeRotating;
	}

	this.setNavItemsElementRef = function (elementId, floatDirection) {
		navItemsElementRef = $get(elementId);

		if (floatDirection.toLowerCase() == "left") {
			for (var i = 0; i < itemsRotateRef.length; i++) {
				createNavItem(i);
			}
		}
		else //its floating right
		{
			for (var i = itemsRotateRef.length - 1; i >= 0; i--) {
				createNavItem(i);
			}
		}
	}

	function createNavItem(index) {

		var className = (index == currentItemIndex) ? "SelectedRotatedNavItem" : "RotatedNavItem";

		var navItem = document.createElement("div");

		var classAtt = document.createAttribute("class");
		classAtt.value = className;
		navItem.setAttributeNode(classAtt);

		//set this up so that the event handler knows which index
		navItem.itemIndex = index;

		$addHandler(navItem, "click", doOnNavItemClick);

		navItemsElementRef.appendChild(navItem);
	}


	function doOnNavItemClick(domEvent) {
		rotateInternal(domEvent.target.itemIndex);
	}

	function goToNextItem() {
		var nextItemIndex = currentItemIndex + 1;
		if (nextItemIndex > itemsRotateRef.length - 1)
			nextItemIndex = 0;

		rotateInternal(nextItemIndex);
	}


	function rotateInternal(newIndex) {

		clearTimeout(nextRotateTimeout);

		itemsRotateRef[currentItemIndex].style.display = "none";

		currentItemIndex = newIndex;
		itemsRotateRef[newIndex].style.display = "block";

		if (navItemsElementRef != undefined) {
			for (var i = 0; i < navItemsElementRef.childNodes.length; i++) {
				var childNavItem = navItemsElementRef.childNodes.item(i);
				var className = (childNavItem.itemIndex == currentItemIndex) ? "SelectedRotatedNavItem" : "RotatedNavItem";
				childNavItem.className = className;
			}
		}

		if (!isRotatingPaused)
			nextRotateTimeout = setTimeout(goToNextItem, itemActiveTime);
	}



	function pauseRotating() {
		isRotatingPaused = true;
		clearTimeout(nextRotateTimeout);
	}

	function resumeRotating() {
		isRotatingPaused = false;
		nextRotateTimeout = setTimeout(goToNextItem, itemActiveTime);
	}


	//expose this to the outside world
	this.doRotate = rotateInternal;
}






