//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://www.t-mobilenavigation.com/";

}

var ts_scripts = ["/scripts/tracking_gsm/tracking_core.js",
                  //"/scripts/ga.js",
				  "/scripts/webtrends/sdc_advanced.js",
				  "/scripts/tracking_gsm/tracking_init.js",
				  "/scripts/tracking_maps/map_unav.js"];

//List out all the possible webtrends accounts
var ts_WTID = {
    "default": "dcs0000000000000000000000_0000",
    "myfaves.com": "dcsh2sdjk000000ggbkpcmzf1_5w8m",
    "sidekick.com": "dcsfkfzco10000w0yrfjs7cf1_4q4w",
    "theonlyphoneyouneed.com": "dcs3mwte1000000w8s0h430g1_7m7i",
    "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",
	"cliq.t-mobile.com":"dcs1jaqbn100000wo0a6qjhmx_6f3s"
};

var ts_GOID = {
    "default": "UA-3641653-1",
    "myfaves.com": "UA-3622171-1",
    "sidekick.com": "UA-3066297-1",
    "theonlyphoneyouneed.com": "UA-30686515-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":""
};

var ts_PREFIXES = {
    "default": "test_",
    "myfaves.com": "myFaves_",
    "sidekick.com": "sk_",
    "theonlyphoneyouneed.com": "athome_",
    "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_",
	"cliq.t-mobile.com": "cliq_"
};

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
    //for (var i = 0; i< ts_scripts.length; i++) {
    //alert("ts_addMainFunctions" + ts_masterURL + ts_scripts[i]);
    //document.write("<SCR"+"IPT TYPE='text/javascript' src='" + ts_masterURL + ts_scripts[i] + "'></SCR"+"IPT>");
    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'];
        trackingMaps;
        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='/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");
    }
    

    if (trackingDebug == "true" && (ts_debugWindow == null || (ts_debugWindow != null && ts_debugWindow.closed == true))) {
        ts_debugWindow = window.open("", "debugger", "menubar=false,width=800,height=620,scrollbars=yes,resizable=yes");
        if (ts_debugWindow.location.href.indexOf("debug") == -1) {
            ts_debugWindow.location.href = "/utils/debug.aspx?trace=" + passThru + "&lastID=" + passThruID;
        }
        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) {
    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");
        }
    }
}

//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 == "") {
            //trace("noID");
            var tempId = "autogen_" + ts_pageName.split("-").join("") 
            tempId = tempId.split("?");
            newId = tempId[0] + "_link_" + i;
            a.id = newId;
        }
        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) {
                    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) {
                    //trace("adding trackEvent, saving functions :" + a.id);
					//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);
                    }
                    */
                    //alert("adding event to : " + a.id);
                } else {
                    //alert("had code not adding anything to : " + a.id);
                    //This must have legacy tracking code on it, so leave it be
                }
            } else {
                //trace("adding trackEvent");
                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);
    }
    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);
}
