/**
 * Google Analytics Singleton Class
 * 
 * @version 1.3.1
 * @author Josue Orozco
 * @copyright (c) 2010 OV Web Solutions(TM). All rights reserved.
 */

//------------------------------------------------------
// FIX APPLICATION_ENV Bug.
if(APPLICATION_ENV == undefined || APPLICATION_ENV == 'undefined' || APPLICATION_ENV == null || typeof(APPLICATION_ENV) != 'string'){
	var APPLICATION_ENV = 'production';
}

//------------------------------------------------------
// Holds Asynchronous GA Objects
var _gaq = _gaq || [];

var AnalyticsFactory = function(){
	
	/*
	 * ****************************************
	 * Initialize Variables
	 * ****************************************
	 */
		
		//-----------------------------------------
		// Holds GA Accounts
		this.accounts = new Array();
		
		//-----------------------------------------
		// Holds GA Objects.
		this.pageTracker = new Array();
	//-----------------------------------------
};

AnalyticsFactory.prototype = {
	
	/**
	 * Holds account numbers in array
	 * Example:
	 * GaManager.SetAccounts(["UA-2020108-2", "UA-5910393-1"]);
	 * 
	 * @param {Array} ga_accounts
	 */
	SetAccounts: function(ga_accounts){
		
		for(var i = 0, len = ga_accounts.length; i < len; i++){
			
			this.accounts[i] = ga_accounts[i];
			XBrowser.Log('GaManager.SetAccounts() => ["' + ga_accounts[i] + '"]');
		}
	},

	GetAccounts: function(){
		return this.accounts;
	},

	TrackAsyncPageView: function(page){
		
		//------------------------------------------------------
		// Let's check whether a specific page was
		// requested.
		//
		// If not, then let's grab the current url,
		// and tell GA to track it.
		//
		if(page == undefined || page == ''){
			
			page = this.GetCurrentPage();
		}

		//------------------------------------------------------
		// Check to see if environment was overwritten or the 
		// current XBrowser Application Environment
		if(XBrowser.GetUrlParams('xbrowser-app-env') == 'development' || XBrowser.GetApplicationEnvironment() == 'development'){
		
			//------------------------------------------------------
			// Either production was overwritten, or We're not in 
			// production, so let's pretend to call a page view, 
			// and log the results
			for(var i = 0, len = this.accounts.length; i < len; i++){

				XBrowser.Log('SIMULATING ASYNC. PAGEVIEW : _gaq.push(["m'+i+'._setAccount", '+String(this.accounts[i])+'])');
				XBrowser.Log('SIMULATING ASYNC. PAGEVIEW: _gaq.push(["m'+i+'._trackPageview", '+String(page)+'])');
			}
		} else {
			
			//-----------------------------------------
			// PRODUCTION
			// Let's go through each account, and initialize
			// a page tracker
			for(var i = 0, len = this.accounts.length; i < len; i++){
			
				//------------------------------------------------------
				// Live tracking code here
				_gaq.push(["m"+i+"._setAccount", String(this.accounts[i])]);
				_gaq.push(["m"+i+"._trackPageview", String(page)]);

				//------------------------------------------------------
				// Logging
				XBrowser.Log('EXECUTING LIVE ASYNC. PAGEVIEW : _gaq.push(["m'+i+'._setAccount", '+ String(this.accounts[i]) +'])');
				XBrowser.Log('EXECUTING LIVE ASYNC. PAGEVIEW : _gaq.push(["m'+i+'._trackPageview", '+String(page)+'])');
			}
		}
	},

	/**
	 * Track a page view in Google Analytics.
	 * 
	 * @param {String} page		// the page you want to track
	 */
	TrackPageView: function(page){
	
		//-----------------------------------------
		// Let's check whether a specific page was
		// requested.
		//
		// If not, then let's grab the current url,
		// and tell GA to track it.
		//
		if(page == undefined || page == ''){
		
			page = this.GetCurrentPage();
		}

		//------------------------------------------------------
		// Check to see if environment was overwritten or the 
		// current XBrowser Application Environment
		if(XBrowser.GetUrlParams('xbrowser-app-env') == 'development' || XBrowser.GetApplicationEnvironment() == 'development'){
			
			//------------------------------------------------------
			// Either production was overwritten, or We're not in 
			// production, so let's pretend to call a page view, 
			// and log the results
			for(var i = 0, len = this.accounts.length; i < len; i++){
				XBrowser.Log('SIMULATING PAGEVIEW : this.pageTracker['+i+'] = _gat._getTracker('+String(this.accounts[i])+')');
				XBrowser.Log('SIMULATING PAGEVIEW : this.pageTracker['+i+']._trackPageview('+String(page)+')');
			}
		} else {

			//------------------------------------------------------
			// Let's go through each account, and initialize
			// a page tracker
			for(var i = 0, len = this.accounts.length; i < len; i++){
			
				try {
					//-----------------------------------------
					// Get the object for each GA Account.
					this.pageTracker[i] = _gat._getTracker(String(this.accounts[i]));
			
					//-----------------------------------------
					// DEPRECATED
					// Initialize data for each GA Account.
					//this.pageTracker[i]._initData();
			
					//-----------------------------------------
					// Track the pageview.
					this.pageTracker[i]._trackPageview(String(page));

					XBrowser.Log('EXECUTING LIVE PAGEVIEW : this.pageTracker['+i+'] = _gat._getTracker('+String(this.accounts[i])+')');
					XBrowser.Log('EXECUTING LIVE PAGEVIEW : this.pageTracker['+i+']._trackPageview('+String(page)+')');

					return true;
				} catch(e){
					try {

						XBrowser.Log('GaManager.TrackPageView() Failed => ' + e);
					} catch(err){

						//------------------------------------------------------
						// Fail silently
					}

					return false;
				}
			}
		}
	},

	/**
	 * Gets the current page
	 * @access private
	 */
	GetCurrentPage: function(){
		
		//-----------------------------------------
			// Get Url protocol
			url_protocol = (("https:" == document.location.protocol) ? "https://" : "http://");
			
			//-----------------------------------------
			// Grab entire url
			url = window.location.href;
			
			//-----------------------------------------
			// BUG: Some urls are encoded, thus the need
			// for unique URIs.
			// Turn to lower case
			//url = url.toLowerCase();
			
			//-----------------------------------------
			// Get rid of protocol (e.g. https:// || http://)
			url = url.replace(url_protocol, '');
			
			//-----------------------------------------
			// Get rid of domain (e.g. www.orozcovision.com)
			url = url.replace(document.domain, '');
	
			XBrowser.Log('GaManager.GetCurrentPage() => ' + url);

			//-----------------------------------------
			// Define page
			return url;
	},

	TrackUrchinConversion: function(uacct, goal){
		
		if(uacct == undefined || uacct == ''){
			throw new Error('_uacct cannot be null and/or blank.');
		}
		
		if(goal == undefined || goal == ''){
			throw new Error('Goal cannot be null and/or blank.');
		}
		
		try {

			_uff = 0; // Reset for multiple accounts
			_uacct = uacct;
			urchinTracker(goal);
		} catch (err) {}
	},

	_uGA: function(l, n, s){

		//------------------------------------------------------
		// Used to obtain a value from a string of key=value pairs
		if(!l || l=="" || !n || n == "" || !s || s == "") return "-";

		var i, i2, i3, c="-";

		i=l.indexOf(n);
		i3=n.indexOf("=")+1;

		if(i > -1){

			i2=l.indexOf(s, i);
			if(i2 < 0){

				i2=l.length;
			}

			c=l.substring((i+i3), i2);
		}

		return c;
	},

	/**
	 * Sessionizes Visitor Labels.
	 * Sets the cookie value, as specified by (label)
	 * to expire after 30 minutes. Visitors that return
	 * later than this specified time period will receive
	 * a new visit label.
	 */ 
	SetVisitorLabel: function(label){
		
		for(var i = 0, len = this.accounts.length; i < len; i++){
			
			//------------------------------------------------------
			// Apply label
			this.pageTracker[i]._setVar(label);
			
			//------------------------------------------------------
			// Sessionize Visitor Label
			date = new Date();
			date.setTime(date.getTime() + 1*60*60*1000);
			
			document.cookie = "__utmv="+_udh+"."+_uES(label)+";path="+_utcp+"; expires="+date.toGMTString()+";"+_udo;
		}
	}
};

/**
 * Instantiate Global Scope Google Analytics Manager
 */
XBrowser.Log('Instantiating GaManager');
if(typeof(GaManager) != 'object'){
	try {
		var GaManager = new AnalyticsFactory();
		XBrowser.Log('GaManager Ready.');
	} catch(e){

		XBrowser.Log('Failed to instantiate GaManager => ' + e);
	}
} else {
	XBrowser.Log('Deferring GaManager Instantiation: Already available');
}
