//Check to see if we have a url already
var ts_masterURL;
try
{
	//Yes? This would have been set in ../main.aspx
	ts_masterURL
} catch (error)
{
	//alert("ts_masterURL not defined");
	ts_masterURL = "http://es.sidekick.com/enes/24/_www_t-mobilenavigation_com/";

};

var ts_scripts = ["/scripts/tracking_gsm/tracking_core.js", "/scripts/webtrends/sdc_advanced.js", "/scripts/tracking_gsm/tracking_init.js"]; //"/scripts/ga.js",/"/scripts/tracking_maps/map_unav.js"

//List out all the possible webtrends accounts
var ts_WTID = {
	"default": "dcs0000000000000000000000_0000",
	"sidekick.com": "dcsfkfzco10000w0yrfjs7cf1_4q4w",
	"sticktogether.com": "dcstouck000000spit8xdc0g1_3u3z",
	"es.sidekick.com": "dcsr2mt4u10000wg2qljtdjy1_9u1v",
	"t-mobilenba.com": "dcs6vykis000004r779h1tzc9_7x7v",
	"t-mobileinvitational.com": "dcspf1vq610000wk5zhuxs0d9_2j4k",
	"t-mobilenbainsider.com": "dcsr7rnio10000slf8zb761d9_1x8u",
	"t-mobileathome.com": "dcsw5ji6u00000c58nbroj2bl_8c4o",
	"t-mobileg1.com": "dcsp2ms2a0000008eomj6ln1t_9c6u",
	"t-mobileprizepass.com": "dcs83p9bu00000oe3f9q7e98t_1z6k",
	"flywitht-mobile.com": "dcst3cn7k100004b31xewe34y_6y8r",
	"vuelacont-mobile.com": "dcst3cn7k100004b31xewe34y_6y8r",
	"t-mobilefutbol.com": "dcsqy69k010000kz8ejuvnt6a_2o1q",
	"mobilizewitht-mobile.com": "dcs7b7u3n1000004fybx31nfd_1w4g",
	"momtomomquiz.com": "dcsuttmj3100000slzrnzjc5f_4k8g",
	"apps.t-mobile.com": "dcsd54vyw00000o2u78t5a33h_4s2w",
	"t-mobilemytouch.com": "dcsqflel200000gwvuf5uud2m_9m9j",
	"simplyt-mobile.com": "dcsqi6qc00000000s5jc4ko1k_5g8t",
	"studio.t-mobile.com": "dcsw2ehbe10000kfdoqfrkhso_2w8l",
	"t-mobilescoop.com": "dcsv2ai6z00000kzcpu1nsdrs_8s8p",
	"cliq.t-mobile.com": "dcs1jaqbn100000wo0a6qjhmx_6f3s",
	"t-mobile9700.com": "dcs1jaqbn100000wo0a6qjhmx_6f3s",
	"t-mobileholidaycardmaker.com": "dcs1jaqbn100000wo0a6qjhmx_6f3s",
	"t-mobilewishlist.com": "dcs1jaqbn100000wo0a6qjhmx_6f3s",
	"htchd2.t-mobile.com" : "dcsam64ls100004j1huoqw8nc_3g7y",
	"mytouch.t-mobile.com": "dcsqflel200000gwvuf5uud2m_9m9j",
	"garminfone.t-mobile.com": "dcsmirld000000s96hqvdfemg_4j9l",
	"galaxy-s.t-mobile.com": "dcslwrzpc000008ahuhrdm6lm_2r4z",
	"t-mobile-coverage.t-mobile.com": "dcs8y7kta00000w027iejenfv_7m3e",
	"android.t-mobile.com": "dcs8y7kta00000w027iejenfv_7m3e"
};

var ts_GOID = {
	"default": "UA-3641653-1",
	"sidekick.com": "UA-3066297-1",
	"sticktogether.com": "UA-3743308-1",
	"es.sidekick.com": "",
	"t-mobilenba.com": "UA-3743322-1",
	"t-mobileinvitational.com": "UA-3743355-1",
	"t-mobilenbainsider.com": "UA-3743510-1",
	"t-mobileathome.com": "UA-4974001-1",
	"t-mobileg1.com": "UA-5716893-1",
	"t-mobileprizepass.com": "",
	"flywitht-mobile.com": "UA-6140872-1",
	"vuelacont-mobile.com": "UA-6140872-1",
	"t-mobilefutbol.com": "",
	"mobilizewitht-mobile.com": "",
	"momtomomquiz.com": "",
	"apps.t-mobile.com": "",
	"t-mobilemytouch.com": "",
	"mytouch.t-mobile.com":"",
	"galaxy-s.t-mobile.com": ""
};

