/** Main variables */
var mapaCalorGroup = '';
var mapaCalorSite = '';
var mapaCalorServer = '';
var mapaCalorLastIframe = -1;
var mapaCalorTime = 0;
var mapaCalorQuota = -1;
var mapaCalorBrowser = '';
var mapaCalorDocument = '';
var mapaCalorWait = 500;
var mapaCalorLocalWait = 0;
var mapaCalorDebug = (window.location.href.search(/debugmapacalor/) !== -1);

/**
* Shows a debug string
**/
function showMapaCalorDebug(str)
{
	if (mapaCalorDebug === true)
	{
		document.getElementById('mapaCalorDebuggerSpan').innerHTML = str;
		document.getElementById('mapaCalorDebuggerDiv').style.display = 'block';
	}
}
/** Main function */
function catchMapaCalor(e)
{
	/** Use a try{} to avoid showing errors to users */
	try
	{
		showMapaCalorDebug('Gathering click data...');
		if (mapaCalorQuota === 0)
		{
			showMapaCalorDebug('Click not logged: quota reached');
			return true;
		}
		if (mapaCalorGroup === '')
		{
			showMapaCalorDebug('Click not logged: group name empty (mapaCalorGroup)');
			return true;
		}
		/** Look for the real event */
		if (e === undefined)
		{
			e = window.event;
			c = e.button;
			element = e.srcElement;
		}
		else
		{
			c = e.which;
			element = null;
		}
		if (c === 0)
		{
			showMapaCalorDebug('Click not logged: no button pressed');
			return true;
		}
		/** Filter for same iframe (focus on iframe => popup ad => close ad => new focus on same iframe) */
		if (element !== null && element.tagName.toLowerCase() === 'iframe')
		{
			if (element.sourceIndex === mapaCalorLastIframe)
			{
				showMapaCalorDebug('Click not logged: same iframe (a click on iframe opens a popup and popup is closed => iframe gets the focus again)');
				return true;
			}
			mapaCalorLastIframe = element.sourceIndex;
		}
		else
		{
			mapaCalorLastIframe = -1;
		}
		var x = e.clientX;
		var y = e.clientY;
		var w = mapaCalorDocument.clientWidth !== undefined ? mapaCalorDocument.clientWidth : window.innerWidth;
		var h = mapaCalorDocument.clientHeight !== undefined ? mapaCalorDocument.clientHeight : window.innerHeight;
		var scrollx = window.pageXOffset === undefined ? mapaCalorDocument.scrollLeft : window.pageXOffset;
		var scrolly = window.pageYOffset === undefined ? mapaCalorDocument.scrollTop : window.pageYOffset;
		/** Is the click in the viewing area? Not on scrollbars. The problem still exists for FF on the horizontal scrollbar */
		if (x > w || y > h)
		{
			showMapaCalorDebug('Click not logged: out of document (should be a click on scrollbars)');
			return true;
		}
		/** Check if last click was at least 1 second ago */
		clickTime = new Date();
		if (clickTime.getTime() - mapaCalorTime < 1000)
		{
			showMapaCalorDebug('Click not logged: at least 1 second between clicks');
			return true;
		}
		mapaCalorTime = clickTime.getTime();
		if (mapaCalorQuota > 0)
		{
			mapaCalorQuota = mapaCalorQuota - 1;
		}
		params = 's=' + mapaCalorSite + '&g=' + mapaCalorGroup + '&x=' + (x + scrollx) + '&y=' + (y + scrolly) + '&w=' + w + '&b=' + mapaCalorBrowser + '&c=' + c + '&random=' + Date();
		showMapaCalorDebug('Ready to send click data...');
		/** Local request? Try an ajax call */
		var sent = false;
		if (mapaCalorServer.substring(0, 4) !== 'http')
		{
			var xmlhttp = false;
			try
			{
				xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
			}
			catch (er)
			{
				try
				{
					xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
				}
				catch (oc)
				{
					xmlhttp = null;
				}
			}
			if (!xmlhttp && typeof XMLHttpRequest !== undefined)
			{
				xmlhttp = new XMLHttpRequest();
			}
			if (xmlhttp)
			{
				if (mapaCalorDebug === true)
				{
					xmlhttp.onreadystatechange = function()
					{
						if (xmlhttp.readyState === 4)
						{
							if (xmlhttp.status === 200)
							{
								showMapaCalorDebug('Click recorded at ' + mapaCalorServer + ' with the following parameters:<br />x = ' + (x + scrollx) + ' (' + x + 'px from left + ' + scrollx + 'px of horizontal scrolling)<br />y = ' + (y + scrolly) + ' (' + y + 'px from top + ' + scrolly + 'px of vertical scrolling)<br />width = ' + w + '<br />browser = ' + mapaCalorBrowser + '<br />click = ' + c + '<br />site = ' + mapaCalorSite + '<br />group = ' + mapaCalorGroup + '<br /><br />Server answer: ' + xmlhttp.responseText);
							}
							else if (xmlhttp.status === 404)
							{
								showMapaCalorDebug('click.php was not found at: ' + (mapaCalorServer !== '' ? mapaCalorServer : '/mapacalor/click.php') + ' please set mapaCalorServer value');
							}
							else
							{
								showMapaCalorDebug('click.php returned a status code ' + xmlhttp.status + ' with the following error: ' + xmlhttp.responseText);
							}
							/** Stop waiting */
							mapaCalorLocalWait = 0;
						}
					};
				}
				xmlhttp.open('GET', mapaCalorServer + '?' + params, true);
				xmlhttp.setRequestHeader('Connection', 'close');
				xmlhttp.send(null);
				sent = true;
			}
		}
		if (sent === false)
		{
			/** This test is needed, as it includes the call to click.php in the iframe */
			if (mapaCalorDebug === true)
			{
				showMapaCalorDebug('Click recorded at ' + mapaCalorServer + ' with the following parameters:<br />x = ' + (x + scrollx) + ' (' + x + 'px from left + ' + scrollx + 'px of horizontal scrolling)<br />y = ' + (y + scrolly) + ' (' + y + 'px from top + ' + scrolly + 'px of vertical scrolling)<br />width = ' + w + '<br />browser = ' + mapaCalorBrowser + '<br />click = ' + c + '<br />site = ' + mapaCalorSite + '<br />group = ' + mapaCalorGroup + '<br /><br />Server answer:<br />' + '<iframe src="' + mapaCalorServer + '?' + params + '" width="700" height="60"></iframe>');
			}
			else
			{
				var mapaCalorImg = new Image();
				mapaCalorImg.src = mapaCalorServer + '?' + params;
			}
		}
		/** Little waiting cycle: default is to wait until Ajax sent or until the end of the time if no Ajax is available */
		var now = new Date();
		mapaCalorLocalWait = now.getTime() + mapaCalorWait;
		while (mapaCalorLocalWait > now.getTime())
		{
			now = new Date();
		}
	}
	catch(err)
	{
		showMapaCalorDebug('An error occurred while processing click (Javascript error): ' + e.message);
	}
	return true;
}

