var chPage = '';
var chReferrer = '';
var chBrowser = null;
var chLastIframe = -1;


function Clickheat_getClickDetails(event) {
   try {
      var options = new Array();
	   options['c'] = null; //button
	   options['d'] = null; //destination url
	   options['x'] = null; //click x
	   options['y'] = null; //click y
	   options['w'] = null; //client width
      if (!event) {
         event = window.event;
         c = event.button;
         if (c == 0) {
            c = 1;
         }
      } else {
         c = event.which;
      }
		if (c == 0) {
			Clickheat_debugMessage('Click not logged: no button pressed');
			return true;
		}
      options['c'] = c;
      var hyperNode = null;

      if (event['srcElement']) {
         hyperNode = event['srcElement'];
      } else if(event['target']) {
         hyperNode = event['target'];
      }
      var destinationUrl = '';
      var linkHTML = '';
      if (hyperNode) {
         while (hyperNode && 'html' != hyperNode['tagName'].toLowerCase() && 'body' != hyperNode['tagName'].toLowerCase()) {
            if ('a' == hyperNode['tagName'].toLowerCase() && hyperNode['href']) {
               destinationUrl = hyperNode['href'];
               linkHTML = hyperNode.innerHTML;
               break;
            }
            hyperNode = hyperNode['parentNode'];
         }
      }

      options['d'] = destinationUrl;
      options['lh'] = linkHTML;


		x = event.clientX;
		y = event.clientY;

		d = document.documentElement != undefined && document.documentElement.clientHeight != 0 ? document.documentElement : document.body;
		scrollx = window.pageXOffset == undefined ? d.scrollLeft : window.pageXOffset;
		scrolly = window.pageYOffset == undefined ? d.scrollTop : window.pageYOffset;
		w = window.innerWidth == undefined ? d.clientWidth : window.innerWidth;
		h = window.innerHeight == undefined ? d.clientHeight : window.innerHeight;
		/** Is the click in the viewing area? Not on scrollbars */
		if (x > w || y > h) {
   		Clickheat_debugMessage('Click not logged: out of document (should be a click on scrollbars under IE)');
			return true;
		}
		var screenSize = window.screen.width;
		options['x'] = x + scrollx;
		options['y'] = y + scrolly;
		options['w'] = w;
		options['ss'] = screenSize;
      options['d'] = options['d'];
      return options;

   } catch(exception) {

   }
}
function Clickheat_catchClick(e) {
   try {
      var options = Clickheat_getClickDetails(e);
		var paramsStr = 't=click&' + Clickheat_makeRequestString(options);
      Clickheat_XMLHTTP_Send(paramsStr);
	} catch(exception) {
   	Clickheat_debugMessage('An error occurred while processing click' + exception.toString());
	}
	return true;
}

function initch() {
   if ((window.location.href.search(/testch/) != -1)) {
      Clickheat_test();
      return;
   }


   chPage = location.href;
   chReferrer = document.referrer;
   chBrowser = Clickheat_getBrowser();

   var options = new Array();
   options['t'] = 'visit'; //type (is click or visit)

	/** Add onmousedown event */
	if (typeof document.onclick == 'function') {
		currentFunc = document.onclick;
		document.onclick = function(e) {
         Clickheat_catchClick(e);
         return currentFunc(e);
		}
	} else {
		document.onclick = Clickheat_catchClick;
	}

   var paramsStr = Clickheat_makeRequestString(options);
	Clickheat_XMLHTTP_Send(paramsStr);
}

function  Clickheat_XMLHTTP_Send(paramsStr) {
   var sent = true;
   var xmlhttp = false;
   try {
      xmlhttp = new XMLHttpRequest();
   }  catch (e) {
      try {
         xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
      } catch (e) {
         try {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
         } catch (oc) {
            xmlhttp = null;
         }
      }
   }
   if (xmlhttp) {
      xmlhttp.onreadystatechange = function() {
         if (xmlhttp.readyState == 4) {
            if (xmlhttp.status == 200) {
               Clickheat_debugMessage('reuqest sent ' + chServer + '?' + paramsStr + '\n\nServer answer: ' + xmlhttp.responseText);
            } else if (xmlhttp.status == 404) {
               Clickheat_debugMessage('server not found at: ' + chServer );
            } else {
               Clickheat_debugMessage('server returned a status code ' + xmlhttp.status + ' with the following error: ' + xmlhttp.responseText);
            }
         }
      }
      xmlhttp.open("POST", chServer, true);
      xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
      var options = new Array();
      options['s'] = chPage;
      options['b'] = chBrowser;
      options['r'] = chReferrer;
      paramsStr += Clickheat_makeRequestString(options);
      paramsStr += 'option=com_clickheat&task=tracker';
      xmlhttp.send(paramsStr);
      sent = true;
   }
   return sent;
}

function Clickheat_makeRequestString(options) {
   var paramsStr = '';
   for (var i in options) {
      if (options[i] && ('string' == typeof(options[i]) || 'number' == typeof(options[i]) || 'bool' == typeof(options[i]))) {
         paramsStr += i + '=' + encodeURIComponent(options[i]) + '&';
      } else if (options[i] && 'object' == typeof(options[i])) {
         for (var y = 0; y < options[i].length; y++) {
            paramsStr += i + '[]=' + encodeURIComponent(options[i][y]) + '&';
         }
      }
   }
   return paramsStr;
}

function Clickheat_getBrowser() {
   /** Also the User-Agent is not the best value to use, it's the only one that gives the real browser */
   b = navigator.userAgent != undefined ? navigator.userAgent.toLowerCase().replace(/-/g, '') : '';
   b0 = b.replace(/^.*(firefox|kmeleon|safari|msie|opera).*$/, '$1');
   if (b == b0 || b0 == '') {
      if (b.match(/mozilla/i)) {
         b0 = 'mozilla';
      } else {
         b0 = 'unknown';
      }
   }
   return b0;
}


function Clickheat_debugMessage(msg) {
   var chDebug = (window.location.href.search(/debugch/) != -1);
   if (chDebug == true) {
      alert(msg);
   }
}

function Clickheat_test() {
   var xmlhttp = false;
   try {
      xmlhttp = new XMLHttpRequest();
   }  catch (e) {
      try {
         xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
      } catch (e) {
         try {
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
         } catch (oc) {
            xmlhttp = null;
         }
      }
   }
   if (xmlhttp) {
      xmlhttp.onreadystatechange = function() {
         if (xmlhttp.readyState == 4) {
            if (xmlhttp.status == 200) {
               if ('OK' == xmlhttp.responseText) {
                  alert('SUCCESS');
               } else {
                  var msg = 'reuqest sent ' + chServer;
                  msg += '\n\nServer answer: ' + xmlhttp.responseText;
                  alert(msg);
               }
            } else if (xmlhttp.status == 404) {
               alert('server not found at: ' + chServer );
            } else {
               alert('server returned a status code ' + xmlhttp.status + ' with the following error: ' + xmlhttp.responseText);
            }
         }
      }
      xmlhttp.open("POST", chServer, true);
      xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
      xmlhttp.send('option=com_clickheat&task=client_test');
      sent = true;
   }
}