// webtuning Link Tracker, version 1.0
wtAddEvent(window, 'load', wtAddLinkTracker, false);

function wtAddEvent(elm, evType, fn, useCapture) {
  // cross-browser event handling for IE5+, NS6 and Mozilla By Scott Andrew 
  if (elm.addEventListener) { 
    elm.addEventListener(evType, fn, useCapture); 
    return true; 
  } else if (elm.attachEvent) { 
    var r = elm.attachEvent('on' + evType, fn); 
    return r; 
  } else {
    elm['on' + evType] = fn;
  }
}

function wtAddLinkTracker() {
	if (!document.getElementsByTagName) return false;
	
	linksElements = document.getElementsByTagName('A');
	for (var i = 0; i < linksElements.length; i++) {
	  // Alle Links mit einem Mousedown-Event versehen
		var oldMousedown = linksElements[i].onmousedown;
		if (typeof linksElements[i].onmousedown != 'function') {
			linksElements[i].onmousedown = wtRecordClick;
		} else {
			linksElements[i].onmousedown = function() {
				oldMousedown();
				wtRecordClick();
			}
		}
		// Links ohne ID mit ID versehen
		if (! linksElements[i].getAttribute('id') )
    	linksElements[i].setAttribute('id',"link_" + i);
	}
}

function wtRecordClick(e) {
	var id, target, url;
	eltLink = wtFindLink(wtFindEventSource(e));
	if( eltLink != null )	{
		id = eltLink.getAttribute('id');
		target = wtEncodeUrl(eltLink.href);
	}
	url = wtEncodeUrl(document.location.href);
	var pars = '';
	apiurl = "/webautor-templates/linktracker/addClick.asp?id=" + id + "&target=" + target + "&url=" + url + "&rand="+Math.random();
	ajaxRequest = new Ajax.Request(apiurl, {method: 'get', parameters: pars, onComplete: passThrough});
	return false;	
}

function passThrough(originalRequest) {
	// alert( originalRequest.responseText );
}

function wtFindLink(elt) {
	if( elt.tagName == 'A' ) {
		return elt;	
	}	else {
		if(elt.parentNode)
			return wtFindLink(elt.parentNode);
		else
			return null;
	}
}

function wtFindEventSource(e) {
	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;
}

function wtEncodeUrl(str) {
    return encodeURIComponent(str);
}

// Darstellung Link Tracking
// ------------------------------------------------------------------
var labelsCreated = false;
var labelsDisplayed = false;
wtAddEvent(document, 'keydown', wtKeyCheck, false);

function wtKeyCheck(e) {
	var keyID = (window.event) ? event.keyCode : e.keyCode;
	var altKey = (window.event) ? event.altKey : e.altKey;
	var ctrlKey = (window.event) ? event.ctrlKey : e.ctrlKey;
	var shiftKey = (window.event) ? event.shiftKey : e.shiftKey;
	
	if((keyID == 84)&&(ctrlKey == true)&&(ctrlKey == shiftKey)) {  // Ctrl + Shift + T
		if(labelsCreated == false)	{
			getClickThroughInfo();
		}	else {
			if(labelsDisplayed == true) {
				displayStatus = "none";
				labelsDisplayed = false;
			}	else {
				displayStatus = "block";
				labelsDisplayed = true;
			}
			eltLabels = document.getElementsByClassName('linklabel');	
			for (var i = 0; i < eltLabels.length; i++) {
				eltLabels[i].style.display = displayStatus;
			}
		}
	}
}

document.getElementsByClassName = function(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;
}

function getClickThroughInfo() {
	var pars = '';	
	url = document.location.href;
	apiurl = "/webautor-templates/linktracker/getClicks.asp?url=" + url + "&rand="+Math.random();
	ajaxRequest = new Ajax.Request(apiurl, {method: 'get', parameters: pars, onComplete: displayClickThroughs});
}	

