// $Id: tracking.js 5675 2009-07-24 19:29:00Z gmatthes $

var dmo = (window.dmo) ? dmo : {};

var gaURL = (location.href.indexOf('https') == 0 ? 'https://ssl' : 'http://www');
gaURL += '.google-analytics.com/ga.js?rnd='+Math.floor(Math.random()*11);

//if(typeof(_gat)!='object') {
	try{
		$.getScript(gaURL, function(){ dmo.initTracking(); });
	}
	catch(err) {
		document.write("<script src='" + gaURL + "' type='text/javascript'></script>");
		//console.log('Failed to load Google Analytics:' + err);
	}
/*}
else {
	dmo.initTracking();
}
*/

dmo.initTracking = function() {
	if (trackingOptions) { dmo.tracker = new Tracker(trackingOptions); } 
	else { dmo.tracker = new Tracker();	}
}

// --------------- [ Constants ] --------------
var Transaction = {
	Category : { Regular : 'Regular', Complimentary : 'Complimentary', AllAccess : 'All Access' },
	Property : { OrderID : 'orderId', Affiliate : 'affiliate', ProductID : 'productId', ProductDescription : 'description', Category : 'category', Price : 'price',	Tax : 'tax', Total : 'total', City : 'city', State : 'state', Country : 'country', Shipping : 'shipping', Quantity : 'quantity' }
};
var Event = {
	Category : { Link : 'link',	Singup : 'signup', VMO : 'vmo',	Homepage : 'homepage', Form : 'form' },
	Action : { Click : 'click',	Fill : 'fill', Submit : 'submit' }
};

// --------------- [ Tracking Class ] ---------------

function Tracker() {
	this._options = null;
	if (arguments.length > 0) { this.setOptions(arguments[0]); }

	if(this._options.url) this._url = this._options.url;
	else this._url = location.pathname;
	this._aMember = /\/account/.test(location.pathname);
	
	// default value for transactions	
	this._transVars = {
		orderId : '',
		affiliate : '',
		productId : '',
		description : '',
		category : '',
		price : 'unknown',
		tax : '0.00',
		total : '0.00',
		city : '',
		state : '',
		country : '',
		shipping : '0.00',
		quantity : '1'
	};
	var _root = this;

	this._fired = {};
	this.init();
}


Tracker.prototype = {
	// --- [ properties ] ---
	getOptions : function() { return this._options; },
	
	setOptions : function(options) {
		var settings = $.extend({
		}, options || {
			account: '',
			links: { 
				external: '/external/',
				mailto: '/mailto/',
				downloads: '/downloads/',
				extensions: [ 'pdf','doc','xls','csv','jpg','gif','mp3','swf','txt','ppt','zip','gz','dmg','xml', 'js']
			}
		});

		this._options = settings;
	},
	
	getPageTracker : function() { return this._pageTracker; },
	
	// --- [ methods ] ---
	setTransactionVar : function(name, value) {
		this._transVars[name] = value;
	},
	
	submitTransaction : function() {
		var pageTracker = this._pageTracker;
		var arg = this._transVars;
		
		pageTracker._addTrans(
			arg.orderId,						// order id
			arg.affiliate,						// affiliate
			arg.total,							// total
			arg.tax,							// tax
			arg.shipping,						// shipping
			arg.city,							// city
			arg.state,							// state
			arg.country							// country
		);
		
		pageTracker._addItem(
			arg.orderId,						// order id
			arg.productId,						// SKU/Code (product id)
			arg.description,					// product name
			arg.category,						// variation on product							
			arg.price,							// price
			arg.quantity						// quantity
		);
		
		pageTracker._trackTrans();
	},
	
	isAMember : function() {
		return this._aMember;
	},
	
	// _trackEvent(category, action, optional_label, optional_value)
	trackEvent : function(category, action, label, value) {
		var len = arguments.length;
		var pageTracker = this._pageTracker;
		
		if (len >= 4) {
			pageTracker._trackEvent(category, action, label, value);
		} else if (len == 3) {
			pageTracker._trackEvent(category, action, label);
		} else {
			pageTracker._trackEvent(category, action);
		}
			
	},
	
	trackPageView : function(url) {
		//if (!this._fired[url]) {
			this._pageTracker._trackPageview(url);
			this._fired[url] = true;
		//}
	},

	init : function init() {
		var pageTracker = _gat._getTracker(this._options.account);
		pageTracker._setAllowAnchor(true);
		pageTracker._setDomainName(".dailymakeover.com");
		pageTracker._initData();

		var rid = this._options.userLevel;
		if(rid == 2){ pageTracker._setVar('Free User');	}
		else if(rid == 3){ pageTracker._setVar('Paid User'); }
		else if(rid >= 4){ pageTracker._setVar('Internal User'); }
		pageTracker._trackPageview(this._url);
		var opts = this._options;
	
		/* --- track special links ---
		$('a').each(function(){
			var u = $(this).attr('href');
			
			if(typeof(u) != 'undefined'){
				var newLink = decorateLink(u);
				
				if(newLink.length){
					$(this).click(function(){
						pageTracker._trackPageview(newLink);
					});
				}
			}				
		});*/
		
		// --- if aMember page, track form interactions ---
	/*	if (this._aMember) {
			path = location.pathname;
			if (path.substr(path.length - 1) != '/') {
				path += '/';
			}
			
			$("input").bind('blur', function () {
				path += $(this).attr('name');
				pageTracker._trackEvent(Event.Category.Form, Event.Action.Fill, path);
			});
			
			$("select").bind('change', function () {
				path += $(this).attr('name');
				pageTracker._trackEvent(Event.Category.Form, Event.Action.Fill, path);
			});
			
			$("textarea").bind('blur', function () {
				path += $(this).attr('name');
				pageTracker._trackEvent(Event.Category.Form, Event.Action.Fill, path);
			});
			
			$("button").bind('click', function () {
				path += $(this).attr('name');
				pageTracker._trackEvent(Event.Category.Form, Event.Action.Click, path);
			});
		}*/
		
		this._pageTracker = pageTracker;
	},
	
	decorateLink : function(u) {
		var trackingURL = '';
		
		if(u.indexOf('://') == -1 && u.indexOf('mailto:') != 0){
			// no protocol or mailto - internal link - check extension
			var ext = u.split('.')[u.split('.').length - 1];			
			var exts = opts.extensions;
			
			for(i = 0; i < exts.length; i++){
				if(ext == exts[i]){
					trackingURL = opts.download + u;
					break;
				}
			}				
		} else {
			if(u.indexOf('mailto:') == 0){
				// mailto link - decorate
				trackingURL = opts.mailto + u.substring(7);					
			} else {
				// complete URL - check domain
				var regex = /([^:\/]+)*(?::\/\/)*([^:\/]+)(:[0-9]+)*\/?/i;
				var linkparts = regex.exec(u);
				var urlparts = regex.exec(location.href);					
				if(linkparts[2] != urlparts[2]) trackingURL = opts.external + u;
			}
		}
		
		return trackingURL;	
	}
}