var ts_PREFIXES = {
	"default": "test_",
	"sidekick.com": "sk_",
	"sticktogether.com": "st_",
	"es.sidekick.com": "essk_",
	"t-mobilenba.com": "nba_",
	"t-mobileinvitational.com": "invitational_",
	"t-mobilenbainsider.com": "insider_",
	"t-mobileathome.com": "TatHome_",
	"t-mobileg1.com": "G1_",
	"t-mobileprizepass.com": "2k9_",
	"flywitht-mobile.com": "FCF_",
	"t-mobilefutbol.com": "soccer_",
	"mobilizewitht-mobile.com": "mobilize_",
	"momtomomquiz.com": "FA_",
	"apps.t-mobile.com": "apps_",
	"t-mobilemytouch.com": "myT_",
	"simplyt-mobile.com": "simply_",
	"studio.t-mobile.com": "studio_",
	"t-mobilescoop.com": "scoop_",
	"cliq.t-mobile.com": "cliq_",
	"t-mobile9700.com": "9700_",
	"t-mobileholidaycardmaker.com": "cardmaker_",
	"t-mobilewishlist.com": "wishlist_",
	"htchd2.t-mobile.com": "hd2_",
	"mytouch.t-mobile.com":"myT_",
	"galaxy-s.t-mobile.com": "s_",
	"garminfone.t-mobile.com": "garmin_",
	"t-mobile-coverage.t-mobile.com": "cov_",
	"t-mobile-coverage.t-mobile.com": "hspa_",
	"t-mobile-coverage.t-mobile.com": "map_"
	
};

var ts_url = "";
var ts_pageName = "";
var ts_pagePath = "";
var ts_prefix = "";

var ts_debugWindow = null;

var gDcsId; //Webtrend account ID 
var googleGlobalID;


function ts_init()
{

	//Step 1. Add a debugging window
	ts_addDebug();

	//Step 2. Figure out our locations and configure accordingly
	var coreURL = window.location.toString().toLowerCase().split("http://").join("").split("www.").join("").split("staging.").join("").split("dev.").join("");
	//Special hack to fix problems caused by '#" being in the URL.
	if (coreURL.indexOf("#") > -1)
	{
		var temp1 = coreURL.split("#");
		coreURL = temp1[0];
	}
	//Remove double slashes
	coreURL = coreURL.split("//").join("/");
	var temp = coreURL.split("/"); //We need to know our location and our pagen name
	ts_url = temp[0].toLowerCase(); //What site are we looking at
	ts_pageName = "" + temp[temp.length - 1].split(".").splice(0, 1);
	ts_pagePath = "" + temp.slice(1, temp.length - 1) //What page are we looking at
	if (ts_pageName == "" || ts_pageName.substring(0, 1) == "?")
	{
		ts_pageName = "default";
	}
	temp = null; //Flush the temp var
	//trace(ts_url + " , " + ts_pageName + " " + ts_pagePath);

	//Step 3. Set the correct WebTrends ID
	ts_addWebTrendsID();
	//Step 4. Add Google Function 
	ts_addGoogle();
	//Step 5. Add all the required main tracking code
	ts_addMainFunctions();
	//Step 6. Add all the tracking maps
	ts_addTrackingMaps();

};

function ts_addWebTrendsID()
{
	//Determine what gDcsId we should be using
	for (var props in ts_WTID)
	{
		if (ts_url.indexOf(props) > -1)
		{
			gDcsId = ts_WTID[props];
			googleGlobalID = ts_GOID[props];
			ts_prefix = ts_PREFIXES[props];

			return;
			break;
		}
	}
	gDcsId = ts_WTID["default"];
	googleGlobalID = ts_GOID["default"];
	ts_prefix = ts_PREFIXES["default"];

};

var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
function ts_addGoogle()
{
	/**
	** Google tracking. Used to as an independent verification tool.
	**/
	//document.write(unescape("%3Cscript src='" + gaJsHost +	"google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
};

function ts_addMainFunctions()
{
	//Write out all the functions required to make this system work
	document.write("<SCR" + "IPT TYPE='text/javascript' src='" + ts_masterURL + "utils/combinefiles.ashx?files=" + ts_scripts.join(",") + "'></SCR" + "IPT>");
	//}
};

