/*
 * initialize tracker
 */
var batstack = {};
var batstackpos = 0;
var browserHasCookies = hasCookies();
var screenAlias = screen;
var windowAlias = window;
//var pageReferrer = getReferrer();
var pageReferrer= 0;

// Maximum delay to wait for web bug image to be fetched (in milliseconds)
var configTrackerPause = 500;
			
/*
 * encode or escape
 * - encodeURIComponent added in IE5.5
 */
var escapeWrapper = windowAlias.encodeURIComponent || escape;

/*
 * decode or unescape
 * - decodeURIComponent added in IE5.5
 */
unescapeWrapper = windowAlias.decodeURIComponent || unescape;

function bat_eat(accio,objecte)
{
	batstack[batstackpos] = accio;
	batstackpos = batstackpos + 1;
    batstack[batstackpos] = objecte;
    batstackpos = batstackpos + 1;
     	
}

function getImage(url) {
	var now = new Date(),
	image = new Image(1, 1);

	expireDateTime = now.getTime() + configTrackerPause;

	image.onLoad = function () { };
	image.src = url;
}

/*
 * Returns the URL to call bat.php, 
 * with the standard parameters (resolution, url, referer, etc.)
 */
function getRequest() {
	var i, now, request;
	now = new Date();
	request = 'url=' + escapeWrapper(document.location.href) +
	        '&res=' + screenAlias.width + 'x' + screenAlias.height +
	        '&h=' + now.getHours() + '&m=' + now.getMinutes() + '&s=' + now.getSeconds() +
	        '&cookie=' + browserHasCookies +
	        '&urlref=' + escapeWrapper(pageReferrer) +
	        '&rand=' + Math.random();

	request =  'http://bat.adforum.com/bat.php' + '?' + request;
	return request;
}

/*
 * Does browser have cookies enabled (for this site)?
 */
function hasCookies() {
	var testCookieName = '_pk_testcookie';
	if (!isDefined(navigator.cookieEnabled)) {
		setCookie(testCookieName, '1');
		return getCookie(testCookieName) == '1' ? '1' : '0';
	}

	return navigator.cookieEnabled ? '1' : '0';
}

/*
 * Is property (or variable) defined?
 */
function isDefined(property) {
	return typeof property !== 'undefined';
}

/*
 * Get page referrer
 
function getReferrer() {
	var referrer = '';
	try {
		referrer = top.document.referrer;
	} catch (e) {
		if (parent) {
			try {
				referrer = parent.document.referrer;
			} catch (e2) {
				referrer = '';
			}
		}
	}
	if (referrer === '') {
		referrer = document.referrer;
	}

	return referrer;
}  */
function bat_cave(aff)
{
	if (batstackpos > 0){
    
        request = getRequest();
	    request += '&aff='+aff+'&data=' + escapeWrapper(stringify(batstack));
	    
	    getImage(request);
		batstack={};
		batstackpos=0;
		
    
    }
	//alert(request);
	
	/*$.post("http://bat.adforum.com.php5-5.dfw1-1.websitetestlink.com/bat.php", batstack);*/
	
	
	
	
	//var pkBaseURL = (("https:" == document.location.protocol) ? "https://bat.adforum.com.php5-5.dfw1-1.websitetestlink.com/piwik/" : "http://bat.adforum.com.php5-5.dfw1-1.websitetestlink.com/piwik/");
	//document.write(unescape("%3Cscript src='" + pkBaseURL + "piwik.js' type='text/javascript'%3E%3C/script%3E"));

	//try {
	//	var piwikTracker = Piwik.getTracker(pkBaseURL + "piwik.php", 1);
	//	piwikTracker.trackPageView();
	//	piwikTracker.enableLinkTracking();
	//}
	//catch( err ) {}
}

/*
 * stringify
 * - based on public domain JSON implementation at http://www.json.org/json2.js (2009-04-16)
 */
function stringify(value) {

	var escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,
		// table of character substitutions
		meta = {'\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\'};

	// If the string contains no control characters, no quote characters, and no
	// backslash characters, then we can safely slap some quotes around it.
	// Otherwise we must also replace the offending characters with safe escape
	// sequences.
	function quote(string) {
		escapable.lastIndex = 0;
		return escapable.test(string) ?
			'"' + string.replace(escapable, function (a) {
				var c = meta[a];
				return typeof c === 'string' ? c :
					'\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4);
			}) + '"' :
			'"' + string + '"';
	}

	function f(n) {
		return n < 10 ? '0' + n : n;
	}

	// Produce a string from holder[key].
	function str(key, holder) {
		var i,          // The loop counter.
			k,          // The member key.
			v,          // The member value.
			partial,
			value = holder[key];

		if (value === null) {
			return 'null';
		}

		// If the value has a toJSON method, call it to obtain a replacement value.
		if (value && typeof value === 'object' && typeof value.toJSON === 'function') {
			value = value.toJSON(key);
		}

		// What happens next depends on the value's type.
		switch (typeof value) {
		case 'string':
			return quote(value);

		case 'number':
			// JSON numbers must be finite. Encode non-finite numbers as null.
			return isFinite(value) ? String(value) : 'null';

		case 'boolean':
		case 'null':
			// If the value is a boolean or null, convert it to a string. Note:
			// typeof null does not produce 'null'. The case is included here in
			// the remote chance that this gets fixed someday.
			return String(value);

        case 'object':
			// Make an array to hold the partial results of stringifying this object value.
			partial = [];

			// Is the value an array?
			// if (Object.prototype.toString.call(value)=="[object Array]") {	// call added in IE5.5
			if (value instanceof Array) {
				// The value is an array. Stringify every element. Use null as a placeholder
				// for non-JSON values.
				for (i = 0; i < value.length; i++) {
					partial[i] = str(i, value) || 'null';
				}

				// Join all of the elements together, separated with commas, and wrap them in
				// brackets.
				v = partial.length === 0 ? '[]' : '[' + partial.join(',') + ']';
				return v;
			}

			// if (Object.prototype.toString.call(value)=="[object Date]") {	// call added in IE5.5
			if (value instanceof Date) {
				return quote(value.getUTCFullYear()   + '-' +
				           f(value.getUTCMonth() + 1) + '-' +
				           f(value.getUTCDate())      + 'T' +
				           f(value.getUTCHours())     + ':' +
				           f(value.getUTCMinutes())   + ':' +
				           f(value.getUTCSeconds())   + 'Z');
			}

			// Otherwise, iterate through all of the keys in the object.
			for (k in value) {
				v = str(k, value);
				if (v) {
					// partial.push(quote(k) + ':' + v); // array.push added in IE5.5
					partial[partial.length] = quote(k) + ':' + v;
				}
			}

			// Join all of the member texts together, separated with commas,
			// and wrap them in braces.
			v = partial.length === 0 ? '{}' : '{' + partial.join(',') + '}';
			return v;
		}
	}

	return str('', {'': value});
}