/**
 * GAAPI Constructor.  Initialise the GA tracking.
 * 
 * @param webId			Your UA-XXXXX-X code
 * @param doLoadScript	Optional.  defaults to true.  Set to false to 
 * 						defer loading until .loadScript() is called 
 * @returns {GAAPI}
 */
var _gaq = _gaq || [];		// global GA var
var pageTracker = null
function GAAPI( webId, doLoadScript )
{
	// Allows user to not have to do a conditional everytime they want to call a tracking method 
	if ( webId == '' ){
		this._disable = true;
	}

	if ( doLoadScript == null ) 
	   doLoadScript = true;
	this._webId = webId;

	_gaq.push(['_setAccount', this._webId ]);
	_gaq.push(['_trackPageview']);
	_gaq.push(function() {  pageTracker = _gat._createTracker(this._webId, 'pageTracker'); } );
	// backwards compat
	
	// Allows delayed loading of GA tracking script
	if ( doLoadScript )	this.loadScript();

}

/**
 * GAAPI Class
 */
GAAPI.prototype = 
{
	/**
	 * Set to true by the constructor if no webid is given.  Methods can still be called but
	 * will just return 
	 */
	_disable: false,
	
	MILLISECONDS: 1,
	SECONDS: 1000,
	MINUTES: 60000,
	HOURS: 60000 * 60,
		
	_debugMode: false,
	_startTimes: new Array(),
	_timerUnitDivisor: 1,
	
	/**
	 * Load the GA.js script.  Called implicitly by the constructor unless disabled.
	 * @return {GAAPI}
	 */
	loadScript: function ()
	{
		if ( this._disable ) return this;
		
		(function() {
		    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);
		  })();
		return this;
	},
	
	/**
	 * Engages the debug mode where tracking calls are console.log'ed and not sent to
	 * GA
	 * @param	val		Defaults to true. Set to false to clear debug mode.
	 * @return	{GAAPI}
	 */
	setDebugMode: function ( val ) 
	{ 
		if ( val == null )	val = true;
		this._debugMode = Boolean(val); 
		return this;
	},
	
	trackEvent: function ( categ, action, label, value )
	{
		if ( this._debugMode )
			this._logEvent( categ, action, label, value );
		else if ( !this._disable )
			_gaq.push( [ '_trackEvent', categ, action, label, value ] );
	},
	
	/**
	 * Set and reset the start time against which to measure trackTime() calls
	 * @return this
	 */
	startTimer: function ( index )
	{
		var now = (new Date()).getTime();
		if ( index != null )
			this._startTimes[ index ] = now;
		else
			this._startTimes.push( now );
		
		return this;
	},
	
	/**
	 * Set the units which trackTime() calls will pass as the value.
	 * 
	 * @param	unit	See class constants, MILLISECONDS, SECONDS, etc.
	 * @return this
	 */
	setTimerUnits: function ( unit )
	{
		// Validate, defaulting to milliseconds
		switch ( unit )
		{
			case this.MILLISECONDS:
			case this.SECONDS:
			case this.MINUTES:
			case this.HOURS:
				this._timerUnitDivisor = unit;
				break;
			default:
				this._timerUnitDivisor = this.MILLISECONDS;
		}
		return this;
	},
	
	/**
	 * Track the time elapsed since initTimer() was called in the units previously specified
	 * by setTimerUnits() 
	 * @param	categ	
	 * @param	categ	
	 * @param	categ	
	 * @param	timerIndex	Optional index for the timer to use.  Defaults to the last set timer start time
	 * @return this 
	 */
	trackTime: function ( categ, action, label, timerIndex )
	{
		var startTime = ( timerIndex == null )
			? this._startTimes[this._startTimes.length - 1]  // get the latest
			: this._startTimes[ timerIndex ];
		var time = this._getTimeElapsed( startTime );
		return this.trackEvent( categ, action, label, time );
	},
	
	/**
	 * Gets the elapsed time from the start time given 
	 * 
	 * @param	startTime	The start time in milliseconds
	 * @return	int 
	 */
	_getTimeElapsed: function ( startTime )
	{
		var time = (new Date()).getTime() - startTime;
		return Math.round( time / this._timerUnitDivisor );
	},
	
	/**
	 * Logs to the console a tracked event
	 * @return this
	 */
	_logEvent: function ( categ, action, label, value )
	{
		var str = [ categ, action, label, value ].join( ' | ');
		console.log( "GAAPI Event Tracked: " + str );
		return this;
	}
}