function initMapaCalor()
{
	/** Debug Window */
	if (mapaCalorDebug === true)
	{
		document.write('<div id="mapaCalorDebuggerDiv" style="padding:5px; display:none; position:absolute; top:10px; left:10px; border:1px solid #888; background-color:#eee; z-index:99;"><strong>MapaCalor debug: <a href="#" onmouseover="document.getElementById(\'mapaCalorDebuggerDiv\').style.display = \'none\'; return false">Rollover to close</a></strong><br /><br /><span id="mapaCalorDebuggerSpan"></span></div>');
	}

	if (mapaCalorGroup === '' || mapaCalorServer === '')
	{
		showMapaCalorDebug('MapaCalor NOT initialised: either mapaCalorGroup or mapaCalorServer is empty');
		return false;
	}

	/** If current website has the same domain as the script, we remove the domain so that the call is made using Ajax */
	domain = window.location.href.match(/http:\/\/[^/]+\//);
	if (domain !== null && mapaCalorServer.substring(0, domain[0].length) === domain[0])
	{
		mapaCalorServer = mapaCalorServer.substring(domain[0].length - 1, mapaCalorServer.length);
	}
	/** Add onmousedown event using listeners */
	if (document.addEventListener)
	{
		document.addEventListener('mousedown', catchMapaCalor, false);
	}
	else if (document.attachEvent)
	{
		document.attachEvent('onmousedown', catchMapaCalor);
	}
	/** Add onfocus event on iframes (mostly ads) - Does NOT work with Gecko-powered browsers, because onfocus doesn't exist on iframes */
	iFrames = document.getElementsByTagName('iframe');
	for (i = 0; i < iFrames.length; i++)
	{
		if (document.addEventListener)
		{
			iFrames[i].addEventListener('focus', catchMapaCalor, false);
		}
		else if (document.attachEvent)
		{
			iFrames[i].attachEvent('onfocus', catchMapaCalor);
		}
	}
	/** Preparing main variables */
	mapaCalorDocument = (document.documentElement !== undefined && document.documentElement.clientHeight !== 0) ? document.documentElement : document.body;
	/** Also the User-Agent is not the best value to use, it's the only one that gives the real browser */
	var b = navigator.userAgent !== undefined ? navigator.userAgent.toLowerCase().replace(/-/g, '') : '';
	mapaCalorBrowser = b.replace(/iceweasel/, 'firefox').replace(/^.*(firefox|kmeleon|safari|msie|opera).*$/, '$1');
	if (b === mapaCalorBrowser || mapaCalorBrowser === '')
	{
		mapaCalorBrowser = 'unknown';
	}
	showMapaCalorDebug('MapaCalor initialised with:<br />site = ' + mapaCalorSite + '<br />group = ' + mapaCalorGroup + '<br />server = ' + mapaCalorServer + '<br />quota = ' + (mapaCalorQuota === -1 ? 'unlimited' : mapaCalorQuota) + '<br /><br />browser = ' + mapaCalorBrowser);
}