function displayClickThroughs(originalRequest) {
	if (!document.getElementsByTagName) return false;
	// alert (originalRequest);
	node = originalRequest.responseXML;
	// alert( originalRequest.responseText );
	
	if (node.childNodes[0].nodeType == 7) rootNode = node.childNodes[1]; else rootNode = node.childNodes[0];
	if (rootNode.childNodes[0].getAttribute('code')=='100') return false; // Error - keine Daten vorhanden
		
	var total = 0; totalcount=0; totalpercent = 0;
	for (var i = 0; i < rootNode.childNodes.length; i++) {
		linknode = rootNode.childNodes[i];
		count = linknode.getAttribute('count');
		percent = linknode.getAttribute('percent');
		target = linknode.getAttribute('target');
		id = linknode.childNodes[0].nodeValue;
		total += eval(count);
		
		if (!document.getElementById(id) ) {
				linksElements = document.getElementsByTagName('A');
				for (var j = 0; j < linksElements.length; j++) {
					if (linksElements[j].href == target && linksElements[j].getAttribute('id').length <= 7) 
						linksElements[j].setAttribute(id);
				}					
		}
		if ( document.getElementById(id) ) {
			eltLink =  document.getElementById(id);
			
			if (eltLink != target){
				linksElements = document.getElementsByTagName('A');
				for (var j = 0; j < linksElements.length; j++) {
					if (linksElements[j].href == target && linksElements[j].getAttribute('id').length <= 7) {
						// alert(linksElements[j].id + ' ' + linksElements[j].href );
						eltLink = linksElements[j];
					}
				}					
			}
			// alert(eltLink);
			if (eltLink == target ){
				totalpercent += eval(percent);
				totalcount += eval(count);				
				eltDiv = document.createElement( 'div' );
				eltDiv.className = "linklabel";
				eltText = document.createTextNode( percent + "% (" + count + ")");
				eltDiv.appendChild( eltText );
				document.body.appendChild( eltDiv );
				
				Drag.init(eltDiv, eltDiv);
				
				ileft = parseInt(getPageOffsetLeft( eltLink )) + 5;
				itop = parseInt(getPageOffsetTop( eltLink )) + 5;
				eltDiv.style.left = ileft + "px";
				eltDiv.style.top = itop + "px";
				if (percent > 9) eltDiv.style.width = percent*6 + "px";
				// alert(eltDiv.style.top);
			} 
		}
	} 
	if (totalcount < total) {
		eltDiv = document.createElement( 'div' );
		eltDiv.className = "linklabel";
		eltText = document.createTextNode( 100 - totalpercent + "% (" + (total-totalcount) + ") unbekannt");
		eltDiv.appendChild( eltText );
		document.body.appendChild( eltDiv );	
		eltDiv.style.left = "450px";
		eltDiv.style.top = "120px";
	}
	labelsCreated = true;
	labelsDisplayed = true;
}

function getPageOffsetLeft(elt) {
  var x = elt.offsetLeft;
  if (elt.offsetParent != null) x += getPageOffsetLeft(elt.offsetParent);
  return x;
}

function getPageOffsetTop(elt) {
  var y = elt.offsetTop;
  if (elt.offsetParent != null) y += getPageOffsetTop(elt.offsetParent);
  return y;
}


/*  Prototype JavaScript framework, version 1.3.1
 *  (c) 2005 Sam Stephenson <sam@conio.net>
 *  Prototype is freely distributable under the terms of an MIT-style license.
 *  For details, see the Prototype web site: http://prototype.conio.net/
/*--------------------------------------------------------------------------*/

// This is cutdown version that only contains the basic Ajax tools 
var Prototype = {
  Version: '1.3.1 cutdown',
  emptyFunction: function() {}
}

var Class = {
  create: function() {
    return function() { 
      this.initialize.apply(this, arguments);
    }
  }
}

var Abstract = new Object();

Object.extend = function(destination, source) {
  for (property in source) {
    destination[property] = source[property];
  }
  return destination;
}

Object.prototype.extend = function(object) {
  return Object.extend.apply(this, [this, object]);
}

Function.prototype.bind = function(object) {
  var __method = this;
  return function() {
    __method.apply(object, arguments);
  }
}

Function.prototype.bindAsEventListener = function(object) {
  var __method = this;
  return function(event) {
    __method.call(object, event || window.event);
  }
}