function ts_addTrackingMaps(usePageMaps)
{
	var mapArray = new Array();
	mapArray.push("/scripts/tracking_maps/map_common.js");
	var currentPage = "/scripts/tracking_maps/" + ts_pagePath + "/map_" + ts_pageName + ".js";
	currentPage = currentPage.split("//").join("/");
	mapArray.push(currentPage);
	//Every site should have at least a "map_commons.js"
	//document.write("<SCR"+"IPT TYPE='text/javascript' src='/scripts/tracking_maps/map_common.js'></SCR"+"IPT>");
	//And hopefully, every page should have its own "map_pageName.js"
	//document.write("<SCR"+"IPT TYPE='text/javascript' src='/scripts/tracking_maps/" + ts_pagePath + "/map_" + ts_pageName + ".js'></SCR"+"IPT>");

	try
	{
		//Find out if there are tracking maps we should add
		//These might be added as special maps a user wants for a specific page.
		//trackingMaps = ['map_myFlashElement.js'];
		if (typeof trackingMaps != "undefined")
		{
			for (var i = 0; i < trackingMaps.length; i++)
			{
				if (trackingMaps[i].indexOf("http") > -1)
				{
					mapArray.push(trackingMaps[i]);
					//document.write("<SCR"+"IPT TYPE='text/javascript' src='" + trackingMaps[i] + "'></SCR"+"IPT>");
				} else
				{
					mapArray.push(trackingMaps[i]);
					//document.write("<SCR"+"IPT TYPE='text/javascript' src='/scripts/tracking_maps/" + trackingMaps[i] + "'></SCR"+"IPT>");
				}
			}
		}

	} catch (error)
	{
		//Do nothing
	}
	document.write("<SCR" + "IPT TYPE='text/javascript' src='http://es.mytouch.t-mobile.com/enes/sdcache/sdtracking/utils/combinefiles.ashx?files=" + mapArray.join(",") + "'></SCR" + "IPT>");
};

var trackingDebug;
function ts_addDebug(passThru, passThruID)
{
	//alert("ts_addDebug : " + passThru + " :: " + passThruID);
	//Opens the debug window when required
	if (!passThru)
	{
		passThru = "";
	}
	if (!passThruID)
	{
		passThruID = "";
	}
	trackingDebug = getQueryVariable("debug");

	if (trackingDebug == "true")
	{
		ts_setCookie("debug", "true");
	} else
	{
		trackingDebug = ts_getCookie("debug");
	}
	//window.console.log("%s: %o", "typeof ts_debugWindow =>" + typeof ts_debugWindow, this);
	//trace("typeof ts_debugWindow =>" + typeof ts_debugWindow);
	if (trackingDebug == "true" && (ts_debugWindow == undefined || (ts_debugWindow != null && ts_debugWindow.closed == true)))
	{
		ts_debugWindow = window.open("", "debugger", "menubar=false,width=800,height=620,scrollbars=yes,resizable=yes");
		if (typeof ts_debugWindow != "undefined" && ts_debugWindow != null && ts_debugWindow.location.href.indexOf("debug") == -1)
		{
			ts_debugWindow.location.href = "http://es.mytouch.t-mobile.com/enes/sdcache/sdtracking/utils/debug.aspx?trace=" + passThru + "&lastID=" + passThruID;
		}
		if (typeof ts_debugWindow != "undefined" && ts_debugWindow != null) {
			ts_debugWindow.focus();
		}
	}
};

function getQueryVariable(variable)
{
	var query = window.location.search.substring(1);
	var vars = query.split("&");
	for (var i = 0; i < vars.length; i++)
	{
		var pair = vars[i].split("=");
		if (pair[0] == variable)
		{
			return pair[1];
		}
	}
	return "";
};

function ts_setCookie(name, value, expires, path, domain, secure)
{
	var curCookie = name + "=" + escape(value) +
     	 ((expires) ? "; expires=" + expires.toGMTString() : "") +
     	 ((path) ? "; path=" + path : "") +
     	 ((domain) ? "; domain=" + domain : "") +
     	 ((secure) ? "; secure" : "");
	document.cookie = curCookie;
};

function ts_getCookie(name)
{
	var dc = document.cookie;
	var prefix = name + "=";
	var begin = dc.indexOf("; " + prefix);
	if (begin == -1)
	{
		begin = dc.indexOf(prefix);
		if (begin != 0)
		{
			return null;
		}
	} else
	{
		begin += 2;
		var end = document.cookie.indexOf(";", begin);
	}
	if (end == -1)
	{
		end = dc.length;
	}
	return unescape(dc.substring(begin + prefix.length, end));
};

