﻿Type.registerNamespace('Pythagoras.CMS.Components');

Pythagoras.CMS.Components.ArticleRotator = function (element) {
	Pythagoras.CMS.Components.ArticleRotator.initializeBase(this, [element]);
	this._disposed = false;
	this._articles = null;
	this._interval = 5;

	this._content = null;
	this._currentItem = null;
	this._timer = null;
}

Pythagoras.CMS.Components.ArticleRotator.prototype = {

	initialize: function () {
		Pythagoras.CMS.Components.ArticleRotator.callBaseMethod(this, 'initialize');
		this._disposed = false;

		var wrapper = this.get_element();
		wrapper.className = 'articleRotator';

		if (this._articles.length == 0) {
			return;
		}

		var content = document.createElement('div');
		content.className = 'contentWrapper';
		wrapper.appendChild(content);
		this._content = content;
		this.setCurrentItem(this._articles[0]);
	},

	setCurrentItem: function (art) {
		this.stopTimer();

		this._currentItem = art;

		var previousContent = this._content.firstChild;

		var content = document.createElement('div');
		content.className = 'content';

		if (previousContent) {
			previousContent.style.display = "none";
			this._content.insertBefore(content, previousContent);
		} else {
			this._content.appendChild(content);
		}

		content.style.backgroundImage = 'url(\'' + art.ImageUrl + '\')';
		content.innerHTML =
			'<div class="body">' + art.Body + '</div>' +
			'<h1>' + art.Title + '</h1>' +
			'<div class="perex">' + art.Perex + '</div>';

		if (previousContent) {
			var fadeOut = new AjaxControlToolkit.Animation.FadeOutAnimation(previousContent, 0.5, 20, 0, 1);
			fadeOut.play();
			fadeOut.onEnd = function () { previousContent.parentNode.removeChild(previousContent); }
		}

		this._timer = window.setTimeout(Function.createDelegate(this, this.timerTick), this._interval * 1000);
	},

	timerTick: function () {
		var currentIndex = this._currentItem == null ? -1 : Array.indexOf(this._articles, this._currentItem);
		var newIndex =
			currentIndex + 1 >= this._articles.length ? 0 : currentIndex + 1;

		this.setCurrentItem(this._articles[newIndex]);
	},

	stopTimer: function () {
		if (this._timer != null) {
			window.clearTimeout(this._timer);
			this._timer = null;
		}
	},

	get_articles: function () {
		return this._articles;
	},

	set_articles: function (value) {
		this._articles = value;
	},

	get_interval: function () {
		return this._interval;
	},

	set_interval: function (value) {
		this._interval = value;
	},

	dispose: function () {
		if (this._disposed == true) {
			return;
		}

		this.stopTimer();

		Pythagoras.CMS.Components.ArticleRotator.callBaseMethod(this, 'dispose');

		this._disposed = true;
	}
}

Pythagoras.CMS.Components.ArticleRotator.registerClass('Pythagoras.CMS.Components.ArticleRotator', AjaxControlToolkit.ControlBase);

if (typeof (Sys) !== 'undefined') Sys.Application.notifyScriptLoaded();
