/**
 * Uses Ajax to keeps a HTML region up to date.
 * jquery.live-region.js
 * @version 0.1
 *
 * @author Andrew Ramsden
 * @see http://irama.org/web/dhtml/live-list/
 * @license GNU GENERAL PUBLIC LICENSE (GPL) <http://www.gnu.org/licenses/gpl.html>
 * 
 * @requires jQuery (tested with 1.3.2) <http://jquery.com/>
 * @requires jQuery jARIA plugin <http://outstandingelephant.com/jaria/>
 * @requires jQuery times plugin <http://jquery.offput.ca/every/>
 */
;
jQuery.liveRegion = {};
jQuery.liveRegion._conf = {
	liveRegionClass : 'live-region',
	activeClass  : 'active',
	updatingClass  : 'updating'
};
jQuery.liveRegion._options = {
	interval  : 300000 // 5 minutes
};


(function($) {// start closure
	
	// On DOMLoad
	//$(function(){
		// Nothing onload
	//});
	
	
	$.fn.liveRegion = function (options) {
				
		// Merge runtime options with defaults
		// Note: The first argument sent to extend is an empty object to
		// prevent extend from overriding the default $.AKN.defaultOptions object.
			options = (typeof options == 'undefined')
				? $.liveRegion._options
				: $.extend({}, $.liveRegion._options, options)
			;
		
		if (typeof options.source == 'undefined') {
			// can't do much without a source
				return $(this);	 // facilitate chaining
		}
		
		$(this).each(function () {
			
			$(this)
				.data('options', options)
				//.ariaState('live','polite') // Be polite these updates are not urgent
			;
			
			// set timer to update after each interval
				$(this).everyTime(options.interval, function() {
					updateLiveRegion.apply(this);
				});
			
			// update once initially
				updateLiveRegion.apply(this);
			
			// set active
				$(this)
					.addClass($.liveRegion._conf.liveRegionClass)
					.addClass($.liveRegion._conf.activeClass)
				;
		});
		
		
		return $(this); // facilitate chaining
	};

	
	updateLiveRegion = function () {
		
		// get options
			options = $(this).data('options');
		
		
		// find container
			if (typeof options.container != 'undefined') {
				container = $(this).parents(options.container).eq(0);
			} else {
				container = $(this);
			}
		
		// set updating class
			$(this).addClass($.liveRegion._conf.updatingClass);
		
		// load new content
			$(this).load(options.source, function(){
				
				$(this).removeClass($.liveRegion._conf.updatingClass);
				
				// fadein container
					if (container.is(':hidden')) {
						container.slideDown().fadeIn('slow');
					}
				
				// debug log
					console.log('live-list #'+container.attr('id')+' updated!');
			});
		
	};
	
	/**
	 * Dump debug messages to console if available, otherwise to status bar.
	 */
	$.debug = function (message){
		if (typeof window.console != 'undefined' && window.console.log != 'undefined') {
			window.console.log(message);
		} else {
			// un comment next line if testing IE6 issues in dev environment (don't use for production)
				//window.status = message;
		}
	};
	
})(jQuery); /* end closure */