// NOTE : Pages should contain ONLY this file OR tracking.js, not both

// version 1.1 2010-08-05 - Added social media tracking, direct and referral


	//Detect if SEM or SEO
	var GetVars = new Array();
	var urlVars = new Array();
	var urlParams = new Array();
	var docLoc = document.location;
	var loc = location.href;
	var urlGet = loc.split('?');
	var docRef = document.referrer;
	var isSE = false;
	var domain = docRef.split('/');
	var trackingType = getURLVariable('trackingType');
	var socialMediaSites = Array('facebook','myspace','twitter','youtube','flickr');
	var referrerTypes = {none:0,internal:1,external:2};
	
	if(!trackingType) {
		var trackingType = 'other'; // default tracking type if none is found in the URL
	}
	
													
	function isSEO() {
		if (trackingType == 'SEO') {
			return true;
		}
		else if(docRef != ''){
			return ((docRef.toLowerCase().indexOf('.google.')>0 && (docRef.toLowerCase().indexOf('&q=')>0 || docRef.toLowerCase().indexOf('?q=')>0 || docRef.toLowerCase().indexOf('query=')>0 )) || (docRef.toLowerCase().indexOf('.yahoo.')>0 && docRef.toLowerCase().indexOf('search?p=')>0) || (docRef.toLowerCase().indexOf('.ask.')>0 && docRef.toLowerCase().indexOf('?q=')>0) || (docRef.toLowerCase().indexOf('.bing.')>0 && docRef.toLowerCase().indexOf('?q=')>0) );
		}
		else {
			return false;
		}
	}
	
	function isSEM() {
		return (isSEO() && docLoc.search.toLowerCase().indexOf('wt.srch')>0) || trackingType == 'SEM';
	}
	
	function isSocial()
	{
		var sm = socialMediaSites;
		var rd = "";
		if(domain.length>=3)
			rd = domain[2];
		else
			return false;
			
		for(var i=0; i<sm.length;i++)
		{
			if(rd.toLowerCase().indexOf(sm[i].toLowerCase())>=0)
				return true;
		}
		return false;
	}
	
	function getReferralType()
	{
		var dr = docRef.toLowerCase();
		if(dr==undefined || dr=="")
			return referrerTypes.none;
		else if(dr.indexOf('toyota.')>0 || dr.indexOf('tmca.')>0)
			return referrerTypes.internal;
		else if(dr.indexOf('http')>=0)
			return referrerTypes.external;
		else
			return referrerTypes.none;
	}
	

	if(urlGet.length==1 || (urlGet[1] !="" && urlGet[1].toLowerCase().indexOf("wt.mc_id")<0))
	{
		if( isSEO() && !isSEM() )
			writeMCID("SEO");
		else if(isSocial())
			writeMCID("Social Media");
		else if(!isSEM() && getReferralType()==referrerTypes.external)
			writeMCID("Referring Site");
		else if(!isSEM() && !isSessionActive() && getReferralType()==referrerTypes.none)
			writeMCID("Direct Visit");
	}
	document.cookie = "_wtsa=1"; // set a session cookie to flag that the session is active
		
function getURLVariable(name) {
	name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
	var regexS = "[\\?&]"+name+"=([^&#]*)";
	var regex = new RegExp( regexS );
	var results = regex.exec( window.location.href );
	if( results == null )
		return "";
	else
		return results[1];
}
	
function writeMCID(val)
{
	if(val != "")
		document.write('<meta name="WT.mc_id" content="' + val + '" />');
}
	
function isSessionActive(){
	var _ucookies = document.cookie.split(";");
	for(i = 0; i < _ucookies.length; i++){
		var np = _ucookies[i].split("=");
		var nc = np[0].replace(/^\s+|\s+$/g, '');
		if(nc.toLowerCase() == '_wtsa')
		{
			return true;
		}
	}
	return false;
};


//******  Additional standard tracking info ******

//these are the custom variables that are settable.
//They are cleared before any track event.
var wt_settable_variables = [
	'WT.ac', 
	'WT.cg_n', 
	'WT.cg_s',
	'WT.BATD_start',
	'WT.BATD_submit',
	'WT.DE_start',
	'WT.DE_submit',	
	'WT.model',
	'WT.flv_name',
	'WT.flv_status',  
	'WT.flv_percentplay',
	'WT.flv_viewduration',
	'DCSext.VehicleConversionID',
	'dcsuri'
];

