var CounterPixel = function() {

	/**
	* Private variables
	*/
	
	/**
	* @private string Primary tracking server URL
	*/
	var cpPath1 = null;
	/**
	* @private string Secondary tracking server URL
	*/
	var cpPath2 = null;

	document.observe("dom:loaded", init);

	function init() {
		// Tracks all external links
		$$('a[href]').findAll(isExternal).each(function(el) {
			//logAttribute("Having external link to ", el);
			el.observe('click', trackExternal);
		});
		
		// Tracks clicks, i.e. NoPVs on JS buttons
		$$('a[rel^=trackClick:]').each(function(el) {
			el.observe('click', trackRel);
		});
		
		// Tracks downloads, basically clicks, but additionally the context menu too
		$$('a[rel^=trackDownload:]').each(function(el) {
			el.observe('click', trackRel);
			el.observe('contextmenu', trackRel); // NOTE: This does not work in Opera
		});
	}
	
	function isExternal(el) {
		if (el.target == '_blank') {
			return true;
		}
		if (el.href.startsWith('http://') || el.href.startsWith('https://')) {
			if (!el.href.match(document.location.hostname)) {
				//el.target = '_blank'; // Force external links to open in new window
				return true;
			}
		}
		return false;
	}

	function trackExternal() {
		var link = this.href.replace(/\//g, "|");
		var label = this.title.strip();
		if(label == '') {
			label = this.innerHTML.stripTags();
		}
		//log("Label '" + label + "' has link '" + link + "'");
		var path = '/ext/local';
		if(label != '') {
			path = path + '/' + encodeURI(label);  
		}
		path = path + '/' + encodeURI(link);
		//log("Having path: " + path);
		CounterPixel.track(path);
	}
	
	function trackRel() {
		var path = this.readAttribute('rel');
		var index = path.indexOf('://');
		if (index > 0 && (index + 3) < path.length) {
			path = path.substring((index + 3), path.length);
		}
		//log("Having path: " + path);
		CounterPixel.track(path);
	}

	function wait(milis) {
		var date = new Date();
		var curDate = null;
		do {
			curDate = new Date();
		}
		while(curDate - date < milis);
	}
	
	function appendParameter(path, name, value) {
		if (name) {
			path = path + ((path.indexOf('?') == -1) ? '?' : '&') + name;
			if (value) {
				path = path + '=' + encodeURIComponent(value);
			}
		}
		return path;
	}

	/**
	* @note This returns an object literal containing all the following
	* methods. These (and these alone) can access the private vars declared
	* above. Something like CounterPixel.cpPath1 does not access the var but
	* rather create a new one.
	*/
	return {

		/**
		* Sets the path variables used for tracking. 
		* 
		* @method initCpPaths 
		* @param string path1
		* @param string path2
		*/
		initCpPaths : function(path1, path2) {
			if (!cpPath1 && !cpPath2) {
				cpPath1 = path1;
				cpPath2 = path2;
			}
		},

		/**
		* Tracks the specified path
		*
		* @method track 
		* @param string path
		*/
		track : function(path) {
			var now = new Date();
			var logpixel1 = new Image();
			var logpixel2 = new Image();
			if (cpPath1 && cpPath2) {
				if (!path.startsWith('/')) {
					path = '/' + path;
				}
				var pixel1src = cpPath1 + path;
				var pixel2src = cpPath2 + path;
				
				if (document.referrer) {
					pixel1src = appendParameter(pixel1src, 'V_REFERER', document.referrer);
					pixel2src = appendParameter(pixel2src, 'V_REFERER', document.referrer);
				}
				
				logpixel1.src = appendParameter(pixel1src, now.getTime(), '');
				logpixel2.src = appendParameter(pixel2src, now.getTime(), '');
				
				//log("Pixel: " + logpixel1.src);
				
				wait(100);
			}
		},

		/**
		* Tracks flash embedding failures
		*
		* @method track 
		* @param boolean notInstalled Pass true if flash is not installed on the client
		*/
		trackFlashEmbedFailure : function(notInstalled) {
			if (notInstalled) {
				this.track('/services/no_flash.html');
			} else {
				this.track('/services/wrong_flash.html');
			}
		},
		
		/**
		* Tries to determine the user's screen resolution, installed flash plugin
		* version and browser being used. The latter is only tracked if a proper
		* version could be determined, the others are always tracked.
		*
		* @method trackUserAgent 
		*/
		trackUserAgent : function() {
			var playerVersion = swfobject.getFlashPlayerVersion();
			var flashVersion = playerVersion.major + '.' + playerVersion.minor
					+ '.' + playerVersion.release;
			
			var browser = false;
			if (Prototype.Browser.IE) {
				browser = 'Internet_Explorer_' + navigator.appVersion.substr(
						navigator.appVersion.indexOf('MSIE')+5, 3);
			}
			else if (Prototype.Browser.Gecko) {
				browser = 'Firefox_' + navigator.userAgent.substr(
						navigator.userAgent.indexOf('Firefox')+8, 3);
			}
			else if (Prototype.Browser.Opera) {
				browser = 'Opera_' + navigator.appVersion.substr(0,3);
			}
			else if (Prototype.Browser.WebKit) {
				browser = 'Safari_' + navigator.appVersion.substr(
						navigator.appVersion.indexOf('Version')+8, 3);
			}
			
			// Screen resolution
			this.track('/user_agent/screenresolution/' + screen.width + 'x'
					+ screen.height + '.nopv');
			
			// Flash Player Version
			this.track('/user_agent/flashversion/' + flashVersion + '.nopv');

			// Browser
			if (browser != false) {
				this.track('/user_agent/browser/' + browser + '.nopv');
			}
		}

	}

}();

/**
 * Creates namespace for Omniture tracking
 */
var Omniture = function() {

	/**
	* @private string Page Name
	*/
	var pageName = null;
		
	function setupDefaults() {
		s.charSet="UTF-8";
		s.currencyCode="EUR";
		s.trackDownloadLinks=false;
		s.trackExternalLinks=true;
		s.trackInlineStats=true;
		s.thisHost=window.location.host;
		s.server=window.location.host;
		s.linkInternalFilters="javascript:,"+s.thisHost;
		s.cookieDomainPeriods=s.server.split('.').length - 1;
		
		s.linkLeaveQueryString=false;
		s.linkTrackVars="None";
		s.linkTrackEvents="None";
			
		s.currDateObj=new Date();
		
		var v = swfobject.getFlashPlayerVersion();
		s.hier2 = v.major + "." + v.minor + "." + v.release;		
	}
	
	function trackPageView() {
		s.pageName = pageName;
		removeTrailingSlash();		
		s.hier1 = s.pageName;
		
		var path = s.pageName.split('/');
	    s.channel = path[0];

		var depth = Math.min(path.length, 5);
		for (var i = 1; i < depth; i++) {
			s['prop' + i] = path[i]; //prop1-4 -> Level 2-5
		}
		s.t();
	}
	
	function removeTrailingSlash() {
		s.pageName = s.pageName.replace(/\/$/, "");
	}
	
	document.observe('dom:loaded', function() {
		if (window.s_account) {
			// Sets default omniture variables
			setupDefaults();
			Omniture.registerSWFAddressListener();
			// Fires an omniture event, so additional omniture variables (such as
			// product views etc) can bet set before tracking function is called
			document.fire('omniture:ready');
			trackPageView();
		}
	});
	
	document.observe('omniture:ready', function() {
		// Track Deeplink if set
		var deeplinkPath = readCookie('trackDeeplink');
		if (deeplinkPath != null) {
			s.prop16 = deeplinkPath;
			eraseCookie('trackDeeplink');
		}
	});
	
	// Public API
	return {
		
		/**
		 * Sets the page name
		 */
		init: function(n) {
			pageName = n;
		},
		
		trackLink: function(link) {
			if (Object.isString(link)) {
				var obj = new Object();
				obj.href = link;
				s.tl(obj,'o', link);
			}
			else {
				s.tl(link,'o');
			}
		},
		
		trackExternalLink: function(link) {
			if (Object.isString(link)) {
				var obj = new Object();
				obj.href = link;
				s.tl(obj,'e', link);
			}
			else {
				s.tl(link,'e');
			}
		},
		
		trackDownloadLink: function(link) {
			if (Object.isString(link)) {
				var obj = new Object();
				obj.href = link;
				s.tl(obj,'d', link);
			}
			else {
				s.tl(link,'d');
			}
		},
		
		trackSubPageView: function(subPage) {
			if (window.s_account) {
				// strip /#/ which is not required, we add it anyway
				var match = /^\/?#?\/?(.*)$/.exec(subPage);
				s.pageName = pageName + "/#/" + match[1];
				s.pageURL = window.location.href;
				s.hier1 = s.pageName;
				s.t();
			}
		},
		
		/*
		setProduct: function(id) {
			if (id) {
				s.events = "prodView";
				s.products = ";" + id;
				//s.prop18 = id;
			}
			else {
				s.events = "";
				s.products = "";
			}
		},*/		
		
		setErrorPage: function() {
			s.pageName = null;
			s.pageType = "errorPage";
		},
		
		registerSWFAddressListener: function() {
			var _this = this;
			SWFAddress.addEventListener(SWFAddressEvent.CHANGE, function () {
				var value = SWFAddress.getValue();
				if (value.size > 0 && value.charAt(0) != "/") {
					value = "/" + value;
				}
				if (value !== '/') {
					_this.trackSubPageView('/#' + value);
				}
			});
		}
		
	}
}();
