/**
 * Content Spy - Javascript Object
 *
 * @copyright   Copyright (C) 2011, Stuart Silvester
 * @author      Stuart Silvester
 * @package     Content Spy
 * @version     1.0.9
 */

Element.addMethods({
    lastDescendant: function(element) {
        element = $(element).lastChild;
        while (element && element.nodeType != 1)
            element = element.previousSibling;
        return $(element);
    }
});

var _spy 	= window.IPBoard;

_spy.prototype.spy =
{
	polltime:		ipb.vars['spy_poll_rate'],

	maxrows:		ipb.vars['spy_rows'],

	type:			ipb.vars['spy_type'],

	lastpoll:		ipb.vars['spy_lastpoll'],

	currentrows:	ipb.vars['spy_current_rows'],

	timeout:		ipb.vars['spy_timeout'],

	lastitem:		ipb.vars['spy_last_item'],

	stopchecking:	0,

	running:		0,

	unreadCount:	0,

	windowHasFocus:	true,

	init: function()
	{
		Debug.write("Initializing ips.spy.js");

		/*
		 * Wait for the DOM to finish loading...
		 */
		document.observe("dom:loaded", function()
		{
			/*
			 * Start the timer!
			 */
			ipb.spy.startPE();

			/*
			 * If we've timed out a click will restart us
			 */
			$('spy_continue').observe( 'click', function(e)
			{
				Event.stop(e);
				ipb.spy.startPE()
			});

			ipb.spy.monitorFocus();
		});
	},

	getNewContent: function(pe)
	{
		if(ipb.spy.running == 1)
		{
			return false;
		}
		ipb.spy.running = 1;
		if(ipb.spy.stopchecking == 1)
		{
			new Effect.Appear( $( 'spy_timeout' ), { duration: 1.0 } );
			pe.stop();
			ipb.spy.running = 0;
			return false;
		}

		new Ajax.Request(ipb.vars['board_url']+'/index.php?app=spy&module=ajax&type='+ipb.spy.type+'&lastpoll='+ipb.spy.lastpoll+'&lastitem='+ipb.spy.lastitem+'&secure_key='+ipb.vars['secure_hash'],
		{
			hideLoader: true,
			evalJSON: 'force',
			onComplete: function(s)
			{
				if ( typeof(s.responseJSON['noresults']) != 'undefined' )
				{
					return;
				}
				li = '';
				s.responseJSON.each(
					function(i)
					{
						ipb.spy.lastitem = i['id'];

						var li = new Element('li');
						li.update( i['html'] );
						li.hide();

						$('spy').insert( { top:li } );
						new Effect.BlindDown( li, { duration: 0.25 } );
						ipb.spy.countAndRemoveRows();
						ipb.spy.unreadCount++;
					}
				);

				ipb.spy.updateTitleUnreadCount();
				ipb.spy.lastpoll = Math.round(new Date().getTime() / 1000);
			}
		}
	);
		ipb.spy.running = 0;
		return true;
	},

	updateTitleUnreadCount: function()
	{
		if( !ipb.spy.windowHasFocus && ipb.spy.unreadCount > 0 && ipb.spy.type != 'mini' )
		{
			if( document.title.match( /\(\d+\) (.+?)/gi ) )
			{
				document.title = document.title.replace( /\(\d+\) (.+?)/gi, "(" + ipb.spy.unreadCount + ") $1" );
			}
			else
			{
				document.title = "(" + ipb.spy.unreadCount + ") " + document.title;
			}
		}
	},

	userTimeout: function(pe)
	{
		ipb.spy.stopchecking = 1;
		pe.stop();
	},

	/*
	 * Clean the title tag upon refocusing
	 */
	cleanTitle: function()
	{
		if( document.title.match( /\(\d+\) (.+?)/gi ) )
		{
			document.title = document.title.replace( /\(\d+\) (.+?)/gi, "$1" );
		}

		ipb.spy.unreadCount	= 0;
	},

	countAndRemoveRows: function()
	{
		if( ipb.spy.maxrows > 0 )
		{
			if( $('spy').childElements().length > ipb.spy.maxrows )
			{
				var _toRemove	= $('spy').childElements().length - ipb.spy.maxrows;

				for( var tr=0; tr < _toRemove; tr++ )
				{
					new Effect.BlindUp( $('spy').lastDescendant(), { duration: 0.25, afterFinish: function()
					 {
						$('spy').lastDescendant().remove();
					 }
					 });
				}
			}
		}
	},

	startPE: function()
	{
		new Effect.Fade( $( 'spy_timeout' ), { duration: 1.0 } );
		ipb.spy.stopchecking = 0;

		/*
		 * Set an interval to poll ipb.spy.getNewContent(), which initiates the AJAX request.
		 */
		new PeriodicalExecuter( ipb.spy.getNewContent, ipb.spy.polltime );

		/*
		 * Set an interval to stop looking for data.
		 */
		if(ipb.spy.timeout > 0)
		{
			new PeriodicalExecuter( ipb.spy.userTimeout, ipb.spy.timeout );
		}
	},

	monitorFocus: function()
	{
		if( Prototype.Browser.IE )
		{
			document.onfocusin = function() { ipb.spy.cleanTitle(); ipb.spy.windowHasFocus = true; };
			document.onfocusout = function() { ipb.spy.unreadCount = 0; ipb.spy.windowHasFocus = false; };
		}
		else
		{
			Event.observe( window, 'focus', function() { ipb.spy.cleanTitle(); ipb.spy.windowHasFocus = true; } );
			Event.observe( window, 'blur', function() { ipb.spy.unreadCount = 0; ipb.spy.windowHasFocus = false; } );
		}
	}
}

ipb.spy.init();
