/**
 DO NOT REMOVE this and jquery
 Tracker current being used by analyticsresults.com

 TESTING ONLY
 Current Version: 002
 Version 001: 
	- Adds a click event to all anchor links
	- In tracking form submits 
		- uses jquery event 'submit'; Problem is that this event is not fired
		  when the form is submitted by javascript eg this.form.submit()
	- allows individual elements to be tracked eg div, li, focus() etc
 Version 002:
	- Form submits
		- form submit event is overridden by newsubmit() method.
			After this new method is called, the original submit method is run.
			This is achieved by adding 
				window.addEventListener('submit', newsubmit, true);
				HTMLFormElement.prototype._submit = HTMLFormElement.prototype.submit;
				HTMLFormElement.prototype.submit = newsubmit;
*/


// TODO: 
// need to record the query parameters? not tracked currently
// HELP: http://code.google.com/apis/analytics/docs/tracking/asyncMigrationExamples.html

// Notes:
// for downloads, query parameters included in tracking
// Code below assumes the tracking code is implemented in the webpage.
//   This includes stuff like setDomain(), sethash etc

// cross domain links. all profiles will have setDomainXXX
// outbound links containing these domains are not tracked via event/pageview as well
var _msCD = [ ];  
var _msP = [["","UA-2816331-4"],["b","UA-305675-26"],["c","UA-6369320-8"]];  // Profiles array of name/profile pairs
var _msUseAsync = true;  // not tested
var _trackSubmit = false;

// init
$(document).bind("ready._ms", initMsLinkTracking);
function initMsLinkTracking(){
	$("a")._msLinksTracker({
		outbound: {run:true,useEvent:true},
		download: {run:true,useEvent:true},
			self: {run:false, useEvent:true},
			mail: {run:true,useEvent:true}
	});

	if(_trackSubmit){
		// capture the onsubmit event on all forms
		window.addEventListener('submit', newsubmit, true);
		// If a script calls someForm.submit(), the onsubmit event does not fire,
		// so we need to redefine the submit method of the HTMLFormElement class.
		HTMLFormElement.prototype._submit = HTMLFormElement.prototype.submit;
		HTMLFormElement.prototype.submit = newsubmit;
	}	
};

// checks if value is inArray
// matches are done by RegEx
function isInArrayRegEx(val, arr){
	for ( var i = 0; i < arr.length; i++ ) {
		var r=new RegExp(arr[i],'i');
		if ( r.test(val)) {
			return i;
		}
	}
	return -1;
}

