﻿/*
* Generate a random uuid.
*
* USAGE: Math.uuid(length, radix)
*   length - the desired number of characters
*   radix  - the number of allowable values for each character.
*
* EXAMPLES:
*   // No arguments  - returns RFC4122, version 4 ID
*   >>> Math.uuid()
*   "92329D39-6F5C-4520-ABFC-AAB64544E172"
* 
*   // One argument - returns ID of the specified length
*   >>> Math.uuid(15)     // 15 character ID (default base=62)
*   "VcydxgltxrVZSTV"
*
*   // Two arguments - returns ID of the specified length, and radix. (Radix must be <= 62)
*   >>> Math.uuid(8, 2)  // 8 character ID (base=2)
*   "01001010"
*   >>> Math.uuid(8, 10) // 8 character ID (base=10)
*   "47473046"
*   >>> Math.uuid(8, 16) // 8 character ID (base=16)
*   "098F4D35"
*/
Math.uuid = (function() {
	// Private array of chars to use
	var CHARS = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split('');

	return function(len, radix) {
		var chars = CHARS, uuid = [];
		radix = radix || chars.length;

		if (len) {
			// Compact form
			for (var i = 0; i < len; i++) uuid[i] = chars[0 | Math.random() * radix];
		} else {
			// rfc4122, version 4 form
			var r;

			// rfc4122 requires these characters
			uuid[8] = uuid[13] = uuid[18] = uuid[23] = '-';
			uuid[14] = '4';

			// Fill in random data.  At i==19 set the high bits of clock sequence as
			// per rfc4122, sec. 4.1.5
			for (var i = 0; i < 36; i++) {
				if (!uuid[i]) {
					r = 0 | Math.random() * 16;
					uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
				}
			}
		}

		return uuid.join('');
	};
})();

var __mfrap = "__mfrap";
var _handler = "http://a.reverseanalytics.com";
var _profileId = undefined;
var _analizeImage = undefined;

function _urlEscape(s) {
	if (typeof (encodeURIComponent) == 'function') { return encodeURIComponent(s); }
	else { return escape(s); }
}

function _getFlashVersion() {
	/**
	* Derived from Apple's suggested sniffer.
	* @param {String} desc e.g. Shockwave Flash 7.0 r61
	* @return {String} 7.0.61
	*/
	function getFlashVersion(desc) {
		var matches = desc.match(/[\d]+/g);
		matches.length = 3;  // To standardize IE vs FF
		return matches.join('.');
	}

	var hasFlash = false;
	var flashVersion = '';

	if (navigator.plugins && navigator.plugins.length) {
		var plugin = navigator.plugins['Shockwave Flash'];
		if (plugin) {
			hasFlash = true;
			if (plugin.description) {
				flashVersion = getFlashVersion(plugin.description);
			}
		}

		if (navigator.plugins['Shockwave Flash 2.0']) {
			hasFlash = true;
			flashVersion = '2.0.0.11';
		}

	} else if (navigator.mimeTypes && navigator.mimeTypes.length) {
		var mimeType = navigator.mimeTypes['application/x-shockwave-flash'];
		hasFlash = mimeType && mimeType.enabledPlugin;
		if (hasFlash) {
			flashVersion = getFlashVersion(mimeType.enabledPlugin.description);
		}

	} else {
		try {
			// Try 7 first, since we know we can use GetVariable with it
			var ax = new ActiveXObject('ShockwaveFlash.ShockwaveFlash.7');
			hasFlash = true;
			flashVersion = getFlashVersion(ax.GetVariable('$version'));
		} catch (e) {
			// Try 6 next, some versions are known to crash with GetVariable calls
			try {
				var ax = new ActiveXObject('ShockwaveFlash.ShockwaveFlash.6');
				hasFlash = true;
				flashVersion = '6.0.21';  // First public version of Flash 6
			} catch (e) {
				try {
					// Try the default activeX
					var ax = new ActiveXObject('ShockwaveFlash.ShockwaveFlash');
					hasFlash = true;
					flashVersion = getFlashVersion(ax.GetVariable('$version'));
				} catch (e) {
					// No flash
				}
			}
		}
	}

	return flashVersion;
}

function _getSilverlightVersion() {
	var version = '';
	var container = null;
	try {
		var control = null;
		if (window.ActiveXObject) {
			control = new ActiveXObject('AgControl.AgControl');
			version = control.Settings.Version;
		}
		else {
			if (navigator.plugins['Silverlight Plug-In']) {
				container = document.createElement('div');
				document.body.appendChild(container);
				container.innerHTML = '<embed type="application/x-silverlight" src="data:," />';
				control = container.childNodes[0];
				version = control.description;
			}
		}
		if (control) {
			if (control.isVersionSupported('4.0')) { version = "4.0"; }
			else if (control.isVersionSupported('3.0')) { version = "3.0"; }
			else if (control.isVersionSupported('2.0')) { version = "2.0"; }
			else if (control.isVersionSupported('1.0')) { version = "1.0"; }
		}
	}
	catch (e) { }
	if (container) {
		document.body.removeChild(container);
	}
	return version;
}

