/************************************************************
 * eDialog Javascript Tracker
 *
 * Heavily inspired by Piwik
 *
 * - In the original Piwik Code there's a "onUnload"-Blocker, to ensure the request is processed.
 * 
 ************************************************************/

// eDialog Tracker Proxy
var	_edtp = _edtp || [];		

	// edJsTr singleton and namespace
var	edJsTr = function() {
		
	/*
	 * apply wrapper
	 *
	 * @param array parameterArray An array comprising either:
	 *      [ 'methodName', optional_parameters ]
	 * or:
	 *      [ functionObject, optional_parameters ]
	 */
	var apply = function (parameterArray) {
		var f = parameterArray.shift();

		if (isString(f)) {
			asyncTracker[f].apply(asyncTracker, parameterArray);
		} else {
			f.apply(asyncTracker, parameterArray);
		}
	}
		
	/*
	 * Get page referrer
	 */
	var getReferrer = function () {
		var referrer = '';

		try {
			referrer = window.top.document.referrer;
		} catch (e) {
			if (window.parent) {
				try {
					referrer = window.parent.document.referrer;
				} catch (e2) {
					referrer = '';
				}
			}
		}
		if (referrer === '') {
			referrer = document.referrer;
		}

		return referrer;
	}
		
	/*
	 * Extract hostname from URL
	 */
	var getHostName = function (url) {
		// scheme : // [username [: password] @] hostame [: port] [/ [path] [? query] [# fragment]]
		var e = new RegExp('^(?:(?:https?|ftp):)/*(?:[^@]+@)?([^:/#]+)'),
			matches = e.exec(url);

		return matches ? matches[1] : url;
	}

	/*
	 * Extract parameter from URL
	 */
	var getParameter = function(url, name) {
		// scheme : // [username [: password] @] hostame [: port] [/ [path] [? query] [# fragment]]
		var e = new RegExp('^(?:https?|ftp)(?::/*(?:[^?]+)[?])([^#]+)'),
			matches = e.exec(url),
			f = new RegExp('(?:^|&)' + name + '=([^&]*)'),
			result = matches ? f.exec(matches[1]) : 0;

		return result ? decodeURIComponent(result[1]) : '';
	}

	/*
	 * Fix-up URL when page rendered from search engine cache or translated page
	 */
	var urlFixup = function (hostName, href, referrer) {
		if (hostName === 'translate.googleusercontent.com') {		// Google
			if (referrer === '') {
				referrer = href;
			}
			href = getParameter(href, 'u');
			hostName = getHostName(href);
		} else if (hostName === 'cc.bingj.com' ||					// Bing
				hostName === 'webcache.googleusercontent.com' ||	// Google
				hostName.slice(0, 5) === '74.6.') {					// Yahoo (via Inktomi 74.6.0.0/16)
			href = documentAlias.links[0].href;
			hostName = getHostName(href);
		}
		return [hostName, href, referrer];
	}
	
	/*
	 * Tracker class
	 *
	 * @param string url to PHP Script
	 * @param int|string cId Campaign ID
	 * @param int|string cfId Campaign Flight ID (optional)
	 */
	var Tracker = function(url, cId, cfId) {

		/************************************************************
		 * Private members
		 ************************************************************/

		var locationArray = urlFixup(document.domain, window.location.href, getReferrer()),
			// Current URL and Referrer URL
			locationHrefAlias = locationArray[1],
			configReferrerUrl = locationArray[2],

			// Request method (GET or POST)
			configRequestMethod = 'GET',

			// Tracker URL
			configTrackerUrl = url || '',

			// Campaign ID
			configTrackerCampaignId = cId || '',
			
			// Campaign Flight ID
			configTrackerCampaignFlightId = cfId || '',
			
			// Document title
			configTitle = document.title,
			
			// Document URL
			configCustomUrl,
			
			// Maximum delay to wait for web bug image to be fetched (in milliseconds)
			configTrackerPause = 500,

			// Minimum visit time after initial page view (in milliseconds)
			configMinimumVisitTime,

			// Disallow hash tags in URL
			configDiscardHashTag = true,

			// Do Not Track
			configDoNotTrack
			
		/*
		 * Purify URL.
		 */
		var purify = function(str) {
			var targetPattern;

			if (configDiscardHashTag) {
				targetPattern = new RegExp('#.*');
				return str.replace(targetPattern, '');
			}
			return str;
		}


		/*
		 * Send image request to Piwik server using GET.
		 * The infamous web bug (or beacon) is a transparent, single pixel (1x1) image
		 */
		var getImage = function (request) {
			var image = new Image(1, 1);

			image.onLoad = function () { };
			image.src = configTrackerUrl + (configTrackerUrl.indexOf('?') < 0 ? '?' : '&') + request;
		}

		/*
		 * POST request to Piwik server using XMLHttpRequest.
		 */
		var sendXmlHttpRequest = function (request) {
			try {
				// we use the progid Microsoft.XMLHTTP because
				// IE5.5 included MSXML 2.5; the progid MSXML2.XMLHTTP
				// is pinned to MSXML2.XMLHTTP.3.0
				var xhr = windowAlias.XMLHttpRequest ? new windowAlias.XMLHttpRequest() :
					windowAlias.ActiveXObject ? new ActiveXObject('Microsoft.XMLHTTP') :
					null;

				xhr.open('POST', configTrackerUrl, true);
				xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
				// Safari: unsafe headers
				// xhr.setRequestHeader('Content-Length', request.length);
				// xhr.setRequestHeader('Connection', 'close');
				xhr.send(request);
			} catch (e) {
				// fallback
				getImage(request);
			}
		}
		
		/*
		 * Send request
		 */
		var sendRequest = function (request, delay) {
			var now = new Date();
			if (!configDoNotTrack) {
				if (configRequestMethod === 'POST') {
					sendXmlHttpRequest(request);
				} else {
					getImage(request);
				}
			}
		}
			
		/*
		 * Returns the URL to call piwik.php,
		 * with the standard parameters (plugins, resolution, url, referrer, etc.).
		 * Sends the pageview and browser settings with every request in case of race conditions.
		 */
		var getRequest = function (request) {
			// build out the rest of the request
			request += '&cid=' + configTrackerCampaignId + '&cfid=' + configTrackerCampaignFlightId +
				'&rand=' + Math.random() + '&method=' + configRequestMethod +
				'&url=' + encodeURIComponent(purify(configCustomUrl || locationHrefAlias)) +
				'&urlref=' + encodeURIComponent(purify(configReferrerUrl))

			return request;
		}

		/*
		 * Log the page view / visit
		 */
		var logPageView = function (customTitle) {
			var now = new Date(),
				request = getRequest('title=' + encodeURIComponent(customTitle || configTitle));

			sendRequest(request, configTrackerPause);
		}


		/************************************************************
		 * Public data and methods
		 ************************************************************/

		return {
			/**
			 * Set request method
			 *
			 * @param string method GET or POST; default is GET
			 */
			setRequestMethod: function (method) {
				configRequestMethod = method || 'GET';
			},
	
			/**
			 * Override referrer
			 *
			 * @param string url
			 */
			setReferrerUrl: function (url) {
				configReferrerUrl = url;
			},
	
			/**
			 * Frame buster
			 */
			killFrame: function () {
				if (window.location !== window.top.location) {
					window.top.location = window.location;
				}
			},
	
			/**
			 * Redirect if browsing offline (aka file: buster)
			 *
			 * @param string url Redirect to this URL
			 */
			redirectFile: function (url) {
				if (window.location.protocol === 'file:') {
					window.location = url;
				}
			},

			/**
			 * Override url
			 *
			 * @param string url
			 */
			setCustomUrl: function (url) {
				configCustomUrl = url;
			},
			
			/**
			 * Append URL
			 *
			 * @param string append
			 */
			appendUrl: function(url) {
				configCustomUrl = locationHrefAlias+url;
			},
			
			/**
			 * Log visit to this page
			 *
			 * @param string customTitle
			 */
			trackPageView: function (customTitle) {
				logPageView(customTitle);
			}
		};
	}
	
	/************************************************************
	 * Proxy object
	 * - this allows the caller to continue push()'ing to _paq
	 *   after the Tracker has been initialized and loaded
	 ************************************************************/

	var TrackerProxy = function () {
		return {
			push: apply
		};
	}
		
	/************************************************************
	 * Constructor
	 ************************************************************/

	// var asyncTracker = new Tracker();

	for (i = 0; i < _edtp.length; i++) {
		apply(_edtp[i]);
	}

	// replace initialization array with proxy object
	_edtp = new TrackerProxy();

	/************************************************************
	 * Public data and methods
	 ************************************************************/

	return {
		/**
		 * Get Tracker (factory method)
		 *
		 * @param string url to PHP Script
		 * @param int|string cId Campaign ID
		 * @param int|string cfId Campaign Flight ID (optional)
		 * @return Tracker
		 */
		getTracker: function (url, cId, cfId) {
			return new Tracker(url, cId, cfId);
		}
	
		/**
		 * Get internal asynchronous tracker object
		 *
		 * @return Tracker
		 */
		/*
		getAsyncTracker: function () {
			return asyncTracker;
		} */
	};
}();
// parameter: URI, Kampagnen-ID, Kampagnen-Flight-ID
var t = edJsTr.getTracker('/exttr/proxy',1,1);
t.trackPageView();