function trace(what)
{
	if (trackingDebug == "true")
	{
		try
		{
			ts_addDebug(escape(what), escape(ts_lastID));
		} catch (error)
		{
			ts_addDebug(escape(what), "");
		}

		try
		{
			ts_debugWindow.trace(what, ts_lastID);
			ts_debugWindow.focus();
		} catch (error)
		{
			try
			{
				ts_debugWindow.trace(what, "");
				ts_debugWindow.focus();
			} catch (error)
			{
				//Do not trace
				//alert("could not trace");
				ts_setCookie("debug", "false");
			}
		}
	}
	if (typeof window.console != "undefined" || trackingDebug == "true")
	{
		window.console.log("%s: %o", what, this);
	}
};

//We'll store any onclick function, that may already be on a tag, in this object
var gsm_proxyFunctions = new Object();

function gsm_rewriteAnchors()
{
	var anchors = document.getElementsByTagName("a");
	//trace("anchors.length = " + anchors.length);

	for (var i = 0; i < anchors.length; i++)
	{
		var a = anchors[i];
		var newId = "";

		if (a.id == "" || a.id.indexOf("_dt") != -1 || a.id.indexOf("dt_") != -1)
		{
			//don't track this
			continue;
		}
		if (a.href.indexOf("#") > -1)
		{
			//alert(a.href + "\n" + window.location);
		}
		var testURL = a.href;
		var rootURL = testURL.replace(window.location, "");
		if (rootURL != "" && rootURL != "#" && (a.target == "" || a.target == "_self" || a.target == "_top"))
		{
			//alert(rootURL);
			if (a.onclick)
			{
				if (a.onclick.toString().indexOf("trackEvent") == -1)
				{
					//Put any functions away for use after the tracking event
					gsm_proxyFunctions[a.id] = a.onclick;
					a.onclick = function() { return trackEventAndGoto(this); };
					//trace("adding trackEventAndGoto, saving functions :" + a.id);
				} else
				{
					//This must have legacy tracking code on it, so leave it be
				}
			} else
			{
				a.onclick = function() { return trackEventAndGoto(this); };
				//trace("adding trackEventAndGoto :" + a.id);
			}

		} else
		{
			if (a.onclick)
			{
				if (a.onclick.toString().indexOf("trackEvent") == -1 || a.onclick.toString().indexOf("return") == -1)
				{
					//Save the function already in the onclick event in this object for later use
					//for example: <a href="#" onclick="doSomething()" id="someId" >Hi!</a>
					//Will end up being
					//gsm_proxyFunctions["someID"] = function () { doSomething(); };
					//And the tag will become
					//<a href="#" onclick="trackEvent(this)" id="someId" >Hi!</a>
					//The tracking system, in either trackEvent or trackEventAndGoto, will then
					//Call gsm_proxyFunctions["someID"](); after the track has taken place.
					gsm_proxyFunctions[a.id] = a.onclick;
					a.onclick = function() { trackEvent(this); };
					//Tried this with listeners and it didn't really work.
					/*if (a.addEventListener) {
						a.addEventListener('click', trackEventHandler, false);
					} else if (a.attachEvent) {
						a.attachEvent('onclick', trackEventHandler);
					}
					*/
				} else
				{
					//This must have legacy tracking code on it, so leave it be
				}
			} else {

				//The most simple option. No other items to deal with. Just add tracking.
				a.onclick = function() { trackEvent(this); };
				/*
				if (a.addEventListener) {
					a.addEventListener('click', trackEventHandler, false);
				} else if (a.attachEvent) {
					a.attachEvent('onclick', trackEventHandler);
				}
				*/
			}
		}
		//trace("a.onclick = " + a.onclick);
		if (window.addEventListener)
		{
			window.removeEventListener('load', gsm_rewriteAnchors, true);
		} else if (window.attachEvent)
		{
			window.detachEvent('onload', gsm_rewriteAnchors);
		}
	};
	gsm_rewriteForms();
}
function gsm_rewriteForms()
{
	var forms = document.getElementsByTagName("form");
	for (var i = 0; i < forms.length; i++)
	{
		var f = forms[i];
		f.onsubmit = function() { return trackEventAndSubmit(this); };
	}
};

ts_init();
if (window.addEventListener)
{
	window.addEventListener('load', gsm_rewriteAnchors, false);
} else if (window.attachEvent)
{
	window.attachEvent('onload', gsm_rewriteAnchors);
};

/*Unav Language Toggle Fix */
/*
if (typeof ($) != "undefined")
{
	
	$(document).ajaxComplete(function() { $.fn.updateSpanishToggle() });
	$.fn.updateSpanishToggle = function()
	{
		$("#language").html("");
		$(".search").css("margin-right", "8px").css("float", "right");
	}
}
*/