﻿/// <summary>OBJECT "imObject": MSNMessenger.P4QuickLaunch ActiveX Object</summary>
/// <remarks>Object for use in imIt which launches IM if object is not null</remarks>
var imObject = imCheck();

/// <summary>FUNCTION "imCheck": tests for presence of MSNMessenger.P4QuickLaunch ActiveX Object</summary>
/// <return>Object or null</return>
function imCheck() {
  var a = i = null;
  var obj = getObject("MSNMessenger.P4QuickLaunch");
  
  if (!obj) { 
    obj = null; 
    if (navigator.userAgent.indexOf("MSIE") > -1) { imDisable(noimMsg); };
  };
  return obj;
  
  function getObject(sname) {
    try { return new ActiveXObject(sname); }
    catch(e) { return null; }
  };
};
/// <summary>FUNCTION "imDisable": render IM link with disabled look and appropriate tooltip</summary>
/// <param name="msg">string value error message for img alt and anchor tooltip</param>
function imDisable(msg) {
  writeCookie("IMID","", null, null); 
  a = document.getElementById(imLinkId);
   
  if (!a) { return; };
  i = a.getElementsByTagName("IMG")[0];
  a.className = "nogif";
  a.removeAttribute("href");
  if (msg!=null && msg!="") { a.title = i.alt = msg; };
  i.src = i.src.replace(".gif", "no.gif");
};

/// <summary>FUNCTION "imIt": opens messenger</summary>
/// <param name="pname">name of parameter</param>
/// <param name="pval">documentid for storing in cookie</param>
/// <remarks>if no appID supplied IM will open session in "Start an Activity" mode (after User selects buddy to contact)</remarks>
/// <remarks>when appID is supplied IM will open session in "Invite" mode (after User selects buddy to contact), launch the IE pane on invite acceptance and paste the web url and a comment in the "Send" area of the Users IM</remarks>
function imIt(pname, pval) {
  if (imObject) {
    if (imAppId) {  
      var cookieValue = escape(pname + "=" + pval) + "|" + escape(document.location.href);
      writeCookie("IMID", cookieValue, null, null); 
      
      // user can block 3rd party cookies or all cookies.
      if (document.cookie.indexOf(cookieValue) < 0) {
        imDisable(ckimMsg);
      } else {
        try { imObject.LaunchApp(imAppId, ""); }
        catch (e) { imDisable(''); }; //IM not running
      };
    } else { imObject.LaunchApp("", ""); }; 
  };
};

/// <summary>FUNCTION "printIt": open print dialog</summary>
/// <remarks>xpr_toolbar.css provides base print styling, also expsed in print preview</remarks>
function printIt() { window.print(); };

/// <summary>FUNCTION "blogIt": opens spaces blog entry with title and any selected texted entered</summary>
/// <param name="bnew">boolean indicating whether to open feature in new browser window</param>
function blogIt(bnew) {
  var txt = getSelectedText();

  window.open(msnSpacesApi + "?Title=" + document.title + 
              "&SourceURL=" + escape(window.location.href.replace(window.location.hash, "")) + 
              "&description=" + txt, (bnew) ? "_toolbar" : "_self", "", bnew)
};

/// <summary>FUNCTION "getSelection": returns selected text value</summary>
function getSelectedText() {
  var txt = "";
  if (window.getSelection) { txt = window.getSelection(); }
  else {
    var range = document.selection.createRange();
    range.expand("word");
    txt = range.text;
  };
  return txt;
};

