// ROTATING ANNOUNCEMENTS
// @author Joseph Karns - Schoolwires Web Developer 1
// Last updated on 7/28/11

(function ($) {
	$.fn.rotatingAnnouncements = function (settings) {
		var config = {
			'animationtype': 'fade',
			'speed': 'normal',
			'type': 'In-Order',
			'timeout': 2000,
			'detailheight': 'auto'
		};
		if (settings) {
			$.extend(config, settings)		}
		
		return this.each(function (index, list) {
			var element = this;
			var totalAnnouncements = $("ul.ui-articles li", element);
			if (totalAnnouncements.length > 0) {
				$("div.ui-widget-detail", element).css('position', 'relative').css('height', config.detailheight);
				for (var i = 0; i < totalAnnouncements.length; i++) {
					$(totalAnnouncements[i]).css('z-index', String(totalAnnouncements.length - i)).css('position', 'absolute').hide();
				};
				if (config.type == "In-Order") {
					setTimeout(function () {
						rotateAnnouncements(totalAnnouncements, config, 1, 0)
					}, config.timeout);
					$(totalAnnouncements[0]).show()
				} else if (config.type == "random") {
					var last = Math.floor(Math.random() * (totalAnnouncements.length));
					setTimeout(function () {
						do {
							current = Math.floor(Math.random() * (totalAnnouncements.length))
						} while (last == current);
						rotateAnnouncements(totalAnnouncements, config, current, last)
					}, config.timeout);
					$(totalAnnouncements[last]).show()
				}
			}
		})
	}
	
	function rotateAnnouncements(totalAnnouncements, config, current, last) {
		if (config.animationtype == 'slide') {
			$(totalAnnouncements[last]).slideUp(config.speed);
			$(totalAnnouncements[current]).slideDown(config.speed)
		} else if (config.animationtype == 'fade') {
			$(totalAnnouncements[last]).fadeOut(config.speed);
			$(totalAnnouncements[current]).fadeIn(config.speed);
		}
		if (config.type == "In-Order") {
			if ((current + 1) < totalAnnouncements.length) {
				current = current + 1;
				last = current - 1
			} else {
				current = 0;
				last = totalAnnouncements.length - 1
			}
		} else if (config.type == "random") {
			last = current;
			while (current == last) current = Math.floor(Math.random() * totalAnnouncements.length)
		}
		setTimeout((function () {
			rotateAnnouncements(totalAnnouncements, config, current, last)
		}), config.timeout)
	}
})(jQuery);
