jQuery.fn.contestalerts = function (options) {
	settings = jQuery.extend({
		//
	}, options);
	
    return this.each(function () {
		var $this = $(this);
		var records = [];
		var i = 0;
		var nextAlertInterval = null;
		function loadAlerts () {
			$.ajax({
				url: URL_CONTESTALERTS_INDEX,
				dataType: 'json',
				data: null,
				success: function (data) {
					if (data.success) {
						records = data.success;
						alertsLoad();
			        }
				}
			});
		}
		
		function alertsLoad () {
			if (records.length == 0) {
				$this.parent().animate({
					opacity: 0
				});
				$this.parent().slideUp();
				i=0;
				if (nextAlertInterval != null) {
					clearInterval(nextAlertInterval);
					nextAlertInterval = null;	
				}
			} else {
				$this.parent().slideDown();
				$this.parent().animate({
					opacity: 1
				});
				if (nextAlertInterval == null) {
					$('div', $this).html(records[i].Contestalert.body);
					nextAlertInterval = setInterval(nextAlert, 6000);
				}
			}
		}
		
		function nextAlert () {
			if (records.length == 0) return;
			i = (i<records.length-1) ? i+1 : 0;
			if ($.browser.msie) {
				$('div', $this).html(records[i].Contestalert.body);
			} else {
				$('div', $this).animate({
					'delay': 5000,
					'opacity' : 0
				}, 500, function () {
					$(this).html(records[i].Contestalert.body);
					$(this).animate({'opacity': 1}, 500).removeAttr('filter');
				});	
			}
		}
		
		loadAlerts();
		setInterval(loadAlerts, 10000);
	});
};

$(document).ready( function() {
	$("#alertMessage").contestalerts();
});
