﻿function Banner(name) {
	this.ObjectName = name;
	this.NumberOfBanners = 0;
	this.CurrentIndex = 0,
	this.TargetElement = null;
	this.TextElement = null;
	this.Options = null;
	this.Width = 0;
	this.ActiveBanner = null;
}

Banner.prototype.Init = function (options, targetId) {
	this.TargetElement = $('#' + targetId);
	this.TextElement = $('#' + targetId + " #text");

	this.Options = options;
	this.NumberOfBanners = $(this.TargetElement).children().size();

	this.Width = $(this.TargetElement).width();

	this.ActiveBanner = $("#slides").children()[this.CurrentIndex];
	this.BeginStoryboardAnimate(options.BeginTime);
}

Banner.prototype.ClearAllTimeouts = function () {
	window.clearTimeout(this.TextOutTimeoutID);
	window.clearTimeout(this.TextInTimeoutID);
	window.clearTimeout(this.AnimateTimeoutID);
}

Banner.prototype.BeginStoryboardAnimate = function (timeOut) {
	this.ClearAllTimeouts();
	this.AnimateTimeoutID = window.setTimeout(this.ObjectName + ".Animate()", timeOut);
}

Banner.prototype.BeginStoryboardTextIn = function (timeOut) {
	this.ClearAllTimeouts();
	this.TextInTimeoutID = window.setTimeout(this.ObjectName + ".TextIn()", timeOut);
}

Banner.prototype.BeginStoryboardTextOut = function (timeOut) {
	this.ClearAllTimeouts();
	this.TextOutTimeoutID = window.setTimeout(this.ObjectName + ".TextOut()", timeOut);
}

Banner.prototype.TextIn = function () {
	var banner = this;

	$(this.TextElement).animate({ left: "0px" }, 1500, function () {
		banner.BeginStoryboardTextOut(banner.Options.WaitTime);
	});
}

Banner.prototype.TextOut = function () {
	var banner = this;

	$(this.TextElement).animate({ left: this.Width + "px" }, 1500, function () {
		banner.BeginStoryboardAnimate(1500);
	});
}

Banner.prototype.Animate = function () {
	this.Next(false);
}

Banner.prototype.Next = function (reset) {
	var index = this.CurrentIndex;

	if (reset)
		$(this.TextElement).css({ left: this.Width + "px" });

	if (index < this.NumberOfBanners - 1)
		index++;
	else
		index = 0;

	this.Goto(index);
}

Banner.prototype.Previous = function (reset) {
	var index = this.CurrentIndex;

	if (reset)
		$(this.TextElement).css({ left: this.Width + "px" });

	if (index > 0)
		index--;
	else
		index = this.NumberOfBanners - 1;

	this.Goto(index);
}

Banner.prototype.Goto = function (index) {
	var banner = this,
		active,
		next;

	if (index >= 0 && index < this.NumberOfBanners) {
		this.ClearAllTimeouts();

		active = this.ActiveBanner;
		next = $("#slides").children()[index];

		$(active).animate({ opacity: 0 }, 1500);
		$(next).animate({ opacity: 1.0 }, 1500, function () {
			banner.BeginStoryboardTextIn(1500);
		});
		this.ActiveBanner = next;
		this.CurrentIndex = index;
	}
}
