 // IPBE AjaxRandomMessges    v.1.0.0 
 // @file        ips.AjaxRandomMsgs.js
 // @date        9:17 AM 3-16-10
 //  @author			$Author: amgedosman $
 // @link				http://ipbegypt.com/
 // @version			$Revision: 1 $
 //-------------------------------------

var _AjaxRandomMsgs = window.IPBoard;

_AjaxRandomMsgs.prototype.AjaxRandomMsgs = {
	ajaxHandler: '',
	updateInterval: '',
	updateIntervalType: '',
	

	
	init: function()
	{
		
		document.observe( 'dom:loaded', function()
		{
			
		
            ipb.AjaxRandomMsgs.ajaxHandler = new Ajax.IntervalUpdates( 'ipbeARM-container', ipb.vars['base_url'] + "app=core&module=ajax&section=AjaxRandomMsgs&secure_key=" + ipb.vars['secure_hash'],
            {
                method: 'get',
                frequency: ipb.AjaxRandomMsgs.ConvertTypeTime(),
                decay: 2,
                evalJSON: 'force'
            });

            
			
		});
	},
	

	
	ConvertTypeTime: function( e )
	{
		if( ipb.AjaxRandomMsgs.updateIntervalType == 'sec' )
		{ 
		   ipb.AjaxRandomMsgs.returns = ipb.AjaxRandomMsgs.updateInterval;
		}
		else if( ipb.AjaxRandomMsgs.updateIntervalType == 'min' )
		{
		   
		   ipb.AjaxRandomMsgs.returns = ipb.AjaxRandomMsgs.updateInterval * 60;
		}
		else
		{
		   ipb.AjaxRandomMsgs.returns = ipb.AjaxRandomMsgs.updateInterval;
		}
		
		return ipb.AjaxRandomMsgs.returns;
		
	}
	
	
};

//------------------------------
// Taken from SOS recent topics
// by: Adriano 
// sosinvision.com
// @author: adrianscott
// http://www.fluther.com/disc/9117/ajaxperiodicalupdater-only-update-if-the-content-has-changed/#quip58902
//------------------------------
Ajax.IntervalUpdates = Class.create(Ajax.Base, 
{
	initialize: function($super, container, url, options) 
	{
		$super(options);
		this.onComplete = this.options.onComplete;
		
		this.frequency = this.options.frequency;
		this.decay = this.options.decay;
		
		this.updater = { };
		this.container = $(container);
		this.url = url;
		this.runnedOnce = 0;
		this.lastTimestamp = '';

		this.start();
	},
		
	start: function() 
	{
		this.options.onComplete = this.updateComplete.bind(this);
		this.onTimerEvent();
	},
		
	stop: function() 
	{
		this.updater.options.onComplete = undefined;
		clearTimeout(this.timer);
		(this.onComplete || Prototype.emptyFunction).apply(this, arguments);
	},
		
	updateComplete: function(t) 
	{
		if (t.responseJSON['last_timestamp'] == this.lastTimestamp ) 
		{
			this.decay = this.decay * this.options.decay;
		} 
		else 
		{
			this.decay = this.options.decay;
			this.container.update( t.responseJSON['html'] );
			this.lastTimestamp = t.responseJSON['last_timestamp']; 
			
			if ( this.runnedOnce == 1 )
			{
				Effect.Pulsate( this.container, { pulses: 1, duration: 1.5 } );
			}
			
			this.runnedOnce = 1;
		}
		
		this.timer = this.onTimerEvent.bind(this).delay(this.decay * this.frequency);
	},
		
	onTimerEvent: function() {
		this.updater = new Ajax.Request(this.url, this.options);
	}
});

ipb.AjaxRandomMsgs.init();
