//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://tracking.t-mobilenavigation.com/";

};

var ts_scripts = ["/scripts/tracking_gsm/tracking_core.js", "/scripts/webtrends/sdc_advanced.js", "/scripts/tracking_gsm/tracking_init.js"];

//List out all the possible webtrends accounts
var ts_WTID = {
	"default": "dcs0000000000000000000000_0000",
	"mytouch.t-mobile.com": "dcsqflel200000gwvuf5uud2m_9m9j",
	"android.t-mobile.com": "dcs8y7kta00000w027iejenfv_7m3e"
	
};

var ts_GOID = {
	"default": "UA-3641653-1",
	"mytouch.t-mobile.com": "",
	"android.t-mobile.com": ""
};

var ts_PREFIXES = {
	"default": "test_",
	"mytouch.t-mobile.com": "myT_",
	"android.t-mobile.com": "android_"
};

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;
		}
	}
	if (typeof gDcsId == "undefined" || gDcsId == undefined) {
		gDcsId = ts_WTID["default"];
	}
	if (typeof googleGlobalID == "undefined" || googleGlobalID == undefined) {
		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"
	//And hopefully, every page should have its own "map_pageName.js"
	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]);
				} else {
					mapArray.push(trackingMaps[i]);
				}
			}
		}

	} catch (error) {
		//Do nothing
	}
	document.write("<SCR" + "IPT TYPE='text/javascript' src='/utils/combinefiles.ashx?files=" + mapArray.join(",") + "'></SCR" + "IPT>");
};

var trackingDebug;
function 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 = "/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));
};

//Overide this function on your local site if you want to do something different
function trace(what) {
	if (trackingDebug != undefined && 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 = $("#page").find("a");
	//trace("Page Anchors.length = " + anchors.length);

	for (var i = 0; i < anchors.length; i++) {

		//var a = anchors[i];
		var a = $(anchors[i]);
		var newId = "";

		if (a.attr("id") == "" || a.attr("id").indexOf("_dt") != -1 || a.attr("id").indexOf("dt_") != -1 || a.hasClass("dt")) {
			//don't track this
			continue;
		}
		var testURL = a.attr("href");
		if (testURL == undefined) {
			continue;
		}
		var rootURL = testURL.replace(window.location, "");
		if (rootURL != "" && rootURL != "#" && (a.attr("target") == "" || a.attr("target") == "_self" || a.attr("target") == "_top")) {
			if (!a[0].onclick) {
				//trace("Adding TEAG to = " + a[0].id);
				a[0].onclick = function () { return trackEventAndGoto(this); };
			}
		} else {
			if (!a[0].onclick) {
				//trace("Adding TE to = " + a[0].id);
				a[0].onclick = function () { trackEvent(this); };
			}
		}
	};
	//gsm_rewriteForms();
}
function gsm_rewriteForms() {

	var forms = $("#page").find("form");
	for (var i = 0; i < forms.length; i++) {
		var f = $(forms[i]);
		f.attr("onsubmit", function () { return trackEventAndSubmit(this); })
	}
};

$(document).ready(function () { gsm_rewriteAnchors() });

ts_init();