/*
 * Click Counter javascript module
 *
 * Detects web browser link clicks then calls PHP script that records them
 *
 *
 * LICENSE: This source file is subject to the BSD license
 * that is available through the world-wide-web at the following URI:
 * http://www.opensource.org/licenses/bsd-license.php.
 *
 * @author     Michael P. Shipley <michael@michaelpshipley.com>
 * @copyright  2008 Michael P. Shipley
 * @license    http://www.opensource.org/licenses/bsd-license.php BSD
 * @version    1.0
 * @link       http://www.michaelpshipley.com Michael Shipley
 */

/**
	Add 'onclick' action to all tags that have a the designated class
*/
function cc_add_click_monitor(gotNoClass)
{

	var atags = document.getElementsByTagName('*');	

	for (var i=0; i < atags.length; i++) 
	{
		if(atags[i].className == gotNoClass)
		{
			atags[i].onclick = function()
			{
				cc_click(this); 
				return true;
			}
		}
	}		
}



/**
	http callback placeholder
*/
function cc_http_response_callback()
{}



/**
	Handle a click by doing an ajax call to the php click handler script
*/
function cc_click(tag)
{
	tag.style.cursor='wait';  			

	// make url of php script that counts clicks.
	var url = document.URL;
	var path = url.substr(0,url.lastIndexOf("/")+1);	
	var click_counter = path + '/click_counter/click.php';
	//alert('click path: ' + click_counter);
	if (window.XMLHttpRequest)
	{
		var http = new XMLHttpRequest();
	}
	else if (window.ActiveXObject)
	{
		var http = new ActiveXObject('Microsoft.XMLHTTP')
	}
	else
	{
		alert('browser doesn\'t support javascript http connections');	
		return true;
	}
	http.onreadystatechange = function()
	{
		if(http.readyState == 4)
		{
			tag.style.cursor='pointer';  					
			if(http.status != 200)
			{
				alert('Click Counter HTTP ERROR: ' + http.responseText);
			}
			else
			{
				cc_http_response_callback(http.responseText);
			}
			return true;				
		}
	}
	
	var url = tag.getAttribute("href");	
	var title = tag.childNodes[0].nodeValue;

	// uncomment to turn off onclick for this <a> tag to prevent repeat clicks
	//tag.setAttribute('onclick',null);
	
	var params = 'url=' + encodeURIComponent(url) + '&title=' + escape(title);

	http.open("POST", click_counter, true);
	http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
	http.setRequestHeader("Content-length", params.length);	
	http.send(params);
	return true;
}