var Try = {
  these: function() {
    var returnValue;
    for (var i = 0; i < arguments.length; i++) {
      var lambda = arguments[i];
      try {
        returnValue = lambda();
        break;
      } catch (e) {}
    }
    return returnValue;
  }
}

var Ajax = {
  getTransport: function() {
    return Try.these(
      function() {return new ActiveXObject('Msxml2.XMLHTTP')},
      function() {return new ActiveXObject('Microsoft.XMLHTTP')},
      function() {return new XMLHttpRequest()}
    ) || false;
  }
}

Ajax.Base = function() {};
Ajax.Base.prototype = {
  setOptions: function(options) {
    this.options = {
      method: 'post',
      asynchronous: true,
      parameters: ''
    }.extend(options || {});
  },

  responseIsSuccess: function() {
    return this.transport.status == undefined
        || this.transport.status == 0 
        || (this.transport.status >= 200 && this.transport.status < 300);
  },

  responseIsFailure: function() {
    return !this.responseIsSuccess();
  }
}

Ajax.Request = Class.create();
Ajax.Request.Events = ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete'];

Ajax.Request.prototype = (new Ajax.Base()).extend({
  initialize: function(url, options) {
    this.transport = Ajax.getTransport();
    this.setOptions(options);
    this.request(url);
  },

  request: function(url) {
    var parameters = this.options.parameters || '';
    if (parameters.length > 0) parameters += '&_=';

    try {
      if (this.options.method == 'get')
        url += '?' + parameters;

      this.transport.open(this.options.method, url,this.options.asynchronous);

      if (this.options.asynchronous) {
        this.transport.onreadystatechange = this.onStateChange.bind(this);
        setTimeout((function() {this.respondToReadyState(1)}).bind(this), 10);
      }

      this.setRequestHeaders();

      var body = this.options.postBody ? this.options.postBody : parameters;
      this.transport.send(this.options.method == 'post' ? body : null);

    } catch (e) {
    }
  },

  setRequestHeaders: function() {
    var requestHeaders = ['X-Requested-With', 'XMLHttpRequest','X-Prototype-Version', Prototype.Version];

    if (this.options.method == 'post') {
      requestHeaders.push('Content-type','application/x-www-form-urlencoded');
      if (this.transport.overrideMimeType)
        requestHeaders.push('Connection', 'close');
    }

    if (this.options.requestHeaders)
      requestHeaders.push.apply(requestHeaders, this.options.requestHeaders);

    for (var i = 0; i < requestHeaders.length; i += 2)
      this.transport.setRequestHeader(requestHeaders[i], requestHeaders[i+1]);
  },

  onStateChange: function() {
	//alert( this.transport.readyState );
    var readyState = this.transport.readyState;
    if (readyState != 1)
      this.respondToReadyState(this.transport.readyState);
  },

  respondToReadyState: function(readyState) {
    var event = Ajax.Request.Events[readyState];

    if (event == 'Complete')
      (this.options['on' + this.transport.status]
       || this.options['on' + (this.responseIsSuccess() ? 'Success' : 'Failure')]
       || Prototype.emptyFunction)(this.transport);

    (this.options['on' + event] || Prototype.emptyFunction)(this.transport);

    if (event == 'Complete')
      this.transport.onreadystatechange = Prototype.emptyFunction;
  }
});