function _getDomain() {
	var domain = document.domain;

	// remove "www." if it is contained in the domain
	if (domain.substring(0, 4) == "www.") domain = domain.substring(4);

	var domainParts = domain.split(".");
	var len = domainParts.length;

	// if standard US domain then return domain
	if (len < 3) return domain;

	// get last part of domain parts for country
	var countryPart = domainParts[len - 1];

	// if country is only two letters then return
	if (countryPart.length < 3) return domain;

	// construct domain from the first two parts if none of the other validation worked
	domain = domainParts[len - 2] + "." + domainParts[len - 1];

	return domain;
}

function _getCookie(n) {
	var value = "";
	var cookie = document.cookie; 
	
	if (!cookie) return value;

	var index = cookie.indexOf(n + "=");

	var len = index + n.length + 1;
	
	if (index > -1) {
		var end = cookie.indexOf(";", len);
		if (end < 0) end = cookie.length;
		value = cookie.substring(len, end);
	}
	
	return value;
}

function _getCookieDomain() {
	var domain = _getDomain();

	if ((typeof domain == "undefined") || (domain.length == 0) || (domain.toLowerCase() === "localhost")) return "";

	return "; domain=" + domain;
}

function _clearCookie(n) {
	document.cookie = n + "=; expires=Thu, 01 Jan 1970 00:00:01 GMT; path=/" + _getCookieDomain();
}

function _getTracker(m) {
	var cookieValue = _getCookie(__mfrap);

	if (cookieValue == undefined || cookieValue.length == 0) {
		document.cookie = __mfrap + "=" + Math.uuid() + "; expires=Sun, 18 Jan 2038 00:00:00 GMT; path=/" + _getCookieDomain();

		// get the cookie that was just added
		cookieValue = _getCookie(__mfrap);
	}

	return cookieValue;
}

function _analizeImageLoad() {
	if ((_analizeImage) && typeof _analizeImage.width == "number") {
		if (_analizeImage.width == 3) { _clearCookie(__mfrap); }
	}
}

function _getWindowHeight() {
	var y = 0;

	if (self.innerHeight)
		y = self.innerHeight;
	else if (document.documentElement && document.documentElement.clientHeight)
		y = document.documentElement.clientHeight;
	else if (document.body && document.body.clientHeight)
		y = document.body.clientHeight;

	return y;
}

function _getWindowWidth() {
	var x = 0;

	if (self.innerWidth)
		x = self.innerWidth;
	else if (document.documentElement && document.documentElement.clientWidth)
		x = document.documentElement.clientWidth;
	else if (document.body && document.body.clientWidth)
		x = document.body.clientWidth;

	return x;
}

function reverseAnalize() {

	// get options from document
	if (typeof reverseAnalytics != "undefined" && reverseAnalytics != null) {
		for (var i in reverseAnalytics) {
			if (typeof (reverseAnalytics[i]) != "string") { continue; }
			if (i == "profileId") { _profileId = reverseAnalytics[i]; }
			else if (i == "handler") { _handler = "http://" + reverseAnalytics[i]; }
		}
		reverseAnalytics = null;
	}

	// if the profile identity is not set then don"t bother going any further, because we will be unable to
	// process the request against the profile
	if ((typeof _profileId == "undefined") || (_profileId.length == 0)) return;

	var url = "", ref = "", je = "false", sw = "", sh = "", scd = "", ww = "", wh = "";

	// get random number
	var r = Math.uuid(16);

	// get tracking identity
	var t = _getTracker(__mfrap);
	
	// is the cookie enabled
	var ce = (navigator.cookieEnabled) ? "true" : "false";

	// get the supported silverlight version
	var slv = _getSilverlightVersion();

	// get the supported flash version
	var fv = _getFlashVersion();
	
	// is java enabled
	if (typeof navigator.javaEnabled != "undefined") je = (navigator.javaEnabled) ? "true" : "false";
	
	// get screen resolution
	if (self.screen) {
		sw = self.screen.width;
		sh = self.screen.height; 
		scd = self.screen.colorDepth;
	}

	// get window dimentions
	ww = _getWindowWidth();
	wh = _getWindowHeight();
	
	// get date
	var d = new Date();
	
	// analysis worker image
	var image = _handler + "/" + __mfrap + ".gif?";
	
	// get source
	if (window.location && window.location.href) url = _urlEscape(window.location.href);
	
	// get referrer
	if (window.document && window.document.referrer) ref = _urlEscape(window.document.referrer);

	_analizeImage = new Image();
	_analizeImage.alt = "";
	_analizeImage.src = image + "v=1.0&r=" + r + "&p=" + _profileId + "&t=" + t + "&url=" + url + "&ref=" + ref + "&ce=" + ce + "&je=" + je + "&slv=" + slv + "&fv=" + fv + "&sw=" + sw + "&sh=" + sh + "&scd=" + scd + "&ww=" + ww + "&wh=" + wh + "&d=" + d.getTime() + "&dtzo=" + d.getTimezoneOffset();
	_analizeImage.onload = function() { _analizeImageLoad(); };
}
reverseAnalize();