// ********************************************** 
// New object to handle virtual page views and events in WT.
// 
// SYNTAX
// hh_WT.trackEvent(object* items to update, bool* clear all old variables before resetting.);
// USAGE
// var updateobj = {
//	'WT.cg_n':'Test Section',
//	'WT.cg_s':'Test Subsection'
//}
// hh_WT.trackEvent(updateobj, true);
// eg. hh_WT.trackEvent({WT.ac':'testclick', 'WT.cg_s':'TestPage'}, false);
// This would keep existing custom settable vars, set WT.ac to testclick, 
// set WT.cg_s to TestPage, then fire a track event.
//
// ADDITIONAL HELPER FUNCTIONS
// hh_WT.debugParams() - Alerts all the vars in the Webtrends obj
// hh_WT.clearVariables(array) - sets the passed variables to blank
// hh_WT.clearAllVariables() - sets all custom Webtrends parameters to blank
// hh_WR.updateVariables(obj) - sets the Webtrends variables to the passed object variables values
// 
// EXAMPLES
//webtrendsTag('Testing: Please Ignore', 'Testing: true'); //must be called on the page.
//
//hh_WT.debugParams(); // see initial parameters
//hh_WT.clearVariables(['WT.cg_n','WT.cg_s']); //clear the specified variables
//hh_WT.debugParams(); //above vars blank
//hh_WT.updateVariables({'WT.cg_n':'TestingClick1'}); //set the specified variables
//hh_WT.debugParams(); //cg_n set
//hh_WT.trackEvent({'WT.ac':'TestClick2'}, false); //fire a track with the previously specified variables
//hh_WT.debugParams(); //all still set
//hh_WT.trackEvent({'WT.ac':'TestClick3'}, true); //clear all previous variables, set WT.ac to TestClick3, then fire a tracking event.
//hh_WT.debugParams(); //all blank except WT.ac
// **********************************************
var hh_WT = function() {
	
	function _debugStr(tag) {
		var result = '';
			if (tag) {
				result += 'Debugging for ' + tag.dcsid + '\r\n';
				if (tag.WT) {
					result += 'WT Vars : \r\n';
					for (var x in tag.WT) {
						result += x + ' : ' + tag.WT[x] + '\r\n';
					}
				}
				
				if (tag.DC) {
					result += '\r\nDC Vars : \r\n';
					for (var x in tag.DC) {
						result += x + ' : ' + tag.DC[x] + '\r\n';
					}
				}
				
				if (tag.DCSext) {
					result += '\r\nDCSext Vars : \r\n';
					for (var x in tag.DCSext) {
						result += x + ' : ' + tag.DCSext[x] + '\r\n';
					}
				}
			}
		
		return result;
	};
	
	//adds a variable to the variables to be cleared on a tracking event
	function _addTrackingVariable(varname) {
		wt_settable_variables.push(varname);
	}
	
	//this function clears any variables passed from the wt tag
	function _clearVariables(arr) {
		
		if (arr) {
			for (var i=0;i<arr.length;i++) {
				eval('if (_tag1.' + arr[i] + '){_tag1.' + arr[i] + '="";}');
				eval('if (_tag2.' + arr[i] + '){_tag2.' + arr[i] + '="";}');
			}
		}
	};
	
	function _clearAllVariables() {
		_clearVariables(wt_settable_variables);
	};
	
	function _updateVariables(obj) {			
		if (obj) {
			for (var x in obj) {	
				var str = x + '="' + obj[x] + '";';
				//alert(str);
				eval('_tag1.' + str);
				eval('_tag2.' + str);
			}
		}
	};
	
	function _trackEvent(obj, clearvars) {
		if (typeof(clearvars) == 'undefined'){
			clearvars = true;
		}
		
		if (clearvars) {
			_clearAllVariables();
		}
		_updateVariables(obj);
		//_debugParams();
		dcsMultiTrack();
	};
	
	function _debugParams() {
		alert(_debugStr(_tag1));
		alert(_debugStr(_tag2));
	};

	
	return {
		addTrackingVariable:_addTrackingVariable,
		updateVariables:_updateVariables,
		clearVariables:_clearVariables,
		clearAllVariables:_clearAllVariables,
		trackEvent:_trackEvent,
		debugParams:_debugParams
	}

}();

