var AnalyticsManager = new Class({
	Implements: [Options, Events, Log],

	UAID: null,
	NAME: '',//avoid conflicts if others use the GA also on the same document

	options: 
	{
		onLoadTrackPageView: true,/* track page view or not on initial load*/
		pageViewStr: null,/*you should start your page name with a leading slash '/'*/
		shouldLog: false,/* console logging for firebug*/
		duplicateAsPageView: false,
		domainName: null
    },

	initialize: function(UAID, NAME, options) 
	{
		//this.enableLog();
//		this.disableLog();

		this.log("AnalyticsManager::initialize()");
		
		this.UAID = UAID;
		if(NAME)
		{
			this.NAME = NAME+'.';
		}
		this.setOptions(options);
		this.log('UAID ' + this.UAID);
		this.log('NAME ' + this.NAME);
		this.log('options.domainName ' + this.options.domainName);
		window._gaq = window._gaq || [];//global level variable
		this._gaq = window._gaq;//reference to global variable
		this._gaq.push([this.NAME+'_setAccount', this.UAID]);
		if(this.options.onLoadTrackPageView)
		{
			this.trackPage(this.options.pageViewStr);
		}
		if(this.options.domainName)
		{
			this._gaq.push([this.NAME+'_setDomainName', this.options.domainName]);
		}
		this.getGA();
	},

	getGA:function()
	{
		this.log("AnalyticsManager::getGA()");
		
		var ga = document.createElement('script');
		ga.type = 'text/javascript';
		ga.async = true;
		ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
		var s = document.getElementsByTagName('script')[0];
		s.parentNode.insertBefore(ga, s);
	},

	pushed: function(description)
	{
		this.log("AnalyticsManager::pushed(" + description + ")");
		
		this.fireEvent('pushed', description);
	},

	trackPage:function(name)
	{
		this.log("AnalyticsManager::trackPage(" + name + ")");
		
		if(name)
		{
			this._gaq.push([this.NAME + '_trackPageview', name]);
			this.pushed('pageview '+ name);
		}
		else
		{
			this._gaq.push([this.NAME + '_trackPageview']);
			this.pushed('pageview');
		}
	},

	trackEvent: function(category, action, opt_label, opt_value)
	{
		this.log("AnalyticsManager::trackEvent(" + category + ", " + action + ", " + opt_label + ", " + opt_value + ")");
		
		this._gaq = window._gaq;//otherwise loses reference to the google _gaq object
		var descriptionStr = '/click/' + category + '/' + action
		if(!opt_label)
		{
			opt_label = null;
		}
		else
		{
			descriptionStr += '/' + opt_label;
		}
		if(!opt_value)
		{
			opt_value = null;
		}
		else
		{
			descriptionStr += '/' + opt_value;
		}
		this._gaq.push([this.NAME + '_trackEvent', category, action, opt_label, opt_value]);
		this.pushed(descriptionStr);
		if(this.options.duplicateAsPageView)
		{
			this._gaq.push([this.NAME + '_trackPageview', descriptionStr]);
			this.pushed('pv ' + descriptionStr);
		}
	}
});
