﻿/*
	* Version: 0.2 11/6/2010
	* Copyright (c) 2011 Webtimisten (www.webtimisten.dk), Benjamin Ravn
	* Requires: min. jQuery v1.4.4
*/

(function ($) {
	$.fn.newsticker = function () {
		var _newsTicker = $(this);
		var _iNewsTickerWidth = _newsTicker.width();
		_newsTicker.width(_iNewsTickerWidth);
		var _iNewsItemTextWidth = 0;
		var _iNewsItems = -1;
		var _newsItem = null;

		var nextNews = function () {
			_newsItem.fadeOut(1000, function () {
				if (_iNewsItems > 1) {
					_newsItem = _newsItem.next();
					_newsTicker.find("div:last").after(_newsTicker.find("div:first"));
				}

				showNewsItem();
			});
		}

		var showNewsItem = function () {
			_newsItem.css("left", 0);

			_newsItem.fadeIn(1000, function () {
				_iNewsItemTextWidth = _newsItem.find("span").width();

				if (_iNewsItemTextWidth > _iNewsTickerWidth) {
					setTimeout(function () {
						var iDiff = _iNewsItemTextWidth - _iNewsTickerWidth;
						_newsItem.animate({ left: -iDiff }, iDiff * 10, "linear", function () {
							setTimeout(function () { nextNews() }, 2000);
						});
					}, 2000);
				}
				else
					setTimeout(function () { nextNews() }, 4000);
			});
		}

		$.ajax({
			url: "/Ajax/News.asp",
			dataType: "json",
			cache: false,
			success: function (data) {
				$.each(data.News, function (i, newsItem) {
					_newsTicker.append($("<div>")
											.css({ width: 2000, display: "none" })
											.append($("<span>")
												.html(newsItem.Text)
											)
										);

				});

				_iNewsItems = _newsTicker.find("div").length;
				_newsItem = _newsTicker.find("div:first");

				showNewsItem();
			}
		});
	};
})(jQuery);