/// <summary>FUNCTION "emailIt": opens "new message" in user's e-mail client</summary>
/// <param name="title">string value of document title - processed on server to ensure corect code-page encoding for non-utf8 mailto client</param>
/// <remarks>mailto only at present</remarks>
function emailIt(title) { 
  if (title == "") { title = document.title; };
  title = title.replace(/\"/g, escape('"'));  
  title = title.replace(/&/g,escape('&'));
  window.location = "mailto:" + "?subject=" + title + "&body=" + title + ":%0d%0a%0d%0a" + escape(window.location.href.replace(window.location.hash, "")); 
};

/// <summary>FUNCTION "": opens "article" for submission to MSN Reporter</summary>
/// <param name="bnew">boolean indicating whether to open feature in new browers window</param>
function reporterIt(base, referer, categ, tag, bnew){
  if (base.indexOf("?f=contribute") == -1) { base += "?f=contribute"; };
  var txt = getSelectedText();
  var url = base + "&url=" + escape(document.location.href) + "&referrer=" + escape(referer);
  url += "&title=" + (reporterTitle!=''? reporterTitle : document.title);
  url += (txt!="") ? "&remark=" + txt : "";
  url += (categ!="" ? "&cat_id=" + categ : "");
  url += (tag!="" ? "&tag_id=" + tag : "");
  
  window.open(url, (bnew) ? "_toolbar" : "_self", "", bnew);
};

/// <summary>FUNCTION "rssIt": opens RSS feed in browser</summary>
/// <param name="url">rss feed url (from slot tree or page meta data)</param>
/// <remarks></remarks>
//function rssIt(url) { window.open(url, "_toolbar", "", false); };

/// <summary>FUNCTION "addToLive": opens apces "add" page which allows user to add feed to their personalized live.com page</summary>
/// <param name="host">live.com "add" page host url</param>
/// <param name="feedUrl">rss feed url (from slot tree or page meta data)</param>
/// <param name="bnew">boolean indicating whether to open feature in new browers window</param>
/// <remarks></remarks>
//function addToLive(host, feedUrl, bnew) { window.open(host + escape(feedUrl), (bnew) ? "_toolbar" : "_self", "", bnew); };

/// <summary>FUNCTION "subscribeLiveAlert":</summary>
/// <param name="url">live alert service url</param>
/// <param name="bnew">boolean indicating whether to open feature in new browers window</param>
/// <remarks></remarks>
//function subscribeLiveAlert(url, bnew) { window.open(url + ((bnew) ? "" : "&returnURL="+ escape(window.location.href.replace(window.location.hash, ""))), (bnew) ? "_toolbar" : "_self", "", bnew); };

/// <summary>Sets cookie content</summary>
/// <param name="cookieName">cookie name</param>
/// <param name="cookieValue">cookie content value</param>
/// <param name="expiryDate">date to expire</param>
/// <param name="path">cookie path value</param>
/// <return>false</return>
function writeCookie(cookieName, cookieValue, expiryDate, path) {
    var newExpiry = null;
    
    if (typeof expiryDate == "undefined" || expiryDate == null || expiryDate == "") {
        /* set expiry for today + 5 years */
        newExpiry = new Date();
        newExpiry.setYear(newExpiry.getFullYear() + 5);
    }
    else { newExpiry = expiryDate; }

    if (typeof path == "undefined" || path == null) { path = "/"; };
    
    if (typeof document!="undefined") { return document.cookie = cookieName + "=" + cookieValue + ";expires=" + newExpiry.toGMTString() + ";path=" + path + ";"; }
    return false;
};

/// <summary>PUBLIC "track_tb" object: custom "ToolbarTracking" object</summary>
var track_tb = new ToolbarTracking();
// initialize tracking object
track_tb.OnCreate();

/// <summary>PUBLIC "ToolbarTracking" object: custom "ToolbarTracking" object</summary>
/// <remarks>Object tracks toolbar button clicks through Omniture</remarks>
function ToolbarTracking() {
    /// <summary>PRIVATE "_t" constant: pointing to instance of "this" object - good practise, required for JavaScript closure</summary>
    _t = this;

    /// <summary>PUBLIC "isIe" constant: boolean value (true = IE 4+, false: other browser)</summary>
    _t.isIe = (navigator.userAgent.indexOf("MSIE") > -1 && (parseInt(navigator.appVersion) >=4));

    /// <summary>PUBLIC "trackingType" variable: string value - activity id value (MostBlogged, MostEmailed, MostPrinted, MostMessaged, MostKicked)</summary>
    _t.trackingType = "Unknown";

    /// <summary>PUBLIC "PostOminitureTrack" function: </summary>
    /// <remarks>Called by "Track" function</remarks>
    _t.PostOminitureTrack = function() {
        // load reference to"window.s" object (created in page for Omniture tracking)
        var source = window.s;
        
        // set custom toolbar property values
        source.prop40 = document.documentElement.getAttribute("lang"); // Market
        source.prop41 = (location.host.indexOf(".msn.")>-1) ? location.host.substr(0,location.host.indexOf(".msn.")).replace(/\./g," ") : location.host; // Site
        source.prop42 = location.pathname.substr(1).replace(location.pathname.substr(location.pathname.lastIndexOf("/")),"").replace(/\//g, " "); // Dept.
        //source.prop11 = _t.trackingType + "|" + pageType_tb; // PG or Article
        source.prop43 = _t.trackingType; 
        
        // fix page url by stripping "#toolbar"
        source.prop44 = source.prop13 = source.prop29 = GetCleanUrl();
        source.prop45 = pageType_tb; // PG or Article
        
        
        if (source.prop49 == "") { source.prop49 = escape(document.title).replace(/"/g, '\\"'); };
        
        // set charset property value (ensures double byte sets reported correctly)
        source.charSet = "UTF-8";
        
        lt = (source.prop16 !='') ? 'o': 'e';

        var omniImg = document.getElementById("omni").getElementsByTagName("img")[0];
        var omniModuleValues = "";
        
        omniModuleValues += "&c40=" + escape(source.prop40) + "&c41=" + escape(source.prop41) + "&c42=" + escape(source.prop42) + "&c43=" + escape(source.prop43) + "&c44=" + escape(source.prop44)  + "&c45=" + escape(source.prop45);

        // call tracking  - with  module level account name & values
        CallOmniTrack(omniImg, window.s_account, tbarOAName, omniModuleValues);
        
//        source.tl(_t,lt,source.prop16);
//        source.t();
        
        /// <summary>PRIVATE "CallOmniTrack" function: </summary>
        /// <param name="img">omniture IMG html element</param>
        /// <param name="pageAccName"></param>
        /// <param name="modAccName"></param>
        /// <param name="propvalues"></param>
        function CallOmniTrack(img, pageAccName, modAccName, propvalues) {
            var itrack = new Image(2,2);
            itrack.src = GetImageUrl(img);
            itrack = null;
            
            /// <summary>PRIVATE "GetImageUrl" function: returns tracking image url</summary>
            /// <param name="i">img html element (page level omniture tracking image)</param>
            /// <remarks></remarks>
            function GetImageUrl(i) {
                // create & execute reg exp to capture page level tracking image src attribute value BEFORE "[AQE]" marker
                var re = new RegExp("(.*)&\\[AQE\\]");
                var arr = re.exec(i.src);
                // return matched url value + propvalues parameter value + "[AQE]" marker
                return arr[1].replace(pageAccName, modAccName) + propvalues + "&[AQE]";
            };
                        
        };
        
        /// <summary>PRIVATE "GetCleanUrl" function: strip anchor/bookmark hash value from URL</summary>
        /// <returns>document URL without anchor/bookmark hash value </returns>
        /// <remarks>Fix page url by stripping "#toolbar"</remarks>
        /// <remarks>Omniture system logs http://news.uk.msn.com/article.aspx?cp-documentid=000000#toolbar as different page to http://news.uk.msn.com/article.aspx?cp-documentid=000000</remarks>
        function GetCleanUrl() { return document.URL.replace(location.hash,""); };
    };
    
    /// <summary>PUBLIC "IsToolBarOnClick" function: determines if the click came from the toolbar</summary>
    /// <param name="srcObject" type="object">HTML element</param>
    /// <returns>boolean value: true (toolbar button clicked); false (toolbar button NOT clicked)</returns>
    /// <remarks>Called by "Track" function</remarks>
    _t.IsToolBarOnClick = function(srcObject)
    {
        if (srcObject == null) {
            return false;
        };
        
        var parentObject = null;
        
        if(srcObject.tagName == "A") {
            parentObject = srcObject;
        }
        else {
            parentObject = srcObject.parentElement;
        };
        
        if(parentObject != null) {
            var isToolBar = ( parentObject.id == "email" ||  parentObject.id == "blog" ||  parentObject.id == "print" ||  parentObject.id == "messenger" ||  parentObject.id == "reporter");
            
            if (isToolBar) {
                _t.SetTrackingType(parentObject.id);
            };
            return (isToolBar);
        }
        else {
            return false;
        };
    };

    /// <summary>PUBLIC "SetTrackingType" function: </summary>
    /// <param name="trackingType" type="string">HTML element id value</param>
    /// <remarks>Called by "IsToolBarOnClick" function</remarks>
    _t.SetTrackingType = function(trackingType)
    {
        if(trackingType.indexOf("email") > -1) {
            _t.trackingType = "MostEmailed";
        }
        else if(trackingType.indexOf("blog") > -1) {
            _t.trackingType = "MostBlogged";
        }
        else if(trackingType.indexOf("print") > -1) {
            _t.trackingType = "MostPrinted";
        }
        else if(trackingType.indexOf("messenger") > -1) {
            _t.trackingType = "MostMessaged";
        }
        else if(trackingType.indexOf("reporter") > -1) {
            _t.trackingType = "MostKicked";
        }
        else {
            _t.trackingType = "Unknown";
        }
    };
        
    /// <summary>PUBLIC "OnCreate" function: initializes object</summary>
    /// <remarks>Attachs event listeners to associated event handlers</remarks>
    _t.OnCreate = function()
    {
        if(window.s) {
            if(document.attachEvent || _t.isIe) {
                document.body.detachEvent("onclick",window.s.bc);
                document.attachEvent("onclick",window.s.bc);
                document.attachEvent("onclick",_t.Track);
                window.attachEvent("onunload",_t.OnDestroy);
            }
            else {
                 document.body.detachEventListener("click", window.s.bc, false);         
                 document.addEventListener("click",window.s.bc , false);
                 document.addEventListener("click",_t.Track , false); 
                 window.addEventListener("unload", _t.OnDestroy,  false); 
            };
        };
    };

    /// <summary>PUBLIC "OnDestroy" function: detroys object</summary>
    /// <remarks>Detachs event listeners, nulls object properties</remarks>
    _t.OnDestroy = function()
    {
        if (document.detachEvent || _t.isIe) {
            window.detachEvent("onunload",_t.OnDestroy);
            document.detachEvent("onclick",_t.Track);
        }
        else {
            window.detachEventListener("unload",_t.OnDestroy, false);
            document.detachEventListener("click",_t.Track, false);    
        };
         _t = _t.trackingType = _t.isIe = null;
    };
        
    /// <summary>PUBLIC "Track" function: </summary>
    /// <param name="" type=""></param>
    /// <returns></returns>
    /// <remarks></remarks>
    _t.Track = function()
    {
        if (window.s && _t.IsToolBarOnClick(window.event.srcElement)) {
          if (window.s.trackExternalLinks) {
              window.s.trackExternalLinks = false;
          };
          _t.PostOminitureTrack();
        };
    };
};
    

