﻿
// These namespaces are declared in Core.js
if (!KSLaw || !KSLaw.Internet || !KSLaw.Internet.Core)
	throw new Error("Some of the expected KSLaw namespaces were not registered");

KSLaw.Internet.Slider = { Control: {}, Arrow: {} };

KSLaw.Internet.Slider.Arrow = function(i, r, c)
{
	this.idle = i;
	this.roll = r;
	this.cssClass = c;
};
KSLaw.Internet.Slider.Control = function()
{
	var current, worker = null, that, elements, left, right, w, l;
	var ATTR = "sliderArrow";

	this.init = function(container, leftArrow, rightArrow, wait, length)
	{
		if(!container.childNodes || container.childNodes.length == 0)return;
		w = wait; l = length;
		elements = [];
		for (var i in container.childNodes)
			if (container.childNodes[i].tagName)
				elements.push(container.childNodes[i]);
		current = 0;
		that = this;
		left = add(container, leftArrow);
		right = add(container, rightArrow);
		container.onmouseover = container.onmouseout = function(e)
		{
			left.style.display = left.style.display == "none" ? "" : "none";
			right.style.display = right.style.display == "none" ? "" : "none";
		};
		that.next();
	};
	this.next = function()
	{
		stop();
		$('#' + extract().id).fadeOut(l);
		if (++current > elements.length - 1) current = 0;
		$('#' + extract().id).fadeIn(l, function() { subscribe(); });
		start();
	};
	this.prev = function()
	{
		stop();
		$('#' + extract().id).fadeOut(l);
		if (--current < 0) current = elements.length - 1;
		$('#' + extract().id).fadeIn(l, function() { subscribe(); });
		start();
	};

	var start = function()
	{
		try { worker = window.setInterval(that.next, w); }
		catch (e) { };
	};
	var stop = function()
	{
		try { window.clearInterval(worker); }
		catch (e) { };
		disable();
	};
	var add = function(container, arrow)
	{
		var img = document.createElement("IMG");
		img.setAttribute(ATTR,arrow.roll);
		img.src = arrow.idle;
		img.className = arrow.cssClass;
		container.appendChild(img);
		img.style.display = "none";
		img.onmouseover = function(e){roll(this);};
		img.onmouseout = function(e){roll(this);};
		return img;
	};
	var roll = function(img)
	{
		var u = img.src;
		img.src = img.getAttribute(ATTR);
		img.setAttribute(ATTR,u);
	};
	var subscribe = function()
	{
		left.onclick = function(e) { that.prev(); };
		right.onclick = function(e) { that.next(); };
	};
	var disable = function()
	{
		worker = null;
		left.onclick = right.onclick = null;
	};
	var extract = function()
	{
		var el = elements[current];
		return el.tagName && el.tagName == "A" ? KSLaw.Internet.Core.getChildrenByTagName(el, "IMG", false)[0] : el;
	};
};
