var wt_is_initialised = false;
var wt_od_domain = CONFIG.WT.wt_domain_1;
var wt_od_dcs_id = CONFIG.WT.wt_dcsid_1;
var wt_domain = CONFIG.WT.wt_domain_2;
var wt_dcs_id =  CONFIG.WT.wt_dcsid_2;
var _tag1 = null;
var _tag2 = null;

//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'
];

var domain = 'toyota.com.au';
if(window.location.hostname != '')
{
	domain = window.location.hostname;
}


// doubleclick tags
function spotlightTag(spotlightSRC, spotlightType, spotlightCat)
{
	doubleclickTag(spotlightSRC, spotlightType, spotlightCat);
}
function doubleclickTag(spotlightSRC, spotlightType, spotlightCat)
{
	var a = Math.random() * 10000000000000;	
	
	var URL = 'http://ad.au.doubleclick.net/activity;src=' + spotlightSRC + ';type=' + spotlightType + ';cat=' + spotlightCat + ';ord=1;num='+ a + '?';	
	var sl = document.createElement('img');
	
	sl.setAttribute('id' , 'sl');
	sl.setAttribute('src', URL);
	sl.style.border = '0px';
	sl.style.height = '0px';
	sl.style.width = '0px';
	sl.style.display = 'none';
	
	document.body.appendChild(sl);
}

// eyeblaster tags
function eyeBlasterTag(eyeBlasterActivityID, eyeBlasterAdvertiser)
{
	var ebRand = Math.random()+ ' ';
	var js = document.createElement('script');
	ebRand = ebRand * 1000000;

	var URL = 'http://bs.serving-sys.com/BurstingPipe/pipe.asp?ActivityID='+ eyeBlasterActivityID +'&AdvertiserID='+ eyeBlasterAdvertiser +'&Frequency=0&rnd=' + ebRand;

	js.setAttribute('type', 'text/javascript');
	js.setAttribute('src', URL);

	try
	{
		document.body.appendChild(js);
	} catch(err) {}
}

// webtrends tags
function wtInit() {
	if(wt_is_initialised) {
		return;
	}
	
	
	_tag1 = new WebTrends(wt_od_dcs_id, wt_od_domain);
	_tag1.dcsGetId();
	//_tag2 = new WebTrends(wt_dcs_id, wt_domain);
	//_tag2.dcsGetId();

	wt_is_initialised = true;
}

function webtrendsTag(group, subgroup)
{
	wtInit();

	group = group.split(';');
	subgroup = subgroup.split(';');
	
	var length = group.length;
		
	for(var i = 0; i < length; i++) {
		_tag1.WT.cg_n = group[i];
		_tag1.WT.cg_s = subgroup[i];
		_tag1.dcsCollect();
		
		//_tag2.WT.cg_n = group[i];
		//_tag2.WT.cg_s = subgroup[i];
		//_tag2.dcsCollect();
	}
}

function webtrendsTag2(group, subgroup)
{
	
	wtInit();

	_tag1.WT.cg_n = group;
	_tag1.WT.cg_s = subgroup;
	_tag1.dcsCollect();
	
	//_tag2.WT.cg_n = group;
	//_tag2.WT.cg_s = subgroup;
	//_tag2.dcsCollect();
}

/* WebTrends Time Tracking */
var wtTimers = Array();

function wtCreateTimer(name) {
  wtInit();
  if(wtTimers == undefined) return;
  wtTimers[name] = Array();
  wtTimers[name].params = Array();
  wtTimers[name].running = false;
  wtTimers[name].label = null;
}

function wtStartTimer(name) {
  if(wtTimers == undefined || wtTimers[name] == undefined) return;
  wtTimers[name].start = new Date() / 1000;
  wtTimers[name].running = true;
}

function wtStopTimer(name) {
  if(wtTimers == undefined || wtTimers[name] == undefined || !wtTimers[name].running)
    return;
  wtTimers[name].stop = new Date() / 1000;
  wtTimers[name].running = false;
  var params = Array();
  
  var i = 0;
  if(wtTimers[name].label != null) {
    params[0] = wtTimers[name].label;
    params[1] = Math.floor(wtTimers[name].stop - wtTimers[name].start);
    i = 1;
  }
  for(key in wtTimers[name].params) {
    params[i*2] = key;
    params[i*2 + 1] = wtTimers[name].params[key];
    i++;
  }  
  dcsMultiTrack.apply(this,params);
}

function wtKillTimer(name) {
  if(wtTimers == undefined || wtTimers[name] == undefined) return;
  wtTimers[name].running = false;
  wtTimers[name].stop = 0;
}

function wtSetTimerParam(name,key,val) {
  if(wtTimers == undefined || wtTimers[name] == undefined) return;
  wtTimers[name].params[key] = val;
}

function wtSetTimerLabel(name, label) {
  if(wtTimers == undefined || wtTimers[name] == undefined) return;
  wtTimers[name].label = label;
}

function wtUnloadHandler() {
  var curDuration = 0;
  for(name in wtTimers) {
    curDuration = Math.floor(new Date().getTime()/1000 - wtTimers[name].start);
    if(wtTimers[name].running && curDuration < 300) {
      wtStopTimer(name);
    }
  }
}

/* ---------------------
 * SEO/SEM Tracking Code
 * --------------------- */