function newsubmit(event) {
    var target = event ? event.target : this;

    // do anything you like here
    //alert('Submitting form to ' + target.action);
    
    
	var action = target.action;
			
	action = action.replace(/^https?:\/\//i,'');
	hostname = action.substr(0, action.indexOf('/'));
	if(hostname.length!=0){
		if(isInArrayRegEx(hostname, _msCD)!=-1){
			_msLinkByPost(target);
		}
	}

	
    // call real submit function
    if(this._submit){
    	this._submit();
    };
}


		// =================================================================
		//  Use Async code or async code by changing the below functions
		// =================================================================
		// link by post
		// maybe one call is enough?
		// the action attribute is changed by _linkByPost, and if it is called more than once,
		//  the query parameters are duplicated in the query string.
		function _msLinkByPost (formObj){
			var action= formObj.action;
			for (var i=0;i<_msP.length;i++){
				if(_msUseAsync){
					var tracker = (_msP[i][0].length==0) ? "" : _msP[i][0]+".";
					formObj.action = action;
					_gaq.push([tracker+'_linkByPost', formObj]);
					//alert(tracker+'_linkByPost :: '+formObj.action);
				}else{
					var t = _gat._getTrackerByName(_msP[i][0]);
					t._linkByPost(formObj);
				}
				// pageTracker._linkByPost(this)

			}
		}
				
		// apply linking
		function _msLinkCrossDomain(href){
			for (var i=0;i<_msP.length;i++){
				if(_msUseAsync){
					var tracker = (_msP[i][0].length==0) ? "" : _msP[i][0]+".";
					//alert("_msLinkCrossDomain => "+tracker+'_link'+ ", '"+ href+"'");
					_gaq.push([tracker+'_link', href]);
				}else{
					var t = _gat._getTrackerByName(_msP[i][0]);
					t._link(href);
				}

				//pageTracker._link('http://example.com/test.html');
			}
		};
		
		// track events
		//  categories, action, label, value, count
		function _msTrackEvent(category, action, label,value){
			for (var i=0;i<_msP.length;i++){
				if(_msUseAsync){
					var tracker = (_msP[i][0].length==0) ? "" : _msP[i][0]+".";     
					//alert("_msTrackEvent => " + tracker + "_trackEvent(cat=" + category+  ",act=" + action + ",lab=" + label + ",val=" +value+ ")"  ); 
					(value.length==0) ?    
						_gaq.push([tracker+'_trackEvent', category,action,label]) :    		
						_gaq.push([tracker+'_trackEvent', category,action,label,value]);
				}else{
					var t = _gat._getTrackerByName(_msP[i][0]);
					(value.length==0) ?    
						t._trackEvent(category,action,label) :    		
						t._trackEvent(category,action,label,value);
				}
						
				// pageTracker._trackEvent('category', 'action', 'opt_label', opt_value);
            }
			
		};
		// track pageview
		//  directory, page
		function _msTrackPageView(category, path){
			for (var i=0;i<_msP.length;i++){
				if(_msUseAsync){
					var tracker = (_msP[i][0].length==0) ? "" : _msP[i][0]+".";
					//alert("_msTrackPageView => " + tracker + "_trackPageview("+category+'/'+path+")");
            		_gaq.push([tracker+'_trackPageview',category+'/'+path]);
            	}else{
					var t = _gat._getTrackerByName(_msP[i][0]);
					t._trackPageview(category+'/'+path); 		
						
				}
            	// pageTracker._trackPageView('url');
            }
		}
		// =================================================================


// click handler
(function($)
{

	// Onclick function that sends GA Event/Pageview 
	// for anchor links
	$.fn._msGenericTracker = function(options)
	{ 
		
		var cfg =
		{
			run:true,
			useEvent:true,
			event: 'click',
			eventParam:{
				category:'click',
				action:'',
				label:'click',
				value:'0'},
			pageviewParam:{
				category: '',
				pages: 'click'}
		};
		var cfg = $.extend(true, cfg, options);
		if(cfg.eventParam.action.length==0){
			cfg.eventParam.action = cfg.event;
		}
		if(cfg.pageviewParam.category==0){
			cfg.pageviewParam.category = cfg.event;
		}
		
		return $(this).bind(cfg.event + '._ms', function(){
			if(cfg.run){
				if(cfg.useEvent){
					_msTrackEvent(cfg.eventParam.category,cfg.eventParam.action,cfg.eventParam.label,cfg.eventParam.value) ;
				}else{
					_msTrackPageView(cfg.pageviewParam.category,cfg.pageviewParam.pages);
				}
			}
		});

	};  // end _msGenericTracker

	// Note: Form action using mailto is not supported
	$.fn._msSubmitTracker = function(options)
	{
		
		//return $(this).bind('submit._ms', function(){

		return $(this).submit( function(){
			//alert( $(this).attr('action'));
			var action = $(this).attr('action');
			action = action.replace(/^https?:\/\//i,'');
			hostname = action.substr(0, action.indexOf('/'));
			if(hostname.length!=0){
				if(isInArrayRegEx(hostname, _msCD)!=-1){
					//alert("Submit to outbound x"+$(this).attr('action'));
					//var frmObj = $(this).get();
					
					_msLinkByPost($(this).get());
				}
			}
		});	
	};  // end _msSubmitTracker
		

	$.fn._msLinksTracker = function(options)
	{ 
		var cfg =
		{
			outbound: {run:true,useEvent:true},
			download: {run:true,useEvent:true},
			self: {run:true, useEvent:true},
			mail: {run:true,useEvent:true},
			ext: /\.(doc*|xls*|ppt*|exe|zip|rar|gz|tar|dmg|csv|pdf|xpi|txt)$/i
		};
		var cfg = $.extend(true, cfg, options);
		
		// ====== assign click function ===========
		return $(this).bind('click._ms', function(){
			var href = $(this).attr('href');
			if(href.length ==0) return;  // ignore empty href
			
			var hName = $(this).attr('hostname').toLowerCase();
			var pName = $(this).attr('pathname');
			var protocol = $(this).attr('protocol');
			var phName = location.host;
			
			// remove leading www.
			phName = (phName.replace(/^www\./i,'')).toLowerCase();
			hName = (hName.replace(/^www\./i,'')).toLowerCase();
			
			// used for checking if it is an internal link
			// var regPh=new RegExp(phName,'i');
			// var regH=new RegExp(hName,'i');
				
			// self anchor
			if(href.match(/^#/)){								
				if(cfg.self.run){
					cfg.self.useEvent ? 
						_msTrackEvent('self','click',href,'') : 
						_msTrackPageView('self','/'+href);
				}
			}
			// if mail
			else if(protocol.match(/^mailto:/i)){				
				if(cfg.mail.run){
					href = href.replace(/^mailto:/i,'');
					cfg.mail.useEvent ? _msTrackEvent('mailto','click',href,'') : 
					_msTrackPageView('mailto',href);
				}
			}
			// if download
			else if((new RegExp(cfg.ext)).test(pName)){		
				if(cfg.download.run){
					href = href.replace(/^https?:\/\//i,'');
					cfg.download.useEvent ? 
						_msTrackEvent('download','click',href,'') : 
						_msTrackPageView('download',href);
				}	
			}
			else if(new RegExp(phName,'i').test(hName) || new RegExp(hName,'i').test(phName)){  // is internal link
				// ignore
			}
			// if external link
			else if(hName != phName){							
			
				// if external and not inside list
				if(isInArrayRegEx(hName, _msCD)==-1) { 
					if(cfg.outbound.run){
						cfg.outbound.useEvent ? 
						_msTrackEvent('outbound','click',hName+pName,'') : 
						_msTrackPageView('outbound',hName+pName);
					}
				}
				// if external and inside list
				else if(isInArrayRegEx(hName, _msCD)!=-1) { //jQuery.inArray	
					_msLinkCrossDomain(href);
				}
			}
		});

	};	// end _msLinksTracker
		
		
		
		
})(jQuery)
