/**
 * javascript object for pulse statistcs. Copyright 2009 :torweg free software
 * group Licensed under the GPLv3 or later (<http://www.gnu.org/licenses/>)
 */
pulse_statistics = {
	/**
	 * @return the appropriate XHR object or false.
	 */
	getHTTPObject : function() {
		var http = false;
		/*
		 * IE --> ActiveX
		 */
		if (typeof ActiveXObject != 'undefined') {
			try {
				http = new ActiveXObject("Msxml2.XMLHTTP");
			} catch (e) {
				try {
					http = new ActiveXObject("Microsoft.XMLHTTP");
				} catch (E) {
					http = false;
				}
			}
			/*
			 * else try XMLHttpRequest.
			 */
		} else if (window.XMLHttpRequest) {
			try {
				http = new XMLHttpRequest();
			} catch (e) {
				http = false;
			}
		}
		return http;
	},
	/**
	 * records the given path with the pulse statistics module located at URL.
	 * 
	 * @param url
	 *            the URL to the statistics recording server
	 * @param pa
	 *            the path to be recorded
	 * @param sid
	 *            the id of the statistics server
	 * @param enc
	 *            boolean indicating whether to URL encode the path
	 */
	record : function(url, pa, sid, enc) {
		var http = false;
		// protocol
		pr = document.location.protocol;

		// check url to be SSL, if document.location.protocol is https
		if ((pr == 'https:') && (url.indexOf("https:") !== 0)
				&& (url.indexOf("://") !== -1)) {
			url = "https://" + url.substring(url.indexOf("://") + 3);
		}

		if ((url.indexOf('://') === -1)
				|| (url.indexOf(pr + '//' + document.location.hostname) === 0)) {
			http = this.getHTTPObject();
		}
		if (enc === true) {
			try {
				pa = encodeURIComponent(pa);
			} catch (e) {
			}
		}

		url += '?path=' + pa;
		url += '&serverId=' + sid;

		try {
			// always encode the referrer
			url += '&ref=' + encodeURIComponent(document.referrer);
		} catch (e) {
		}
		try {
			// screen-resolution
			url += '&x=' + screen.width + '&y=' + screen.height;
		} catch (e) {
		}
		try {
			// viewport size
			if (typeof window.innerWidth != 'undefined') {
				// modern browsers
				url += '&vx=' + window.innerWidth + '&vy=' + window.innerHeight;
			} else {
				// try IE6 style
				url += '&vx=' + document.documentElement.clientWidth + '&vy='
						+ document.documentElement.clientHeight;
			}
		} catch (e) {
		}
		url += '&ts=' + new Date().getTime();

		/*
		 * no XHR, load an image instead.
		 */
		if (!http) {
			try {
				img = new Image();
				img.src = url;
			} catch (e) {
			}
			return;
		}

		/*
		 * do XHR.
		 */
		url += '&xhr=true';
		if (http.overrideMimeType) {
			http.overrideMimeType('text/xml');
		}
		http.open("GET", url, true);
		http.onreadystatechange = function() {
		};
		http.send(null);
	}
};

