/**
 * $Id: jquery.announce.js 27558 2011-10-04 21:04:53Z art49 $
 * usage
 *  $('.announcements').announce();
 * options (all optional):
 *  src      - the URL for the json 
 *  success  - the handler for successful retrieval of announcements
 *  error    - the handler for successful retrieval of announcements
 *  [type]   - what types of announcements to display by default {downtime: true}
 * 
 * json example: 
 * {"announcements" : [
 * 	{ 
 * 		"type"		: "downtime", 
 * 		"message"	: "The Problems of the Week will be unavailable Saturday, May 7th from 7:00-8:30AM EDT while we apply software upgrades.", 
 * 		"starts"	: "Fri May 06 2011 07:00:00 GMT-0400 (EDT)",
 * 		"expires"	: "Sat May 07 2011 08:30:00 GMT-0400 (EDT)"
 * 	},
 * 	{ 
 * 		"type"		: "downtime", 
 * 		"message"	: "The Problems of the Week will be unavailable Saturday, June 4th from 7:00-8:30AM EDT while we apply software upgrades.", 
 * 		"starts"	: "Thu June 02 2001 07:00:00 GMT-0400 (EDT)",
 * 		"expires"	: "Sat June 04 2051 08:30:00 GMT-0400 (EDT)"
 * 	},
 * 	{ 
 * 		"type"		: "freestuff",
 * 		"message"	: "We have free stuff",
 * 		"starts"	: "Fri May 06 2011 07:00:00 GMT-0400 (EDT)",
 * 		"expires"	: "Sat May 07 2051 08:30:00 GMT-0400 (EDT)"
 * 	}
 * ]}
 */
(function( $ ){

	$.fn.announce = function( options ) {

		var $this = $(this);

		$this.hide().html('');

		var settings = {
			'downtime' 	: true, 
			'src'		: '/announce/announce.json',
			'success'	: success,
			'process'	: process,
			'cache'		: true,
			'error'		: error
		};

		if ( options ) {
			$.extend( settings, options );
		}

		var src = settings['src'];

		if (!settings.cache || typeof $().announce.jsonAnnouncements === 'undefined') {
			$.ajax({ url: src, async: false, cache: false })
			    .success( settings.success )
			    .error( settings.error )
		}

		settings.process();

		return this;

		function success(data) { $().announce.jsonAnnouncements = data; }

		function process() {
			var announcements = $.parseJSON($().announce.jsonAnnouncements).announcements;
			$.each(announcements, function(index, value) {
				if (isPertinent(value)) {
					$this.append('<p class="' + value.type + '">' + value.message + ' </p>');
				}
				});
			$this.show();
		}

		function error() {
			$this.html('...');
			$this.addClass('error');
			$this.show();
		}

		function isPertinent(announcement) {
			return ( settings[announcement.type] && (isNowBetweenStartAndEnd(announcement.starts, announcement.expires)));
		}

		function isNowBetweenStartAndEnd(start, end) {
			var now = new Date();
			start = new Date(start);
			end   = new Date(end);
			return (start.getTime() < now.getTime() && end.getTime() > now.getTime() );
		}

	};
})( jQuery );

