// TogglePrayer -----------------------------------------------------------
// Used to toggle Live Prayer status after the web campus has loaded.
// Example:
// var tp = new TogglePrayer();
// tp.init({
//   url: "path/to/service",
//   short_loop: "10000", interval in milliseconds for checking the service when offline
//   long_loop: "60000", interval in milliseconds for checking the service when online
//   iframe: "prayer_frame_id"
// });
//
var TogglePrayer = function() {
	// to keep scope after it's been lost
	var _this = this;
	
	this.init = function(args) {				
		if (typeof args == "undefined") {
			throw("You must initialize TogglePrayer with these arguments as an object: url, short_loop, long_loop, and iframe.");
		}
		else {					
			this.url = args.url;
			this.short_loop = args.short_loop;
			this.long_loop =args.long_loop;
			this.iframe =args.iframe;
			_this.prayer_is_on = false;
		}
	};
	
	this.callOnce = function() {
		this.beginAjax();
	};
	
	this.startLoop = function() {
		if (!_this.prayer_is_on)
			this.interval = setInterval(function() { _this.beginAjax(); }, this.short_loop);
		else
			this.interval = setInterval(function() { _this.beginAjax(); }, this.long_loop);
	};
	
	this.stopLoop = function() {
		clearInterval(this.interval);
	};
	
	this.beginAjax = function() {				
		$.ajax({
			url: this.url+"?"+Math.round(Math.random()*1000000),
			complete: this.handleResponse
		});
	};
	
	this.handleResponse = function(d, s) {
		var count = eval("("+ d.responseText +")").online;
						
		if (s == "success") {
			_this.stopLoop();
			
			if (count > 0) {						
				if (!_this.prayer_is_on)
					_this.refreshLivePrayer();
				
				_this.prayer_is_on = true;
			}
			else if (count <= 0) {
				if (_this.prayer_is_on)
					_this.refreshLivePrayer();
					
				_this.prayer_is_on = false;
			}
			
			_this.startLoop();
		}
		else {
			// request was unsuccessful
			// fail silently
		}
	};
	
	this.refreshLivePrayer = function() {
		var the_iframe = document.getElementById(_this.iframe);
		var the_jframe = $("#"+_this.iframe); // this is cumbersome
		
		// the reload takes a split second, so we start it before
		// hiding and showing the iframe
		if (document.frames)
			document.frames(this.iframe).window.location.reload(true);
		else
			the_iframe.contentDocument.location.reload(true);
		
		the_jframe.hide();
		// using this so there's no FoUC
		setTimeout(function() { $('#'+_this.iframe).fadeIn('slow'); }, 1000);
	};
};

$(document).ready(function() {			
	var tp = new TogglePrayer();
	tp.init({
		url: "http://www.newspring.cc/live-prayer/operators.php",
		short_loop: "10000",
		long_loop: "30000",
		iframe: "prayer_frame"
	});
	tp.startLoop();
});
