/*
Ajax Link Tracker, version 2.2.2

Copyright (c) 2006 Glenn Jones
Modified by Rick LaTour

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

You must give the original author attribution. For any reuse or
distribution, you must make clear to others the licence terms of this
work.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/


function AjaxLinkTracker() {

    var me;
    if (this.constructor == AjaxLinkTracker){
        me = this;
    }else{
        me = arguments[arguments.length-1];
    }

	// Configuration
	// ------------
	me.apiURL = 'http://ezinearticles.com/ajt/';
	me.displayCount = true;
	me.displayPercent = true;
	me.displayLabel = true;
	me.numberDays = 28; //1-30
	me.clickOffSet = 10;
	// -----------

	me.url = encodeURIComponent( document.location.href );
	me.listeners = [];


	me.addLinkTracking = function(){
		if (!document.getElementsByTagName) return false;

		// Create ajax objects
		me.clickedXHR = new XHRConnection();
		me.getClicksXHR = new XHRConnection();

		// find links in document
		links = document.getElementsByTagName('a');

		// if link does have a id add one
		for (var i = 0; i < links.length; i++) {
			me.addEvent( links[i], 'mousedown', me.recordClick, false );
			me.addEvent( links[i], 'keypress', me.linkKeyPress, false );
			if (! links[i].getAttribute('id') ) {
				links[i].setAttribute('id','link_' + i);
			}
		}

		// find buttons in document
		inputs = document.getElementsByTagName('input');
		for (var i = 0; i < inputs.length; i++) {

			type = inputs[i].getAttribute('type');

			// only attach events to buttons
			if ( type == 'submit' || type == 'button' ){
				me.addEvent( inputs[i], 'mousedown', me.recordClick, false );
				me.addEvent( inputs[i], 'keypress', me.linkKeyPress, false );
				// if button does have a id add one
				if (! inputs[i].getAttribute('id') ){
					inputs[i].setAttribute('id','button_' + i);
				}
			}
		}
	}

	me.linkKeyPress = function(e) {
		// check for return key press
		var keyID = (window.event) ? event.keyCode : e.keyCode;
		if (keyID == 13) {
			me.recordClick(e);
		}
	}

	me.recordClick = function(e) {
		// records click information using ajax
		source = me.findSourceElement(e);
		tag = source.tagName;

		var id,label,target,art_id,zone;
        art_id=document.getElementById('art_id').value;

		if( tag == 'IMG'){
			if( source.parentNode.tagName == 'A' )
			{
				id = source.parentNode.getAttribute('id');
				target = source.parentNode.href;
			}
			label = source.getAttribute('alt');
			if (label == null) {
				label = 'image';
			}
			//alert(source.parentNode.tagName);
			//alert(source.parentNode.id);
			//zone=source.parentNode.id;// return href id for tracking 'Print this' and other image clicks
            zone=me.findNodes(source);
		}

		if( tag == 'A' ){
			id = source.getAttribute('id');
			target = source.href;
			label = me.getInnerText( source, '' );
			//alert(source.parentNode.parentNode.tagName);
			//alert(source.parentNode.parentNode.id);
			zone=me.findNodes(source);
			//alert(zone);
		   // zone=source.parentNode.parentNode.id;//return div id for tracking in body or sig
		}

		if( tag == 'INPUT' ){
			id = source.getAttribute('id');
			label = source.getAttribute('value');

			if( source.getAttribute('type') == 'submit' ) {
				target = me.getFormTarget( source );
			} else {
				target = 'script';
			}
		}


		id = encodeURIComponent( id );
		target = encodeURIComponent( target );
		label = encodeURIComponent( label );

        var zones=new Array("sig","body","print");// define valid id tags

		if(zones.inArray(zone)){
          if(! target.match('/expert=/')){
		var ajaxURL = me.apiURL + 'addclick.php?id=' + id + '&art_id='+ art_id +'&zone=' + zone +'&label=' + label + '&target=' + target + '&url=' + me.url + '&rand='+Math.random();
		//alert(ajaxURL);
		me.clickedXHR.send( ajaxURL, 'get', me.beenClicked, null  );
          }
		}
	}


	me.beenClicked = function( obj ) {
		//alert( obj.responseText );
	}


	me.getInnerText = function( node, text ) {
		// returns the text of any element node
		for (var i = 0; i < node.childNodes.length; i++) {

			if( node.childNodes[i].nodeType == 3 ) {
				text += node.childNodes[i].nodeValue;
			}
			if( node.childNodes[i].nodeType == 1 ) {
				text = me.getInnerText( node.childNodes[i], text);
			}
		}
		return text;
	}

	me.getFormTarget = function( elt ) {
		// returns the form action attribute from
		// if given the child node of that form
		target = null;
		parentElt = elt.parentNode;
		if( parentElt.nodeType == 1 ) {
			if( parentElt.tagName == 'FORM' ) {
				target = parentElt.getAttribute('action');
			}else {
				target = me.getFormTarget( elt.parentNode );
			}
		}else {
			target = me.getFormTarget( elt.parentNode );
		}
		return target;
	}

	me.addEvent = function( elm, evType, fn, useCapture ) {
		// Updated version which captures passed events
		if (elm.AddEventListener)
		{
			elm.AddEventListener(evType, fn, useCapture);
			return true;
		} else if (elm.attachEvent) {
			var r = elm.attachEvent('on' + evType, fn);
			me.listeners[me.listeners.length] = [ elm, evType, fn ];
			return r;
		} else {
			var xEventFn = elm['on' + evType];
			if (typeof elm['on' + evType] != 'function')
			{
				elm['on' + evType] = fn;
			} else {
				elm['on' + evType] = function(e) { xEventFn(e); fn(e); };
			}
		}
	}

	me.unload = function(){
		// page unload event which removes circular references
		// that may cause memory leaks in IE 5/6
		if( window.attachEvent ){
			for (var i = 0; i < me.listeners.length; i++) {
				me.listeners[i][0].detachEvent( 'on' + me.listeners[i][1], me.listeners[i][2] );
			}
		}
	}

	me.getElementsByClassName = function( className ) {
		// returns a collection of element nodes which
		// have the passed className
		var children = document.getElementsByTagName('*') || document.all;
		var elements = new Array();
		for (var i = 0; i < children.length; i++)
		{
			var child = children[i];
			var classNames = child.className.split(' ');
			for (var j = 0; j < classNames.length; j++)
			{
				if (classNames[j] == className)
				{
					elements.push(child);
					break;
				}
			}
		}
		return elements;
	}

	me.findSourceElement = function(e) {
		// finds event source
		if (typeof e == 'undefined')
			var e = window.event;

		var source;
		if (typeof e.target != 'undefined')
		{
			source = e.target;
		} else if (typeof e.srcElement != 'undefined') {
			source = e.srcElement;
		} else {
			return true;
		}

		if (source.nodeType == 3)
			source = source.parentNode;

		return source;
	}


	me.findNodes = function(e){
	 zone='';
	 p=e;
     try{
	 while(p.id != 'sig' && p.id != 'body' && p.id != 'print'){
     p=p.parentNode;
	 //alert(parent.id);
       try{
	      if((typeof p.id != 'undefined')){
		  zone=p.id;
		  }}catch(err){}
     }}catch(err){}
	 return zone;
	}

	me.getPageOffsetLeft = function(elt) {
		var x;
		x = elt.offsetLeft;
		if (elt.offsetParent != null)
			x += me.getPageOffsetLeft(elt.offsetParent);
		return x;
	}

	me.getPageOffsetTop = function(elt) {
		var y;
		y = elt.offsetTop;
		if (elt.offsetParent != null)
			y += me.getPageOffsetTop(elt.offsetParent);
		return y;
	}

	//------------------------------------------


	me.addEvent( window, 'load', me.addLinkTracking, false );
//	me.addEvent( document, 'keydown', me.keyCheck, false );
	me.addEvent( window, 'unload', me.unload, false );

}

var ajaxLinkTracker = new AjaxLinkTracker();


function XHRConnection() {
    var me;
    if (this.constructor == XHRConnection){
        me = this
    }else{
        me = arguments[arguments.length-1]
    }

	me.Request = me.createXHR();

    me.handler = function () {
		if (me.Request.readyState == 4) {
			if (me.Request.status == 200) {

				me.processResponse();
			}
		}
	}

	me.send = function ( url, action, fnOK ) {
	    me.URL = url;
		me.Action = action;
		me.fnOK = fnOK;
		if( me.Request != null ){
			me.Request.open(me.Action, me.URL, true);
			me.Request.onreadystatechange = me.handler;
			me.Request.send(null);
		}else{
			alert('Could not load XHR object');
		}
	}
}

XHRConnection.prototype.createXHR = function() {
    try { return new ActiveXObject('Msxml2.XMLHTTP'); } catch (e) {}
    try { return new ActiveXObject('Microsoft.XMLHTTP'); } catch (e) {}
    try { return new XMLHttpRequest(); } catch(e) {}
    return null;
}

XHRConnection.prototype.processResponse = function () {
	this.fnOK(this.Request);
}

Array.prototype.inArray = function (value) {
	var i;
	for (i=0; i < this.length; i++) {
		if (this[i] === value) {
			return true;
		}
	}
	return false;
};


