/*
 * Google Analytics Utilities
 *
 * @Author Thomas März (thomas.maerz@noogen.de)
 *
 * Used at
 *		http://www.citrix.de
 *		http://partnerweb.citrix.de
 *		http://www.citrix.eu/grenzenlos
 *
 *		and many other sites
 */

/* http://www.google.com/support/analytics/bin/answer.py?hl=en&answer=55597 */

var _pageName = document.location.pathname + document.location.search;

function track(name) {
	if(!name || name == "") {
		name = _pageName;
	}
	if (typeof(pageTracker) == 'object') {
		pageTracker._trackPageview(name);
		log('_trackPageview(' + name + ')');
	} else if (typeof(urchinTracker) == 'function') {
		urchinTracker(name);
		log('urchinTracker(' + name + ')');
	}
}

// Firebug Logging
function log(message) {
	if(typeof(console) == 'object') {
		console.log(message);
	}
}

var LinkTracker = Class.create({

	initialize: function(rules) {
		this.rules = rules;
		this.links = $$('a');

		this.links.each((function(a) {
			var rule = this.linkRule(a);
			if(rule) {
				a.href = rule.href();
				a.observe('click', function() {
					track(rule.pageName());
				});
			}
		}).bind(this));
	},

	linkRule: function(a) {
		var result = null;

		this.rules.each(function(rule) {
			var tmp = new RuleLink(a, rule);
			if(!result && tmp.matches()) {
				result = tmp;
			}
		});
		
		return result;
	}
	
});

/* Rewrite Rules for Tracking */
var Rule = Class.create({
	
	initialize: function(map) {
		this.regex = map.regex;
		this.replacement = map.replacement;

		this.source = map.source;
		this.campaign = map.campaign;
		this.requiresOutgoing = map.requiresOutgoing;
		
		_rules.push(this);
	}
	
});

var RuleLink = Class.create({

	initialize: function(a, rule) {
		this.a = a;
		this.rule = rule;
	},
	
	matches: function() {
		return this.isOutgoing() && this.a.href.match(this.rule.regex);
	},
	
	isOutgoing: function() {
		if(this.rule.requiresOutgoing) {
			return document.location.hostname != this.a.hostname;
		}
		return true;
	},
	
	isCampaignLink: function() {
		if(this.rule.source == null || this.rule.campaign == null) {
			return false;
		}
		return this.a.hostname.match(/(.*)\.citrix\.(de|at|ch|eu)/);
	},
	
	pageName: function() {
		return this.a.href.replace(this.rule.regex, this.rule.replacement);
	},
	
	href: function() {
		if(!this.isCampaignLink()) {
			return this.a.href;
		}
		var href = this.a.href;
		if(href.indexOf("utm_source") == -1) {
			if(this.a.search == "") {
				href += "?";
			}
			href += "utm_source=" + this.rule.source + "&utm_campaign=" + this.rule.campaign + "&utm_medium=web";
		}
		return href;
	}

});

var _rules = new Array();

Event.observe(window, 'load', function() {
	new LinkTracker(_rules);
});
