var _googleAnalytics = new function() {};

/**
 * This function is triggered when a tracked element is clicked. Or, for GA_Track_Live, when it is displayed;
 */
_googleAnalytics.bindClick = function(element) {
	var classes = jQuery(element).attr('class');
	var c       = classes.split(' ');

	// I have to find the link Category and action.
	//  Since some browsers may not support "unofficial" tag attributes,
	//  I chose the "class" attributes to feed this.
	//  "title" could not be used since it appears in tooltips, and
	//  "rel" may be already used.

	var classNameToFindCategory  = 'GA_Track_Category_';
	var classNameToFindAction    = 'GA_Track_Action_';
	var category                 = '';
	var action                   = '';

	// Unfortunately, hasClass method does not support wildcard.
	//  So I have to loop through classes to find what I need.
	jQuery(c).each(function() {
		if (this.indexOf(classNameToFindCategory) >= 0) {
			category = this.substr(classNameToFindCategory.length);
		}

		if (this.indexOf(classNameToFindAction) >= 0) {
			action = this.substr(classNameToFindAction.length);
		}

		if (category != '' && action != '') {
			// Leaves the loop.
			return;
		}
	});

	_googleAnalytics.PushTrackEvent(category, action);
};

_googleAnalytics.bindClasses = function() {
	if (typeof _googleAnalyticsAccounts != 'undefined') {
		jQuery('.GA_Track').bind('click', function() {
			_googleAnalytics.bindClick(this);
		});
		// If the function is called more than once, we don't want multiple bindings
		jQuery('.GA_Track').removeClass('GA_Track');

		jQuery('.GA_Track_Live').css('display', 'none');
		jQuery('.GA_Track_Live').each(function() {
			_googleAnalytics.bindClick(this);
			// We don't want tracking to happen twice for a live element, so we remove the class.
			jQuery(this).removeClass('GA_Track_Live');
		});
	}
};

jQuery(document).ready(function() {
	_googleAnalytics.bindClasses();
});

_googleAnalytics.PushTrackEvent = function(category, action, value) {
	value = (typeof value == 'undefined' || isNaN(value)) ? null : value;

	var currentDomain = document.domain;
	var currentPage   = window.location.pathname;
	var url           = currentDomain + currentPage;
    var isDownload    = action.indexOf("Download");

    if (category.indexOf("Player") >= 0) {
    	var section = (url.indexOf("members.") >= 0) ? "-Members" : "-Freetour";
        category    = category + section;
    }

    jQuery(_googleAnalyticsAccounts).each(function() {
		_gaq.push([this + '._trackEvent', category, action, url, value]);

		if (isDownload >= 0) {
			_googleAnalytics.sleep(200);
		}
	});
};

_googleAnalytics.sleep = function(milliseconds) {
	var start = new Date().getTime();

	while ((new Date().getTime() - start) < milliseconds) {
		// Waiting for milliseconds
	}
};
