/**
 * Innovative Technology Concepts
 * http://innovativetechnologyconcepts.com/my_scripts/online_users_counter/
 */

function WtOnlineUsersCounter(settings)
{
	this.useLog = false;
	
	this.Log = function(text)
	{
		if (!this.useLog) return;
		
		console.log(text);
	}
	
	this.defaults = {
		container: 'idOnlineVisitors',
		handler: '',
		periodicity: 30,
		useImages: null
	}
	settings = $.extend(true, {}, this.defaults, settings);
	this.Log(settings);
	
	this.handler = settings.handler;
	this.updatePeriodicity = settings.periodicity * 1000;
	this.selContainer = $('#' + settings.container);
	this.useImages = settings.useImages;
	
	this.updaterLink = null;
	
	this.Init = function()
	{
		//instant update
		this.Update(); 
		
		this.StartUpdater();
	}
	
	this.StartUpdater = function()
	{
		clearInterval(this.updaterLink);
		
		this.updaterLink = setInterval(function(objOuc){
			return function()
			{
				objOuc.Update();
			}
		}(this), this.updatePeriodicity);
	}
	
	this.StopUpdater = function()
	{
		clearInterval(this.updaterLink);
	}
	
	this.Update = function()
	{
		var url = this.handler + this.GetSeparator(this.handler) + 'action=update';
		
		this.Log('Update(): ' + url);
		
		$.get(url, function(objOuc){
			return function(data, textStatus, jqXHR)
			{
				objOuc.OnUpdate(data);
			}
		}(this), 'html');
	}
	
	this.OnUpdate = function(text)
	{
		this.Log('OnUpdate(): ' + text);
		
		var count = parseInt(text, 10);
		if (isNaN(count)) count = 0;
		
		var html = count;
		var html = this.GetCounterContent(count);
		
		
		
		this.selContainer.html(html);
	}
	
	this.GetCounterContent = function(count)
	{
		var images = this.useImages;
		if (images)
		{
			var strCount = new String(count);
			var html = '';
			for (var i=0; i<strCount.length; i++)
			{
				var digit = parseInt(strCount[i]);
				var src = images[digit];
				this.Log('digit:' + digit + ' / src:' + src);
				html += '<img src="' + src +'" />';
			}
			return html;
		}
		else
		{
			return count;
		}
	}
	
	this.GetSeparator = function(url)
	{
		return (url.indexOf('?') > 0) ? '&' : '?'; 
	}
}
