var _googleAnalytics = new function() {};

// We name the handler for binding, to make sure no other functions are caught in the crossfire of the unbind
_googleAnalytics.bindClick = function() {
	var classes = $(this).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.
	//
	// Unfortunately, hasClass method does not support wildcard.
	//  So I have to loop through classes to find what I need.
	
	var classNameToFindCategory  = 'GA_Track_Category_';
	var classNameToFindAction    = 'GA_Track_Action_';
	var category                 = '';
	var action                   = '';
	var value                    = null;
	
	$(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;
		}
	});
	
	if ($(this).hasClass('GA_Track_Select')) {
		value = $(this).val();
	}

	_googleAnalytics.PushTrackEvent(category, action, value);
}

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

		// If the function is called more than once, we don't want multiple bindings
		$('.GA_Track_Select').unbind('change', _googleAnalytics.bindClick);
		$('.GA_Track_Select').bind('change', _googleAnalytics.bindClick);
	}
};

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

_googleAnalytics.PushTrackEvent = function(category, action, value) {
	value = (typeof value == 'undefined' || isNaN(value)) ? null : value;
	
	if (value != null) {
		value = Number(value);
	}
	
	var currentDomain = document.domain;
	var currentPage   = window.location.pathname;
	var url           = currentDomain + currentPage;
    var isDownload    = action.indexOf('Download');
    
    if (category.indexOf('Player') >= 0) {
        category = category + '-Freetour';
    }

	$(_googleAnalyticsAccounts).each(function() {
		_gaq.push([this + '._trackEvent', category, action, url, value]);
		
		if (isDownload >= 0) {
            sleep(200);
		}
	});
};

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