
stag =
{

    thisDomain: 0,
    thisPath: 0,
    refDomain: 0,
    refKeywords: 0,
    loadTime: 0,
    hasUnloaded: 0,
    thisSection: '',

    Init: function() {
        with (this) {
            SetHandler(window, 'load', PageLoad);
            SetHandler(window, 'beforeunload', Unload);
            loadTime = new Date();
            thisDomain = GetDomain(window.location.url);
            thisPath = GetPath(window.location.href);
            refDomain = GetDomain(document.referrer);
            refKeywords = GetKeywords(document.referrer);
            m_dataMap.pair.section.value = GetSection(document.location.href);
            m_dataMap.pair.country.value = 'ca';
            thisSection = m_dataMap.pair.section.value;

        }
    },


    // Handlers
    SetHandler: function(obj, eventname, handler) {
        with (this) {
            if (IsNOrU(obj.addEventListener)) {
                obj.detachEvent('on' + eventname, handler);
                obj.attachEvent('on' + eventname, handler);
            }
            else {
                obj.removeEventListener(eventname, handler, false);
                obj.addEventListener(eventname, handler, false);
            }
        }
    },

    Unload: function() {
        with (stag) {
            HoldPageUnload(1000);
            hasUnloaded = 1;
            Action('unload');
        }
    },

    PageLoad: function(evt) {
        with (stag) {
            m_dataMap.pair.location.value = CleanString(thisPath);
            var dr = document.referrer;
            var ss = GetQuerystringValue("source");

            var sr = GetCookie(document.cookie, 'sesref');
            if (sr) {
                if (sr.indexOf(document.domain) == -1) {
                    dr = sr;
                }
            } else {
                SetCookie('sesref', encodeURIComponent(dr), false);
            }

            var cs = GetCookie(document.cookie, 'sessrc')
            if (cs) {
                ss = cs;
            } else if (ss) {
                SetCookie('sessrc', ss, false);
            }
            // set pair values
            if (dr.indexOf(document.domain < 0)) {
                m_dataMap.pair.url.value = encodeURIComponent(dr);
                m_dataMap.pair.domain.value = GetDomain(dr);
            }
            m_dataMap.pair.keywords.value = GetKeywords(dr);
            m_dataMap.pair.search.value = GetKeywords(dr, 1);
            m_dataMap.pair.source.value = ss;
            if (window.partnerId) m_dataMap.pair.var1.value = partnerId;
            View();
        }
    },





    // Util Functions
    IsNOrU: function(obj) {
        return !(typeof obj != 'undefined' && obj != null);
    },
    GetSection: function(u) {
        pages = [
            { url: '\/home\/', section: 'home' },
            { url: '\/editions\/', section: 'Select an Edition' },
            { url: '\/locator\/', section: 'Find a PC' },
            { url: '\/buyingguide\/', section: 'Buying Guide' }
            ]

        for (var i = 0; i < pages.length; i++) {
            var page = pages[i];
            if (u.match(pages[i].url)) {
                return pages[i].section;
            }
        }

    },

    GetDomain: function(i) {
        var regex = "(?:http|https)://(.*?)/";

        if (i && i.length > 0) {
            var start = i.indexOf("//") + 2;

            var end = i.indexOf("/", 8);

            if (end == -1) { end = i.length };

            return (i.substring(start, end));
        }

        return "";
    },

    GetPath: function(i) {
        if (!this.IsNOrU(window.document.href)) {
            return encodeURIComponent(this.CleanString(window.document.href));
        }
        if (i && i.length > 0) {
            // Find the first / after "http://" (8 is length of "https://")
            var start = i.indexOf("/", 8);

            var end = i.indexOf('?');

            if (end == -1) { end = i.length };

            return (i.substring(start, end));
        }

        return "";
    },

    GetKeywords: function(i, p) {
        with (this) {
            providers =
			{
			    // Order based on marketshare
			    Google: { form: "http://www.google.com/search?", key: "q" },
			    Yahoo: { form: "http://search.yahoo.com/search?", key: "p" },
			    Bing: { form: "http://www.bing.com/search?", key: "q" },
			    AOL: { form: "http://search.aol.com/aol/search?", key: "query" },
			    AskWeb: { form: "http://www.ask.com/web?", key: "q" },
			    AskBar: { form: "http://www.ask.com/bar?", key: "q" },
			    //Baidu: { form: "http://www.baidu.com/s?", key: "wd" },
			    Test: { form: "http://test.razorfish.com", key: "q" }
			}

            // loop through all m_searchProviders
            for (var search in providers) {
                // check for a match
                if (i.indexOf(providers[search].form) == 0) {
                    // extract keywords
                    if (p) return search;
                    return GetQuerystringValue(providers[search].key, i).replace(/[+]/g, ",");
                }
            }

            // no major search providers found, return empty string
            return "";
        }
    },

    GetQuerystringValue: function(s, u) {
        s += "=";
        var h = u ? u : window.location.href,
            ss = h.indexOf(s),
            a = "&";
        q = h.indexOf('?');
        if (q > 0 && ss > q) {
            sh = h.substring(ss + s.length);
            return sh.indexOf(a) > 0 ?
                       sh.substring(0, sh.indexOf(a)) :
                       sh;
        }
        return "";
    },

    StrSetCookie: function(key, val, isPersistent, hostname, date) {
        var cookieVal = key + '=' + val;
        var dom = hostname == '' ? null : hostname.match(/[^\.]*\.[^\.]*$/);
        if (dom != null && dom[0].length < 6) {
            // Check for co.uk domains
            dom = hostname.match(/[^\.]*\.[^\.]*\.[^\.]*$/);
            if (dom != null)
                dom[0] = dom[0].replace(/^www\./i, '')
        }
        if (dom != null) // Add the domain only if valid
            cookieVal += ('; domain=' + dom[0]);
        cookieVal += '; path=/; ';
        if (isPersistent) {
            date.setTime(date.getTime() + (365 * 24 * 60 * 60 * 1000));
            cookieVal += 'expires=' + date.toGMTString() + '; ';
        }
        return cookieVal;
    },

    GetCookie: function(cookie, name) {
        var aCookie = cookie.split('; ');
        for (var i = 0; i < aCookie.length; i++) {
            var aCrumb = aCookie[i].split('=');
            if (aCrumb.length > 1 && name == aCrumb[0])
                return unescape(aCrumb[1]);
        }
        return null;
    },

    SetCookie: function(key, val, isPersistent) {
        var lh = location.hostname && location.hostname != 'localhost' ? location.hostname : ''
        document.cookie = this.StrSetCookie(key, val, isPersistent, lh, new Date());
    },

    // atlas action method
    Action: function(action) {

        // groom it
        var a = this.CleanString(action);

        // split based on delimiter
        var p = a.split("|");

        if (p.length > 5) {
            // iterate through parts
            for (var i = 0; i < p.length; ++i) {
                // pivot on index
                switch (i) {
                    // set action                                                                    
                    case 0:
                        this.m_dataMap.pair.action.value = p[i];
                        break;
                    // set actionname                                                                    
                    case 1:
                        this.m_dataMap.pair.actionname.value = p[i];
                        break;
                    // set section                                                                    
                    case 2:
                        this.m_dataMap.pair.section.value = p[i];
                        break;
                    // set time                                                                    
                    case 3:
                        this.m_dataMap.pair.time.value = p[i];
                        break;
                    // set videotime                                                                    
                    case 4:
                        this.m_dataMap.pair.videotime.value = p[i];
                        break;
                    // set videosession                                                                    
                    case 5:
                        this.m_dataMap.pair.videosession.value = p[i];
                        break;
                    // set var1                                                                    
                    case 6:
                        this.m_dataMap.pair.var1.value = p[i];
                        break;
                    case 7:
                        // set var2
                        this.m_dataMap.pair.var2.value = p[i];
                        break;
                }
            }
        }
        else {
            // iterate through parts
            for (var i = 0; i < p.length; ++i) {
                // pivot on index
                switch (i) {
                    // set action                                                                    
                    case 0:
                        this.m_dataMap.pair.action.value = p[i];
                        break;
                    // set actionname                                                                    
                    case 1:
                        this.m_dataMap.pair.actionname.value = p[i];
                        break;
                    // set section                                                                    
                    case 2:
                        this.m_dataMap.pair.section.value = p[i];
                        break;
                    // set var1                                                                    
                    case 3:
                        this.m_dataMap.pair.var1.value = p[i];
                        break;
                    // set var2                                                                    
                    case 4:
                        this.m_dataMap.pair.var2.value = p[i];
                        break;
                }
            }
        }

        // build url
        var url = this.m_dataMap.buildUrl();
        // alert(url);
        // load it
        //this.LoadImage(url);
        this.Queue(url);

        // notify listeners
        for (var i = 0; i < this.m_actionListeners.length; ++i) {
            // save bytes w/ a shortcut reference
            var cb = this.m_actionListeners[i];

            // invoke callback                
            if (typeof cb == 'function')
                cb(url);
        }

        //clear remaining obsolete value
        this.m_dataMap.pair.time.value = "";
        this.m_dataMap.pair.videotime.value = "";
        this.m_dataMap.pair.videosession.value = "";
        this.m_dataMap.pair.var2.value = "";
    },

    // atlas click event
    View: function() {
        // invoke view action
        this.Action("view");
    },

    m_actionListeners: new Array(),

    // time pivot in seconds (used for unload event)
    m_timePivot: 5,

    // image obj
    m_image: new Image(),

    // Tracking calls queue.
    m_queue: new Array(),
    m_tLoading: false,
    // name value pairs
    m_dataMap:
    {
        // single values
        single:
        {
            url: "switch.atdmt.com",  // base atlas url
            type: "action",            // denotes event type
            project: "riax_msft_wnseven",                  // project name
            version: "v3"                 // denotes atlas version
        },

        // name value pairs
        pair:
        {
            language: { value: navigator.language ?
                                   navigator.language :
                                   navigator.browserLanguage
            },  // user-agent language
            country: { value: "" },                         // country
            location: { value: "" },                         // location value (i.e., page name)
            action: { value: "", reset: 1 },              // action (e.g., "click" or "view")
            actionname: { value: "", reset: 1 },              // actionname (e.g., "privacy" or "legal")
            section: { value: "", reset: 0 },              // section (e.g., "Confirmation" or "Footer")
            source: { value: "" },                         // source (querystring value of parameter "source")
            time: { value: "" },                         // timeonpage (should be # of seconds on page)
            videotime: { value: "" },                         // videotime(used for video player)
            videosession: { value: "" },                      // videosession(used for video player)
            var1: { value: "" }, 					 // extra svar1: { value: partnerId }, 	
            var2: { value: "" }, 					 // extras
            search: { value: "" },                         // search engine
            keywords: { value: "" },                         // search keywords
            domain: { value: "" },                         // url domain
            url: { value: ""}                          // url (document.referrer value)
        },

        // builds out a URL
        buildUrl: function() {
            // url uber base
            var u = ["http:/"];

            // add singles
            for (var s in this.single) {
                // add value
                u.push(this.single[s]);
            }

            // add doubles
            for (var p in this.pair) {
                // get value
                var v = this.pair[p].value;

                // do null?
                if (v != "") {
                    // add name and value
                    u.push(p + "." + v);
                }

                // reset?
                if (this.pair[p].reset) {
                    // set to null
                    this.pair[p].value = "";
                }
            }

            // return completed url
            return u.join('/');
        }
    },

    Queue: function(src) {
        with (stag) {
            LoadImage(src);
            //if (m_tLoading && !hasUnloaded)
            // m_queue.push(src);
            //else
            //   LoadImage(src); // load new image with a cache-killer param attached
        }
    },
    /**************************************************************************
    ** UTILITY METHODS
    *************************************************************************/

    // loads and image
    LoadImage: function(i) {
        with (stag) {
            m_tLoading = true;
            // load new image with a cache-killer param attached
            m_image.src = i + "/?" + Math.random();
        }
    },

    // cleans up a string and removes 'bad' characters
    CleanString: function(str) {
        //str = unescape(str);
        str = str.replace(/\/|\?|&|\.|#/g, "_").replace('%3F', '_').replace('%3A', '');
        return str;
    },

    HoldPageUnload: function(t) {
        var ULTin = new Date().getTime();
        var ULTout = ULTin;
        for (var i = 0; ULTin + t > ULTout; i++) {
            window.status = '';
            ULTout = new Date().getTime();
        }
    }

}

stag.Init(true);

$(document).ready(function() {
    $('area').each(function() {
        var trackstring = 'click|' + $(this).attr('alt') + '|' + stag.m_dataMap.pair.section.value + "|" + partnerId;
        $(this).attr('track', trackstring);
        $(this).click(function() {
            stag.Action($(this).attr('track'));
        });
    });

    $('img#w7ReadySubmit').click(function() {
        var os = $('select#w7ReadyOS').val();
        var cpu = $('select#w7ReadyProcessor').val();
        var ram = $('select#w7ReadyRam').val();
        var hd = $('select#w7ReadyHD').val();
        var directx = $('#w7ReadyDirectX').is(':checked');
        var ags = $('#w7ReadyAGS').is(':checked');
        stag.m_dataMap.pair.var2.value = "os_" + os + "-cpu_" + cpu + "-ram_" + ram + "-hd_" + hd + "-directx_" + directx + "-ags_" + ags;
        stag.Action('click|Get Reccomendations');
    });

    $('a').each(function() {
        var trackstring = 'click|';
        var bucket = false;
        var linkname = '';
        if ($(this).text() == "") {
            trackstring += $(this).find(":first").attr('alt');
        } else {
            trackstring += $(this).text();
        }

        //trackstring += '|' + stag.m_dataMap.pair.section.value + "|" + partnerId;

        bucket = $(this).parents()
                    .map(function() {
                        var tcn = this.className;
                        if ((this.className && this.className.indexOf('w7Nav') != -1) || (this.id && this.id.indexOf('w7Nav') != -1)) return 'Site Nav';
                    }).get();

        if (bucket.length > 0) {
            trackstring += '|' + bucket[0];
        }
        //trackstring += '|' + stag.m_dataMap.pair.section.value + "|" + partnerId;
        $(this).attr('track', trackstring);
        $(this).click(function() {
            //stag.Action($(this).attr('track'));
            stag.Action(eval("'" + trackstring + "'"));
            stag.m_dataMap.pair.section.value = stag.thisSection;
        });

    });

});

