window.addEvent('domready', function(){

	$$('.trackevent').each( function(el){
		el.addEvent('click', trackclick.bindWithEvent(this));
	});

	$$('.trackeventnow').each( function(el){
		el.addEvent('click', trackclicknow.bindWithEvent(this));
	});

});

// This one is for javascript links
function trackclick(e) {
	var el = $(e.target);
	trackLink(el.getProperty('rev'), true);
}

// This one is for buttons and regular links
function trackclicknow(e) {
	var el = $(e.target);
	trackLink(el.getProperty('rev'), false);
}

// Wrapper to run this asynchronously
// This decodes from JSON into an obj, then reencodes it for the offset
function trackLink(objstring, delay) {
	if (typeof objstring == 'object') {
		var obj = objstring;
	} else {
		var obj = Json.evaluate(objstring);
	}
	if (delay) {
		window.setTimeout('doTrackLink(\''+Json.toString(obj)+'\');', 1);
	} else {
		doTrackLink(Json.toString(obj));
	}
}

// Where the work is done. Should not be called directly.
function doTrackLink(objstring) {

	// Parse the objstring into an object
	var obj = Json.evaluate(objstring);

	// Create new tracking object
	// Not sure why we don't use the one already created,
	// but the s_gi(s_account) part is in /js/lib/s_code.js
	var omTrack = s_gi(s_account);
	// List events (currently only one per link)
	var omEvents = '';
	// We'll be adding things to this
	var omTrackVars = [];

	// If there are events, need to enter it only once into the vars
	if (obj['events']) omTrackVars.push('events');

	// The obj parameter contains the things that need to be tracked.
	for (var key in obj) {
		if (key == 'events') {
			// Add event17 on all tracked links
			omEvents = 'event17,' + obj[key];
		} else {
			omTrack[key] = obj[key];
			omTrackVars.push(key);
		}
	}
	omTrack.linkTrackVars = '';
	omTrack.linkTrackVars = omTrackVars.join();
	omTrack.linkTrackEvents = omEvents;
	omTrack.events = omEvents;

	// Run the function that sends the tracking info
	omTrack.tl();
}