// makes divs movable by www.youngpup.net
var Drag = {

	obj : null,

	init : function(o, oRoot, minX, maxX, minY, maxY, bSwapHorzRef, bSwapVertRef, fXMapper, fYMapper)
	{
		o.onmousedown	= Drag.start;

		o.hmode			= bSwapHorzRef ? false : true ;
		o.vmode			= bSwapVertRef ? false : true ;

		o.root = oRoot && oRoot != null ? oRoot : o ;

		if (o.hmode  && isNaN(parseInt(o.root.style.left  ))) o.root.style.left   = "0px";
		if (o.vmode  && isNaN(parseInt(o.root.style.top   ))) o.root.style.top    = "0px";
		if (!o.hmode && isNaN(parseInt(o.root.style.right ))) o.root.style.right  = "0px";
		if (!o.vmode && isNaN(parseInt(o.root.style.bottom))) o.root.style.bottom = "0px";

		o.minX	= typeof minX != 'undefined' ? minX : null;
		o.minY	= typeof minY != 'undefined' ? minY : null;
		o.maxX	= typeof maxX != 'undefined' ? maxX : null;
		o.maxY	= typeof maxY != 'undefined' ? maxY : null;

		o.xMapper = fXMapper ? fXMapper : null;
		o.yMapper = fYMapper ? fYMapper : null;

		o.root.onDragStart	= new Function();
		o.root.onDragEnd	= new Function();
		o.root.onDrag		= new Function();
	},

	start : function(e)
	{
		var o = Drag.obj = this;
		e = Drag.fixE(e);
		var y = parseInt(o.vmode ? o.root.style.top  : o.root.style.bottom);
		var x = parseInt(o.hmode ? o.root.style.left : o.root.style.right );
		o.root.onDragStart(x, y);

		o.lastMouseX	= e.clientX;
		o.lastMouseY	= e.clientY;

		if (o.hmode) {
			if (o.minX != null)	o.minMouseX	= e.clientX - x + o.minX;
			if (o.maxX != null)	o.maxMouseX	= o.minMouseX + o.maxX - o.minX;
		} else {
			if (o.minX != null) o.maxMouseX = -o.minX + e.clientX + x;
			if (o.maxX != null) o.minMouseX = -o.maxX + e.clientX + x;
		}

		if (o.vmode) {
			if (o.minY != null)	o.minMouseY	= e.clientY - y + o.minY;
			if (o.maxY != null)	o.maxMouseY	= o.minMouseY + o.maxY - o.minY;
		} else {
			if (o.minY != null) o.maxMouseY = -o.minY + e.clientY + y;
			if (o.maxY != null) o.minMouseY = -o.maxY + e.clientY + y;
		}

		document.onmousemove	= Drag.drag;
		document.onmouseup		= Drag.end;

		return false;
	},

	drag : function(e)
	{
		e = Drag.fixE(e);
		var o = Drag.obj;

		var ey	= e.clientY;
		var ex	= e.clientX;
		var y = parseInt(o.vmode ? o.root.style.top  : o.root.style.bottom);
		var x = parseInt(o.hmode ? o.root.style.left : o.root.style.right );
		var nx, ny;

		if (o.minX != null) ex = o.hmode ? Math.max(ex, o.minMouseX) : Math.min(ex, o.maxMouseX);
		if (o.maxX != null) ex = o.hmode ? Math.min(ex, o.maxMouseX) : Math.max(ex, o.minMouseX);
		if (o.minY != null) ey = o.vmode ? Math.max(ey, o.minMouseY) : Math.min(ey, o.maxMouseY);
		if (o.maxY != null) ey = o.vmode ? Math.min(ey, o.maxMouseY) : Math.max(ey, o.minMouseY);

		nx = x + ((ex - o.lastMouseX) * (o.hmode ? 1 : -1));
		ny = y + ((ey - o.lastMouseY) * (o.vmode ? 1 : -1));

		if (o.xMapper)		nx = o.xMapper(y)
		else if (o.yMapper)	ny = o.yMapper(x)

		Drag.obj.root.style[o.hmode ? "left" : "right"] = nx + "px";
		Drag.obj.root.style[o.vmode ? "top" : "bottom"] = ny + "px";
		Drag.obj.lastMouseX	= ex;
		Drag.obj.lastMouseY	= ey;

		Drag.obj.root.onDrag(nx, ny);
		return false;
	},

	end : function()
	{
		document.onmousemove = null;
		document.onmouseup   = null;
		Drag.obj.root.onDragEnd(	parseInt(Drag.obj.root.style[Drag.obj.hmode ? "left" : "right"]), 
									parseInt(Drag.obj.root.style[Drag.obj.vmode ? "top" : "bottom"]));
		Drag.obj = null;
	},

	fixE : function(e)
	{
		if (typeof e == 'undefined') e = window.event;
		if (typeof e.layerX == 'undefined') e.layerX = e.offsetX;
		if (typeof e.layerY == 'undefined') e.layerY = e.offsetY;
		return e;
	}
};