﻿var ref_id = '';
var l_id = '';
var options = { path: '/', expires: 5 };
var b_debug = false;
var s_debug = '';

$(document).ready(function () {
	// Try querystring
	try {
		ref_id = '' + $.query.get('VPID');

		if (ref_id.length > 0) {
			$.cookie("ga_ref", ref_id, options);
		}
	}
	catch (ex) {
		// Do nothing
	}

	// Try querystring2 (L)
	try {
		l_id = '' + $.query.get('L');

		if (l_id.length > 0) {
			$.cookie("ga_link", l_id, options);
		}
	}
	catch (ex) {
		//
	}

	// Try querystring3 (debug)
	try {
		var checkDebug = '' + $.query.get('debug');

		if (checkDebug.length > 0) {
			b_debug = true;
		}
	}
	catch (ex) {
		//
	}

	// Try for cookie
	if (ref_id.length <= 0) {
		ref_id = $.cookie("ga_ref");

		if (ref_id == null) {
			ref_id = '';
		}
	}

	// Try for cookie 2
	if (l_id.length <= 0) {
		l_id = $.cookie("ga_link");

		if (l_id == null) {
			l_id = '';
		}
	}

	if (b_debug) {
		s_debug = 'VPID=' + ref_id + '\n';
		s_debug += 'L=' + l_id + '\n';

		alert('DEBUG:\n\n' + s_debug);
	}

	$("a").click(function () {
		if (ref_id.length > 0)
			updateLinks($(this).attr("href"));
	});
});

updateLinks = function (linkUrl) {
	try {
		var newLinkUrl = "";
		var oldLinkUrl = linkUrl;

		newLinkUrl = "/[" + ref_id;

		if (String(l_id).length > 0) {
			newLinkUrl += "/L" + l_id;
		}
		newLinkUrl += "]";

		if (linkUrl.length > 0 && linkUrl.substring(0, 1) == "/") {
			newLinkUrl += linkUrl;
		}
		else {
			newLinkUrl += "/" + linkUrl;
		}

		if (b_debug) {
			s_debug = 'Old URL=' + oldLinkUrl + '\n';
			s_debug += 'New URL=' + newLinkUrl + '\n';

			alert('DEBUG:\n\n' + s_debug);
		}

		pageTracker._trackPageview(newLinkUrl);
	}
	catch (ex) {
		if (b_debug) {
			alert('Error:' + ex.description);

			return false;
		}
	}
}