//
// closure
//

(function($) {
	
	/**** force run *****************************************************/
	
	$(function () 
	{
		var interval 	= 1000 * 60 * 4, //4min
			url 		= document.location.href.toString(),
			data		= { heartbeat: '' };
		
		// run heartbeat
		var beat = function (data)
		{
			var o = {};
			try { o = eval('('+data+')'); } catch (e) { };
			if (o.status && o.status != 0)
			{
				switch (o.status) {
					case 1:
					default:
						//alert('oh no, we hit a 1 -- reloading!');
						try {
							Media.closeChildWindows();
						} catch (e) {}
						//throw "Hit a 1 -- reloading!";
						document.location.reload();
						return;
				};
			};
			
			//console.log(['Heartbeat status', o]);
		};
		
		// send to server
		var send_beat = function ()
		{
			$.get(url, data, beat);
		};
		
		var t = setInterval(send_beat, interval);
	});
	

	/**** Plugin ********************************************************

	$.fn.heartbeat.defaults = {
			interval: 60000, //1min
			target: document.location.toString(),
			callback: NULL,
			get: FALSE,
			post: FALSE
	};
	/**
	 * Creates a new heartbeat object for each matched element
	 *
	$.fn.heartbeat = function (opts)
	{
		// extend defaults but do not override
		opts = $.extend({}, $.fn.heartbeat.defaults, opts);

		return this.each(function () 
		{
			var $this 		= $(this),
				o 			= opts,
				url_func 	= o.post ? $.post : $.get;

			function beat ()
			{
				// load the target using GET
				url_func(o.target, o.data, o.callback);
			};

			// check previous
			var t = $this.data('heartbeat_id');
			if (t) {
				try { clearInterval(t); } catch (e) { }
			}
			// start the interval
			t = setInterval(beat, o.interval);
			$this.data('heartbeat_id', t);
		});
		
	};
	
	/**
	 * Stops the heartbeat stored in the selected element.
	 * @author Jesse Decker
	 *
	$.fn.heartbeat_stop = function ()
	{
		return this.each(function ()
		{
			var id = $(this).data('heartbeat_id');
			try { clearInterval(id); } catch (e) { };
		};
	};
	/**/
	
//
// end closure
//
})(jQuery);