// 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
	}
	
	// debugging
	var testref = getURLVariable('testref');
	if(testref != "")
	{
		docRef = unescape(testref);
		domain = docRef.split('/');
	}
	// end debugging

	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;
};
	
	// ********************************************** 
	// 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
		}
	
	}();
	
	
	
	// Track the vehicle section

function trackVehicleView()
{
	var _wtvtpath = document.location.pathname.split("/");
	if(_wtvtpath.length<2)
		return;
	var _wtvehicle = "";
	switch(_wtvtpath[1])
	{
		case "aurion":
			_wtvehicle=_wtvtpath[1];
			break;
		case "avensis":
			_wtvehicle=_wtvtpath[1];
			break;
		case "camry":
			_wtvehicle=_wtvtpath[1];
			break;
		case "coaster":
			_wtvehicle=_wtvtpath[1];
			break;
		case "corolla":
			_wtvehicle=_wtvtpath[1];
			break;
		case "camry-hybrid-camry":
			_wtvehicle="hybridCamry";
			break;
		case "fj-cruiser":
			_wtvehicle="fjCruiser";
			break;
		case "hiace":
			_wtvehicle="hiace";
			break;
		case "hilux":
			_wtvehicle="hilux";
			break;
		case "kluger":
			_wtvehicle=_wtvtpath[1];
			break;
		case "landcruiser-200":
			_wtvehicle="landcruiser200";
			break;
		case "landcruiser-70-series":
			_wtvehicle="landCruiser70Series";
			break;
		case "prado":
			_wtvehicle="prado";
			break;
		case "prius":
			_wtvehicle=_wtvtpath[1];
			break;
		case "rav4":
			_wtvehicle=_wtvtpath[1];
			break;
		case "rukus":
			_wtvehicle=_wtvtpath[1];
			break;
		case "tarago":
			_wtvehicle=_wtvtpath[1];
			break;
		case "yaris":
			_wtvehicle=_wtvtpath[1];
			break;
	}
	
	if(_wtvehicle=="")
		return;
	
	var _cval = _getCookie("toyvstate");
	var _varr = new Array();
	var _isOK = 1;
	if(_cval != "")
	{
		_varr = _cval.split("|");
	}
	
	for(var i=0; i< _varr.length; i++)
	{
		if(_varr[i] == _wtvehicle)
		{
			_isOK =0;
			break;
		}
	}

	
	if(typeof(window.DCSext) == "undefined")
		window["DCSext"] = new Object();
	if(_isOK == 1)
	{
		_varr.push(_wtvehicle);
		document.write("<meta name='DCSext.VehicleSectionVisit' content='1' />");
	}
	document.write("<meta name='DCSext.VehicleConversionID' content='" + _wtvehicle + "' />");
	if(typeof(window["vehicle"]) =="undefined")
		window["vehicle"] = _wtvehicle;
	
	_cval = _varr.join("|")
	_setCookie("toyvstate",_cval);
}

function _setCookie(cookieName,cookieValue,expire,strDomain) {
	var pdm = "";
	if (strDomain && strDomain!="") 
		pdm=" domain="+strDomain+";"; 

	if((typeof(expire)) == "object")
		document.cookie = cookieName+"="+escape(cookieValue) + ";expires="+expire.toGMTString() + "; path=/;" + pdm;
	else
		document.cookie = cookieName+"="+escape(cookieValue) + "; path=/;" + pdm;
}

function checkSpecialOffer()
{
	var dq = document.location.search;
	var dl = document.location.pathname;
	
	$("head").append("<meta id='spoff' name='DCSext.SpecOfferState'>");
	if(dq.indexOf("SpecOffer=1")>0 || dl.indexOf('thankyou')>0)
		$("#spoff").attr("content",'Special Offer');
	else
		$("#spoff").attr("content",'Non Special Offer');
}

function _getCookie(strParam){
	var _ucookies = document.cookie.split(";");
	for(i = 0; i < _ucookies.length; i++){
		var np = _ucookies[i].split("=");
		if(_trim(np[0].toLowerCase()) == strParam.toLowerCase())
		{
			var val ="";
			for(i=1;i<np.length;i++)
			{
				if(i>1)
					val += "=";
				
				val += np[i];
			}
			return unescape(_trim(val));
		}
	}
	return "";
}


function _trim (val){ return val.replace(/^\s+|\s+$/g, '') ; }

/*THIS FUNCTION IS FOR BPYT TO TRACK CLICKS*/
function updateWTTag(page,section,group) 
{
	
	var pageTitle = "Toyota Australia - Build and Price Your Toyota";
	
	if (group=="null" || !group || group=="undefined" || group==undefined){
		document.title = pageTitle +" - " + section + " - " + page;
	} else {
		document.title = pageTitle +" - " +  group + " - " + section + " - " + page;
	}
		
	var dcsuri = '';
	
	if (group=="null" || !group || group=="undefined" || group==undefined){
		dcsuri = "Build and Price: " + section +"-"+ page +".html";
	} else {
		dcsuri = "Build and Price: " + group +"-"+ section +"-"+ page +".html";
	}
	
	hh_WT.trackEvent({'WT.cg_n': 'Build and Price: ' + group, 'WT.cg_s': section + ' - ' + page, 'DCS.dcsuri': dcsuri}, true); 
	
}

trackVehicleView();
checkSpecialOffer();


