//generic
var _neutralPath = "/resources/neutral/";
var _targetedPath = "/resources/targeted/";
var _cgifUrlPath = _neutralPath + "c.gif";
var _printHeadImg = _neutralPath + "windows_flag.gif";
var _welcomePage = "welcome.htm", _moreHelpPage = "wlgmh.htm", _helpCommunityPage = "helpcomm.htm";
var _faqKey = "qaf", _omniImgKey = "msnportal", _megaInstIdKey = "mega";
var _winWidth = 640, _winHeight = 640;
var _srchDispInc = 5;
var _thinSvc = "thinservice.aspx";
var _commHost = "", _env = "", _appPath = "", _showSurvey = false;
//Decision tree
var _dtUrl = "", _dtMessengerUrl = "", _hwFreq = "", _dtRetHead = "", _dtRetText = "";
//user-specific (defined in page header)
var _queryOriginal = _query;
//market-specific
var _mkt = "en-us", _tlHelpHead = "", _tlCommHead = "", _tlFaqHead = "", _tlTocHead = "", _queryDefault = "", _progressText = "", _viewMoreText = "";
//project-specific
var _forumId = "", _boardId = "", _threadId = "", _appTitle = "", _cuWinMode = "", _cuWriteCookie = "", _fdbckButtonStyle = "", _useDt = false;
var _sessionIdTimeoutMin = 5;

/*******************************/
/***** SessionId (SID) Object *****/
/*******************************/
function SID () {}
SID.resolveGlobalSessionId = function () {
    if ((_sidQS != null) && (_sidQS != "") && (_tsQS != null) && (_tsQS != "")) {
        // session id passed in through query string
        var min = GetCurrentMin();    
        var diff = min - _tsQS;
        if ((diff >= 0) && (diff <= _sessionIdTimeoutMin)) {
            _sid = _sidQS;
        } // else keep value of _sid var unchanged        
    }
    // else keep value of _sid var unchanged
}
 
/*******************************/
/***** Colmid (CM) Object *****/
/*******************************/
function CM() {}
CM.mouseover = function(p_o) {p_o.style.backgroundColor = "#FFFFFF";}
CM.mouseout = function(p_o) {p_o.style.backgroundColor = "#FFFFFF";}
CM.mousedown = function(p_ev) {
    p_ev = (p_ev) ? p_ev : event;
    CM.ismousedown = true;
    CM.currpos = p_ev.clientX;
    CM.currLeftW = CM.getCurrLeftW();
    document.body.style.cursor = 'e-resize';
    return false;
}
CM.mouseup = function() {
    CM.ismousedown = false;
    document.body.style.cursor = 'auto';
    CM.currLeftW = parseInt(document.getElementById("colleft").style.width);
    return false;
}
CM.mousemove = function(p_ev) {
    if (CM.ismousedown) {
        p_ev = (p_ev) ? p_ev : event;
        var newpos = p_ev.clientX;
        var pxmoved = parseInt(newpos - CM.currpos);
        pxmoved = (IsRTL()) ?  -pxmoved : pxmoved;
        var newLeftW = parseInt(CM.currLeftW + pxmoved);
        var newRightW = GetWinWidth() - newLeftW - CM.rightWAdj;
        //TL.display('',newRightW)//DEBUG
        if (newLeftW >= CM.minLeft && newRightW >= CM.minRight) {
            document.getElementById("colleft").style.width = newLeftW + 'px';
        }
        return false
    } else return true;
}
CM.setMinLeft = function() {
    CM.minLeft = parseInt(document.getElementById("colleft").style.width);
}
CM.getCurrRightW = function() {
    return GetWinWidth() - CM.getCurrLeftW() - CM.rightWAdj;
}
CM.getCurrLeftW = function() {
    if (CM.currLeftW == 0) CM.currLeftW = parseInt(document.getElementById("colleft").style.width);
    return CM.currLeftW;
}
CM.ismousedown;
CM.currpos;
CM.currLeftW = 0;
CM.minLeft;
CM.minRight = 300;
CM.rightWAdj = 21;//8+8+5
/***** End Colmid (CM) Object *****/

/***********************************/
/***** Community (Comm) Object *****/
/***********************************/
function Comm() {}
Comm.exists = function() {
    return (_forumId != null && _forumId != "")
        && (_boardId != null && _boardId != "");
}
Comm.showNavLink = function(){
    if (Comm.exists()) {
        var o = document.getElementById('gotocomm');
        o.href = Comm.getHomeUrl();
        o.style.display = 'inline';
        Comm.navLinkHidden = false;
    }
}
Comm.hideNavLink = function() {
    document.getElementById('gotocomm').style.display = 'none';
    Comm.navLinkHidden = true;
}
Comm.goToSite = function(p_fid,p_bid,p_tid) {
    var fid = Comm.getForumId(p_fid);
    MapLog.UserSentToCommunity(p_tid,fid,p_bid);//omniture
    OpenNewWin(Comm.getUrl(fid,p_bid,p_tid,null),"commwin","");
    return false;
}
Comm.goToSiteUrl = function(p_url,p_fid,p_bid,p_tid) {
    MapLog.UserSentToCommunity(p_tid,p_fid,p_bid);//omniture
    OpenNewWin(p_url,"commwin","");
    return false;
}
Comm.getUrl = function(p_fid,p_bid,p_tid,p_mid) {
    var url;
    if (IsStringNullOrEmpty(p_fid) || IsStringNullOrEmpty(p_bid)) {
        url = Comm.getHomeUrl();
    }
    else if (IsStringNullOrEmpty(p_tid)) {
        url = Comm.getBoardUrl(p_fid,p_bid);
    }
    else if (IsStringNullOrEmpty(p_mid)) {
        url = Comm.getThreadUrl(p_fid,p_bid,p_tid);
    }
    else {
        url = Comm.getMessageUrl(p_fid,p_bid,p_tid,p_mid);
    }

    url += "?sid=" + Comm.getSidString();
    if (!IsStringNullOrEmpty(p_mid)) url += "#msg" + p_mid;
    return url;
}
Comm.getHomeUrl = function() {
    var url = "http://" + _commHost + "/" + _mkt;
    return url;
}
Comm.getForumUrl = function(p_fid) {
    var url = null;
    if (!IsStringNullOrEmpty(p_fid)) {
        url = Comm.getHomeUrl();
        url += "/" + p_fid;
    }
    return url;    
}
Comm.getBoardUrl = function(p_fid,p_bid) {
    var url = Comm.getForumUrl(p_fid);
    if (url == null) {}
    else if (!IsStringNullOrEmpty(p_bid)) {
        url += "/" + p_bid;
    }
    return url;    
}
Comm.getThreadUrl = function(p_fid,p_bid,p_tid) {
    var url = Comm.getBoardUrl(p_fid,p_bid);
    if (url == null) {}
    else if (!IsStringNullOrEmpty(p_tid)) {
        url += "/t" + p_tid;
    }     
    return url;    
}
Comm.getMessageUrl = function(p_fid,p_bid,p_tid,p_mid) {
    var url = Comm.getThreadUrl(p_fid,p_bid,p_tid);
    if (url == null) {}
    else if (!IsStringNullOrEmpty(p_mid)) {
        url += "/m" + p_mid;
    }
    return url;    
}
Comm.getForumId = function(p_fid) {
    return GetFirstNonBlankString(p_fid,_forumId);
}
Comm.getSidString = function() {
    //Append minutes since midnight 1/1/1970
    var currMins = GetCurrentMin();
    return _sid + "_" + currMins;
}
Comm.displayHelpCommLink = function() {
    var el = document.getElementById("hlpcomm");
    if (el) {
        if (Comm.exists()) el.style.display = 'inline';
        else el.style.display = 'none';
    }
}
Comm.navLinkHidden = true;
/***** End Community (Comm) Object *****/

/*******************************/
/***** Decision Tree Object *****/
/*******************************/
DT = function()
{
    this.initialize = function() {
    
        m_parentDiv = document.getElementById("topiccontents");
        createIframeElement();
    };
    this.isEnabled = function() {
        return (_useDt && browserSupportsDt());
    };
    this.hide = function() {
        if (this.isEnabled) {
            try {
                m_iframeElement = m_parentDiv.removeChild(m_iframeElement);
            } catch (e){}
            Print.show();
        }
    };
    this.show = function(bHist,loc) {
        if (this.isVisible()) { return false; }
        while (m_parentDiv.hasChildNodes())
        {
            var node = m_parentDiv.removeChild(m_parentDiv.lastChild);
        }
        m_parentDiv.appendChild(m_iframeElement);
        FB.reset();
        FB.hideRating();
        Print.hide();
        if (bHist) TH.addDecisionTree();
        MapLog.InstantAnswer(loc);//Omniture
        SizeContents();
        return false;
    };
    this.isVisible = function() {
        if (this.isEnabled()) {
            for (var i=0; i<m_parentDiv.childNodes.length; i++) {
                if (m_iframeElement && m_parentDiv.childNodes[i] == m_iframeElement) { return true; }
            }
        }
        return false;
    };
    this.showLink = function() {
        var disp = (this.isEnabled()) ? '' : 'none';
        document.getElementById('dtnavlink').style.display = disp;
        document.getElementById('dtnavsubtext').style.display = disp;
    }
    this.enableReturnLink = function() {
        m_returnLinkEnabled = true;
    };
    this.disableReturnLink = function() {
        m_returnLinkEnabled = false;
    };
    this.returnLinkIsEnabled = function() {
        return m_returnLinkEnabled;
    };
    this.getReturnLink = function() {
        var returnLinkElement = document.createElement("div");
        var hrElem = document.createElement("hr");
        hrElem.id = "dtReturnLinkRule";
        hrElem.setAttribute("noShade","noShade");
        returnLinkElement.appendChild(hrElem);
        var heading = document.createElement("h5");
        heading.innerText = _dtRetHead;
        returnLinkElement.appendChild(heading);
        var link = document.createElement("span");
        link.innerHTML = FormatString("<a href='#' id='dtReturnLink' onclick='DecisionTree.show(true,MapLog.clickLocContSup);'>{1}</a></p>", _dtRetHead, _dtRetText);
        returnLinkElement.appendChild(link);
        return returnLinkElement;
    };
    function createIframeElement()
    {
        var iframeId = "dtIFrame";
        var url = encodeURIComponent(location.protocol + "//" + location.host + "/" + _dtMessengerUrl);
        
        m_iframeElement = document.createElement("iframe");
        m_iframeElement.src = FormatString(_dtUrl, url, Proj.getCurrentProject(), _mkt, _query); 
        m_iframeElement.id = iframeId;
        m_iframeElement.setAttribute("frameBorder", 0);
    }
    
    function browserSupportsDt() {
        if (IsIE6Plus() || IsFireFox()) { 
            return true; 
        }
        return false;
    }
    var m_returnLinkEnabled = false;
    var m_parentDiv = null;
    var m_iframeElement = null;
}
var DecisionTree = new DT();

/***** End Decision Tree (DT) Object *****/

/*******************************/
/***** FAQ Object *****/
/*******************************/
function FAQ() {}
FAQ.showFAQ = function() {
    if (FAQ.cache == null) {
        FAQ.getFAQ();
    } else {
        FAQ.display(FAQ.cache);
    }
    return false;
}
FAQ.getFAQ = function() {
    var url = Svc.getHelpUrl("","keyword",_faqKey,v4);
    Req.makeRequest(url,FAQ.busyReq,"tlhelplinks",FAQ.successCallback,FAQ.errorCallback,"");
}
FAQ.successCallback = function(p_req,p_pass) {
    var contents = "";
    var aFaq = Svc.getResultsArray(p_req.responseText);
    if (aFaq.length == 1) {//search error; return error text
        contents = aFaq[0];
    } else {//there are FAQ(s)
        contents += "<ul>";
        for (i = 0; i < aFaq.length; i += 2) {
            contents += TL.createHelpLink(aFaq[i],aFaq[i+1],"faq"+i);
        }
        contents += "</ul>";
        FAQ.cache = contents;
        if (aFaq.length == 2) HT.show(aFaq[0]);//single FAQ, so display the topic
    }
    FAQ.display(contents);
}
FAQ.errorCallback = function(p_req,p_pass) {
    FAQ.display(Req.getErrorHtml(p_req));
}

FAQ.display = function(p_Faq) {
    MapLog.FaqListPresented();//Omniture
    CommTL.hide();//hide any community search results
    TL.display(p_Faq,_tlFaqHead);
    FAQ.hideNavLink();
    TOC.showNavLink();
    SizeContents();
}
FAQ.hideNavLink = function() {
    document.getElementById('faqnav').style.display = 'none';
}
FAQ.showNavLink = function() {
    document.getElementById('faqnav').style.display = '';
}
FAQ.clearCache = function() {
    FAQ.cache = null;
}
FAQ.busyReq = false;
FAQ.cache = null;
/***** End FAQ Object *****/

/*******************************/
/***** Feedback (FB) Object *****/
/*******************************/
function FB() {}
FB.submitRating = function(r) {
    FB.currentRating = r;
    if (TH.isTopic()){
        MapLog.RatingsSubmitted(TH.getCurrentTopic(),TH.getCurrentProject(),r,1,"");//omniture
    }
    else{
        MapLog.RatingsSubmitted(TH.getCurrentThreadId(),TH.getCurrentThreadProject(),r,0,CommTL.clickLocation);//omniture
    }
    FB.showVerbatim();
    return false;
}
FB.showRating = function() {
    if (FB.ratingHidden && FB.thanksHidden && Comm.navLinkHidden) {
        document.getElementById('topicrating').style.display = 'inline';
        FB.setButtonStyle();
        FB.ratingHidden = false;
    }
}
FB.hideRating = function() {
    if (!FB.ratingHidden) {
        document.getElementById('topicrating').style.display = 'none';
        document.getElementById('ratebuttons').style.display = 'none';
        FB.ratingHidden = true;
    }
}
FB.showThanks = function() {
    if (FB.thanksHidden && FB.ratingHidden && Comm.navLinkHidden) {
        document.getElementById('fdbckthanks').style.display = 'inline';
        FB.thanksHidden = false;
    }
}
FB.hideThanks = function() {
    if (!FB.thanksHidden) {
        document.getElementById('fdbckthanks').style.display = 'none';
        FB.thanksHidden = true;
    }
}
FB.setButtonStyle = function() {
    // Set visibility of text-style button or smiley-style image.
    document.getElementById('rateimg').style.display = (_fdbckButtonStyle == "text") ? 'none' : 'inline';
    document.getElementById('ratebuttons').style.display = (_fdbckButtonStyle == "text") ? 'inline' : 'none';
    // Set visibility of Smiley-style image on the verbatim text input.
    FB.verbatimImageHidden = (_fdbckButtonStyle == "text");
    SizeContents();
}
FB.hideVerbatim = function() {
    document.getElementById('topicfdbck').style.display = 'none';
    FB.verbatimHidden = true;
    FB.clearVerbatim();
    TF.show();
    FB.hideRating();
    FB.showThanks();
    SizeContents();
    return false;
}
FB.showVerbatim = function() {
    TF.hide();
    if (FB.verbatimImageHidden) {
        document.getElementById('fdbckimg').style.display = 'none';
    } else {
        document.getElementById('fdbckimg').style.display = 'inline';
        document.getElementById('fdbckimg').src = FB.getImg(FB.currentRating,true);
    }
    document.getElementById('topicfdbck').style.display = '';
    FB.setVerbatimText();
    FB.verbatimHidden = false;
    SizeContents();
    document.getElementById('fdbckarea').focus();
}
FB.setVerbatimText = function() {
    document.getElementById('fdbckheadpos').style.display = (FB.currentRating == 2) ? 'inline' : 'none';
    document.getElementById('fdbckheadneg').style.display = (FB.currentRating == 2) ? 'none' : 'inline';
}
FB.clearVerbatim = function() {
    document.getElementById('fdbckarea').value = '';
}
FB.reset = function() {
    Comm.hideNavLink();
    FB.hideVerbatim();
    FB.hideThanks();
    FB.showRating();
}
FB.submitVerbatim = function() {
    var feed = NormalizeWhitespace(document.getElementById('fdbckarea').value);
    if (feed.length > 0){
        if (TH.isTopic()){
            MapLog.FeedbackSubmitted(TH.getCurrentTopic(),TH.getCurrentProject(),feed,FB.currentRating,1,"");//Omniture	
        }
        else{
            MapLog.FeedbackSubmitted(TH.getCurrentThreadId(),TH.getCurrentThreadProject(),feed,FB.currentRating,0,CommTL.clickLocation);//Omniture	
        }
    }
        FB.hideVerbatim();
    return false;
}
FB.getImg = function(p_idx,p_bFocus) {
    if (p_bFocus) p_idx += 3;
    return _appPath + _neutralPath + FB.images[p_idx];
}
FB.evalKeyUp = function(p_el) {
    var chars = p_el.value;
    if (chars.length > 900) p_el.value = chars.substring(0,900);
}
FB.currentRating;
FB.images = new Array('rate0dk.gif','rate1dk.gif','rate2dk.gif','rate0lt.gif','rate1lt.gif','rate2lt.gif');
FB.ratingHidden = false;
FB.thanksHidden = false;
FB.verbatimHidden = true;
FB.verbatimImageHidden = true;
FB.colAdjust = 7.6;
/***** End Feedback (FB) Object *****/

/***********************************/
/***** UserHistory (UH) Object *****/
/***********************************/
function UH() {}
UH.add = function(p_searchType, p_query) {
    if (p_query != UH.previous) {
        UH.previous = p_query;
        UH.aQueries.push(p_searchType + ":" + EncodeQuery(p_query));
    }
}

UH.getSearchList = function(p_count) {
    var history = "";
    for (var i = (UH.aQueries.length - 1); i > (UH.aQueries.length - 1) - p_count; i--) {
        history += UH.aQueries[i] + ",";
        if (i == 0) break;
    }
    return history;
}
UH.aQueries = new Array();//search query
UH.previous = "";
/***** End SearchQuery (UH) Object *****/

/**************************/
/***** ContactUs  ***********/
/**************************/
function ContactUs() {}

ContactUs.Utils = 
{
    setContactUsCookie:function() 
    {  
        var cookieVal = "";
        cookieVal += "searches=" + UH.getSearchList(20);
        cookieVal += ";project=" + ((Proj.getCurrentProject() != null) ? Proj.getCurrentProject() : "");
        cookieVal += ";sessionid=" + ((_sid != null) ? _sid : "");
        cookieVal += ";market=" + ((_mkt != null) ? _mkt : "");
        // ContextMetadata used for diagnostics.
        cookieVal += ";featurearea=" + ContactUs.featureArea;
        cookieVal += ";errorsource=" + ContactUs.errorSource;
        cookieVal += ";errorid=" + ContactUs.errorId;
        cookieVal += ";keywords=" + ContactUs.keywords;
        var exp = new Date(); 
        exp.setTime(exp.getTime() + (5*60*1000));
        Util.CookieHelper.setCookie("help.live.contactus", cookieVal, exp, "/");
    },
    
    processKeywords:function() 
    {
        var errorIdPos = -1;
        var firstMatch = true;
        var errorIdPattern = /^0[x|X][0-9a-fA-F]{8}$/;  // Example: 0x12345678
        var extraSpacesPattern = /\s+/g;
        var keywordsReversed = "";
        // Example keywords: "noitavitca rorretropssap 00884008x0 ignoreme ignoreme"
        ContactUs.keywords = TrimString(DecodeQuery(ContactUs.keywords).replace(extraSpacesPattern, ' ')); 
        var words = ContactUs.keywords.split(' ');
        for (var i = 0; i < words.length; i++) {
            words[i] = ReverseChars(words[i]);
            keywordsReversed += words[i];
            if (i < (words.length - 1)) {
                keywordsReversed += " ";
            }
            var idFound = errorIdPattern.test(words[i]);
            if (idFound && firstMatch) {
                errorIdPos = i;
                ContactUs.errorId = words[i];
                firstMatch = false;
            }
        }
        if (words.length >= 1  && errorIdPos != 0)
            ContactUs.featureArea = words[0];
        if (words.length >= 2 && errorIdPos != 1)
            ContactUs.errorSource = words[1];
        ContactUs.keywords = keywordsReversed;
    }
};

ContactUs.featureArea = "";
ContactUs.errorSource = "";
ContactUs.errorId = "";
ContactUs.keywords = "";
/***** End ContactUs *****/

/*********************************/
/***** HelpTopic (HT) Object *****/
/*********************************/
function HT() {}
HT.show = function(p_topic) {
    HT.load(p_topic,null,true,true,''); //get the topic content and display it
}
HT.load = function(p_topic,p_proj,p_bHist,p_bFoot,p_clickLoc) {
    //p_proj is non-null if called from TopicHistory
    var proj = (p_proj != null && p_proj != "") ? p_proj : Proj.getCurrentProject();
    var url = Svc.getHelpUrl(proj,"topic",p_topic,"");
    var pass = p_topic + "," + proj + "," + p_bHist + "," + p_bFoot + "," + p_clickLoc;
    Req.makeRequest(url,HT.busyReq,"topiccontents",HT.successCallback,HT.errorCallback,pass);
}
HT.successCallback = function(p_req,p_pass) {
    var params = p_pass.split(",");
    var topic = params[0];
    var proj = params[1];
    var bHist = (params[2] == "true");
    var bFoot = (params[3] == "true");
    var clickLoc = params[4];
    FB.reset();
    if (bFoot) {TF.show();} else {TF.hide();}
    if (bHist) TH.addTopic(topic);
    HT.display(p_req.responseText,topic,false);
    if (topic == _moreHelpPage) MapLog.GetMoreHelp(proj);//Omniture
    else MapLog.SelfCareArticleViewed(topic,proj,clickLoc);//Omniture
}
HT.errorCallback = function(p_req,p_pass) {
    var params = p_pass.split(",");
    var topic = params[0];
    var proj = params[1];
    HT.display(Req.getErrorHtml(p_req),topic,true);
    MapLog.SelfCareArticleError(topic,proj);//Omniture
}
HT.topicDisplayedOnLoad = function(t) {
    var proj = null;
    FB.reset();
    
    if (t.toLowerCase() != _welcomePage) {
        TF.show();
        TH.addTopic(t);
    } else {
        TF.hide();
    }
    
    topicOnLoad();
    HT.setCurrent(t);
    MapLog.SelfCareArticleViewed(t,proj);//Omniture
}


HT.display = function(p_html,p_topic,p_error) {
    if (p_error) {
        if (p_topic.toLowerCase() != _welcomePage) HT.showWelcome();
        else document.getElementById("topiccontents").innerHTML = "";
    } else {
        var tc = document.getElementById("topiccontents");
        tc.innerHTML = p_html;
        if (DecisionTree.isEnabled()) {
            DecisionTree.hide();
            if (DecisionTree.returnLinkIsEnabled()) {
                tc.appendChild(DecisionTree.getReturnLink());
                DecisionTree.disableReturnLink();
            }
        }
        topicOnLoad();
        HT.setCurrent(p_topic);
    }
}
HT.showWelcome = function() {
    HT.load(_welcomePage,null,false,false,'');
    return false;
}
HT.showMoreHelp = function() {
    HT.load(_moreHelpPage,null,true,false,'');
    return false;
}
HT.showCommunityPage = function() {
    HT.load(_helpCommunityPage,null,true,false,'');
    return false;
}
HT.getCurrentTopicProject = function() {
    if (HT.current == _welcomePage) return Proj.getCurrentProject();
    else return TH.getCurrentProject();
}
HT.setCurrent = function(p_name) {
    HT.previous = HT.current;
    HT.current = p_name;
}
HT.busyReq = false;
HT.current = "";
HT.previous = "";
/***** End HelpTopic (HT) Object *****/

/**************************************/
/***** CommunityTopic (CT) Object *****/
/**************************************/
function CT() {}
//tid=threadid,fid=forumid,bid=boardid
CT.load = function(p_prj,p_tid,p_fid,p_bid,p_bHist,p_loc) {
    var id = p_bid + ":" + p_tid;
    var url = Svc.getHelpUrl(p_prj,"cmtythread",id,"");
    var pass = p_tid + "," + p_fid + "," + p_bid + "," + p_prj + "," + p_bHist + "," + p_loc;
    Req.makeRequest(url,CT.busyReq,"topiccontents",CT.successCallback,CT.errorCallback,pass);
}
CT.successCallback = function(p_req,p_pass) {
    var params = p_pass.split(",");
    var tid = params[0];
    var fid = params[1];
    var bid = params[2];
    var prj = params[3];
    var bHist = (params[4] == "true");
    var p_loc = params[5];
    MapLog.CommunityThreadViewed(tid,fid,bid,p_loc);//Omniture
    CT.render(p_req.responseText,fid,bid,tid);
    FB.reset();
    TF.show();
    if (bHist) TH.addThread(tid,fid,bid,prj);//add thread to history
    HT.setCurrent(tid);
}
CT.errorCallback = function(p_req,p_pass) {
    //BUGBUG? Add Omniture logging for community thread view error
    //var params = p_pass.split(",");
    //var tid = params[0];
    //var fid = params[1];
    //var bid = params[2];
    //var prj = params[3];
    //MapLog.CommunityThreadViewed(tid,fid,bid);//Perhaps indicate "error" in one of the params passed
    CT.display(Req.getErrorHtml(p_req),"","");
}
CT.render = function(p_json,p_fid,p_bid,p_tid) {
    p_json = CT.scrubJson(p_json);
    var arr = eval(p_json);
    var html = CT.createTitle(arr[0],p_fid,p_bid,p_tid);
    for (var i = 1; i < arr.length; i++) {
        html += CT.createMessage(arr[i],p_fid,p_bid,p_tid);
        if (i < arr.length - 1) html += CT.createRule();
    }
    CT.display(html,p_tid);
}
CT.scrubJson = function(p_s) {
    p_s = p_s.replace(/[\r\f\s]/g," ");//carriage return, form feed, white space
    p_s = p_s.replace(/\n{2,}/g,"<p></p>");//two or more consecutive newline
    p_s = p_s.replace(/\n/g,"<br/>");//single newline
    return p_s;
}
CT.breakLongCharSequences = function(p_s) {
    var reg = /\S{27}/g;//non-blank chars in long sequence
    p_s = p_s.replace(reg,"$& ");//insert space after long char sequences
    return p_s;
}
CT.createTitle = function(p_t,p_fid,p_bid,p_tid) {
    var ttl = CT.breakLongCharSequences(p_t.ttl);
    var commurl = Comm.getUrl(p_fid,p_bid,p_tid,null);
    var html = "<h4 id='cmtythreadttl'><a id='cttl' href='" + commurl + "'"
            + " onclick=\"return Comm.goToSiteUrl('" + commurl + "','" + p_fid + "','" + p_bid + "','" + p_tid + "')\">" + ttl + "</a></h4>";
    return html;
}
CT.createRule = function() {
    return "<hr size='1' align='left' class='cmtymsgrule'/>";
}
CT.createMessage = function(p_m,p_fid,p_bid,p_tid) {
    //p_m.id,p_m.dn,p_m.tc,p_m.an,p_m.bd
    var html = (p_m.an.toLowerCase() == "true") ? "<div class='cmtymsgba'>" : "<div class='cmtymsg'>";
    //TODO: English strings to be localized
    var commurl = Comm.getUrl(p_fid,p_bid,p_tid,p_m.id);
    html +=	 "<div class='cmtymsghead'><a class='cmtymsgheadlink' href='" + commurl + "'"
            + " onclick=\"return Comm.goToSiteUrl('" + commurl + "','" + p_fid + "','" + p_bid + "','" + p_tid + "')\">"
            + "Posted by " + p_m.dn + " on " + CT.convertTime(p_m.tc)
            + "</a></div><div class='cmtymsgbody'>" + CT.breakLongCharSequences(p_m.bd) + "</div></div>";
    return html;
}
CT.display = function(p_html,p_tid) {
    _threadId = p_tid;
    document.getElementById("topiccontents").innerHTML = p_html;
    DecisionTree.hide();
}
CT.convertTime = function(p_tc) {
    //convert UTC to local and change format
    //assumes input "mo/dy/year hr:mn:sc XM"
    var aTC = p_tc.split(" ");
    if (aTC.length != 3) return p_tc + " UTC";
    var aDate = aTC[0].split("/");
    if (aDate.length != 3) return p_tc + " UTC";
    var aTime = aTC[1].split(":");
    if (aTime.length < 2) return p_tc + " UTC";
    var ampm = aTC[2].toUpperCase();

    var year = parseInt(aDate[2]);
    var month = parseInt(aDate[0]);
    var day = parseInt(aDate[1]);
    var hour = parseInt(aTime[0]);
    if (hour == 12 && ampm == "AM") hour = 0;
    else if (ampm == "PM" && hour != 12) hour += 12;
    var minute = parseInt(aTime[1]);

    var utcDate = new Date(Date.UTC(year,month-1,day,hour,minute));

    minute = utcDate.getMinutes() + "";
    minute = (minute.length == 1) ? "0" + minute : minute;
    p_tc = (utcDate.getMonth() + 1) + "-" + utcDate.getDate() + "-" + utcDate.getFullYear() 
            + " " + utcDate.getHours() + ":" + minute;
    return p_tc;
}
CT.busyReq = false;
/***** End CommunityTopic (CT) Object *****/

/*******************************/
/***** Print Object *****/
/*******************************/
function Print() {}
Print.show = function() {
    if (Print.hidden) {
        document.getElementById("print").style.display = "";
        Print.hidden = false;
    }
}
Print.hide = function() {
    if (!Print.hidden) {
        document.getElementById("print").style.display = "none";
        Print.hidden = true;
    }
}
Print.print = function() {
    if (document.images){//disable omniture log image
        var imgs = document.images;
        if (typeof(imgs) == "object" && imgs != null){
            for (var i = imgs.length - 1; i >= 0; i--){
                if (imgs[i].src.indexOf(_omniImgKey) != -1){
                    imgs[i].src = _appPath+_cgifUrlPath;
                    break;
                }
            }
        }
    }
    var wlicon = document.getElementById("wlicon");
    if (wlicon != null) wlicon.src = _appPath+_printHeadImg;//replace temp header img with correct img
    var idssimg = document.getElementById("idss");
    if (idssimg != null) idssimg.src = _appPath+_cgifUrlPath;//disable idss c.gif
    if(IsFireFox()) //Adjust height for FireFox to print all the pages
    {
        window.document.getElementById("topiccontents").style.height = 'auto';
    }
    window.print();//Print topic currently displayed
    //Omniture
    if (HT.current.toLowerCase() == _welcomePage)//welcome page not in history, so handle separately
        MapLog.SelfCareArticlePrinted(_welcomePage,Proj.getCurrentProject());
    else if (TH.isTopic())
        MapLog.SelfCareArticlePrinted(TH.getCurrentTopic(),TH.getCurrentProject(),"");
    else
        MapLog.CommunityThreadPrinted(TH.getCurrentThreadId(),TH.getCurrentThreadForum(),TH.getCurrentThreadBoard(),CommTL.clickLocation);
    return false;
}
Print.hidden = false;
/***** End Print Object *****/

/*******************************/
/***** Project (Proj) Object *****/
/*******************************/
function Proj() {}
Proj.getCurrentProject = function() {
    if (Proj.currentProject == null) {
        Proj.currentProject = Proj.getSelectedProject();
    }
    return Proj.currentProject;
}
Proj.getSelectedProject = function() {
    var prods = document.getElementById('projsel');
    return prods.options[prods.selectedIndex].value;
}
Proj.onChange = function() {
    Search.showDefaultText();
    Proj.currentProject = Proj.getSelectedProject();
    FAQ.clearCache();
    TOC.clearCache();
    Proj.getNewSettings();
}
Proj.respondToNewSettings = function() {
    Comm.displayHelpCommLink();
    DecisionTree.showLink();
    TH.initialize();
    Print.show();
    //overwritten if only one FAQ
    if (DecisionTree.isEnabled()) {
        DecisionTree.initialize();
        DecisionTree.show(true,null);
    } else {
        HT.showWelcome();
    }
    FAQ.getFAQ();
}
Proj.getNewSettings = function() {
    //use thinservice.aspx?market=<mkt>&project=<prj> to get project settings
    var url = Svc.getHelpUrl("","","","");
    Req.makeRequest(url,Proj.busyReq,"",Proj.successCallback,Proj.errorCallback,"");
}
Proj.successCallback = function(p_req,p_pass) {
    var params = p_req.responseText.split(",");
    _forumId = params[0];
    _boardId = params[1];
    _cuWinMode = params[2];
    _cuWriteCookie = params[3];
    _fdbckButtonStyle = params[4];
    _useDt = (params[5].toLowerCase() == "true");
    Proj.respondToNewSettings();
}
Proj.errorCallback = function(p_req,p_pass) {
    _forumId = "";
    _boardId = "";
    _cuWinMode = "";
    _cuWriteCookie = "";
    _useDt = false;
    Proj.respondToNewSettings();
}
Proj.currentProject = null;
Proj.busyReq = false;
/***** End Project (Proj) Object *****/



/*******************************/
/***** Request (Req) Object *****/
/*******************************/
function Req() {}
Req.makeRequest = function(p_url,p_busyReq,p_progId,p_successCallBack,p_errorCallBack,p_pass) {
    //p_url: the web service url
    //p_busyReq: is a request for this object currently in progress?
    //p_progId: element id where progress HTML should be shown
    //p_successCallBack: callback function for successful response
    //p_errorCallBack: callback function for erroneous response
    //p_pass: string of params to pass to callback functions
    if (p_busyReq) return;
    var req = Req.getRequest();
    if (req != null) {
        p_busyReq = true;
        Req.showProgress(p_progId);
        req.onreadystatechange = function() {
            if (req.readyState == 4) {
                p_busyReq = false;
                window.clearTimeout(toId);
                if (req.status == 200) {
                    p_successCallBack(req,p_pass);
                } else {
                    p_errorCallBack(req,p_pass);
                }
            }
        }
        req.open("GET", p_url, true);
        req.send(null);
        var toId = window.setTimeout( function() {if (p_busyReq) req.abort();}, Req.timeout );
    }
}
Req.getRequest = function() {
    var xmlHttp;
    try { xmlHttp = new ActiveXObject("MSXML2.XMLHTTP"); return xmlHttp; } catch (e) {}
    try { xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); return xmlHttp; } catch (e) {}
    try { xmlHttp = new XMLHttpRequest(); return xmlHttp; } catch(e) {}
    return null;
}
Req.showProgress = function(p_id) {
    if (p_id != "") document.getElementById(p_id).innerHTML = Req.getProgressHtml();
}
Req.getProgressHtml = function() {
    return "<p class='progress'><img src='"+_appPath+_neutralPath+"hig_progcircle_animated.gif' align='middle' width='16' height='16' alt='" + _progressText + "'/>&nbsp;" + _progressText + "</p>";
}
Req.getErrorHtml = function(p_req) {
    //TODO: implement accepted way to handle request error
    return "<p>" + "(" + p_req.status + ") " + p_req.statusText + "</p>"
}
Req.timeout = 20000;
/***** End Request (Req) Object *****/

/*******************************/
/***** Search Object *****/
/*******************************/
function Search() {}
Search.doSearch = function() {
    //Submit request for MAP help search with user-supplied query terms.
    var oInput = document.getElementById('helpquery');
    if ( oInput ) {
        var q = oInput.value;
        if (q != _queryDefault) { //ensure no search for default text
            if ( q.length > 0 ) {
                UH.add("search", q); //add to search history
            }
            q = ScrubQuery(q);
            if ( q.length > 0 ) {//the query is not empty, so get the results
                _query = q;//cache the encoded version of the query
                Search.getResults('search',q);
                if (Comm.exists()) CommSearch.getResults(q);
            } else {// the query is empty; return focus to the input box
                oInput.focus();
            }
        }
    }
    return false;
}
Search.doSearchViaEnter = function(p_ev)  {
    // Submit the Help Search when the user presses the Enter key
    // while focus is in the Help Search input box.
    p_ev = (p_ev) ? p_ev : event;
    var target = (p_ev.target) ? p_ev.target : p_ev.srcElement;
    var charCode = (p_ev.charCode) ? p_ev.charCode : ((p_ev.which) ? p_ev.which : p_ev.keyCode);
    if ((charCode == 13 || charCode == 3) && target.id =='helpquery'){Search.doSearch();}
    return false;
}
Search.getResults = function(p_qt,p_q) {
    Search.clearCache();
    var url = Svc.getHelpUrl("",p_qt,p_q,v4);
    var pass = p_qt + "," + p_q;
    ++Search.activeSearches;
    Req.makeRequest(url,Search.busyReq,"tlhelplinks",Search.successCallback,Search.errorCallback,pass);
}
Search.successCallback = function(p_req,p_pass) {
    --Search.activeSearches;
    var params = p_pass.split(",");
    var qt = params[0];
    var q = params[1];
    var aResults = Svc.getResultsArray(p_req.responseText);
    var len = aResults.length;
    if (len == 1) { // = error with search
        if (qt == "keyword") {
            //Show FAQ instead
            FAQ.showFAQ();
            if (DecisionTree.isEnabled()){
                DecisionTree.show(true,null);
            } else {
                HT.showWelcome();
            }
        } else {
            //there was a search error; return the error text
            MapLog.SearchExecuted(qt,q,"",MapLog.mapSearch);//Omniture
            Search.displayResults("<p>" + aResults[0] + "</p>",qt);
        }
    } else {
        //there are search results
        var count = len/2;
        Search.aNames = new Array(count);
        Search.aTitles = new Array(count);
        var idx = 0;
        for (i = 0; i < len; i += 2) {
            Search.aNames[idx] = aResults[i];
            Search.aTitles[idx] = aResults[i+1];
            idx++;
        }
        MapLog.SearchExecuted(qt,q,count,MapLog.mapSearch);//Omniture
        Search.renderResults(qt);
    }
}
Search.errorCallback = function(p_req,p_pass) {
    --Search.activeSearches;
    var params = p_pass.split(",");
    var qt = params[0];
    var q = params[1];
    MapLog.SearchExecuted(qt,q,"",MapLog.mapSearch);//Omniture
    Search.displayResults(Req.getErrorHtml(p_req),qt);
}
Search.renderResults = function(p_qt) {
    //TODO: Create function Search.isError() to make this clearer
    if (Search.isError()) {
        if (p_qt == "keyword") {
            //zero hits for keyword search
            FAQ.showFAQ();
        } else {
            //there was a search error or zero hits for user search
            //so display the error text that is in the title element
            Search.displayResults(Search.aTitles[0],p_qt);
        }
    } else {
        //there are search results
        Search.displayResults(Search.createLinks(0,p_qt),p_qt);
        if (p_qt != "keyword") Search.handlePossibleSingleResult();
    }
}
Search.isError = function() {
    return (Search.getResultsCount() == 1 && Search.aNames[0] == '');
}
Search.handlePossibleSingleResult = function() { 	//Only called if query type is search
    if (Search.activeSearches == 0)
    {
        //all search have finished so we can see if any have single results
        var helpResultsCount = Search.getResultsCount();
        var commResultsCount = CommSearch.getResultsCount();
        if (helpResultsCount == 1 && commResultsCount == 0)
        {
            //single help result and zero community results so show the help topic
            HT.show(Search.aNames[0]);
        }
        else if (helpResultsCount == 0 && commResultsCount == 1)
        {
            //single community result and zero help results so show the community thread
            CT.load(Proj.getCurrentProject(),CommSearch.aThreadIds[0],_forumId,CommSearch.aBoardIds[0],true,CommTL.clickLocation);
        }
    }
}	
Search.createLinks = function(p_start,p_qt) {
    var html = "<ul>";
    var max;
    var resultsCount = Search.getResultsCount();
    if (!Comm.exists()) {
        max = resultsCount;
    } else {
        max = (p_start == 0) ? _srchDispInc : resultsCount;
        max = (max > resultsCount) ? resultsCount : max;
    }
    for (var i = 0; i < max; i++) {
        html += TL.createHelpLink(Search.aNames[i],Search.aTitles[i],"sr"+i);
    }
    html += "</ul>";
    Search.helpLinks = html;//cache the topic links
    if (resultsCount > max) html += Search.createMoreLink(max,p_qt);//user can chose to view more
    return html;
}
Search.createMoreLink = function(p_start,p_qt) {
    return "<div id='viewmorehelp'><a id='vmh' href='#sml' onclick='Search.viewMore(" + p_start + ",\"" + encodeURIComponent(p_qt) + "\")'>" + _viewMoreText + "</a></div>";
}
Search.displayResults = function(p_html,p_qt) {
    var num = Search.getResultsCount();
    var head = _tlHelpHead + " (" + num + ")";
    if (p_qt == "keyword") {
        if (num == 1) {
            HT.show(Search.aNames[0]);
            FAQ.showFAQ();
        }
        else {
        
            // Relavent Community Search within MAP
            // targeted keyword search can contain nonsense keywords to load specific articles
            // after MAP search results have been returned, get the title of the first MAP article
            // and use it for community search.
            qTitle=Search.aTitles[0];
            if (Comm.exists()) CommSearch.getResults(qTitle, p_qt);
            
            if (num == 0 && DecisionTree.isEnabled()) {
                //Show the DT when no results are found & qt == keyword
                DecisionTree.show(true,null);
            } else {
                HT.showWelcome();
            }
            TL.display(p_html,head);
            
            FAQ.showNavLink();
        }
    }
    else { //Type = "search"
        TL.display(p_html,head);
        FAQ.showNavLink();
        if (TH.count()==0)
        {
            //Show the welcome page only if this is the first call to help
            HT.showWelcome();
        }

    }
    TOC.showNavLink()
    SizeContents();
}
Search.viewMore = function(p_start,p_qt) {
    Search.displayResults(Search.createLinks(p_start,p_qt),p_qt);
}
Search.focus = function(oInput) {
    var val = oInput.value;
    if (val == _queryDefault) oInput.value = '';//remove the default text if it is present
    oInput.select();
}
Search.blur = function(oInput) {
    var val = oInput.value;
    if (val == null || val.length == 0) oInput.value = _queryDefault;
}
Search.showDefaultText = function() {
    document.getElementById('helpquery').value = _queryDefault;
}
Search.clearCache = function() {
    Search.aNames = null;
    Search.aTitles = null;
    Search.helpLinks = "";
}
Search.getResultsCount = function() {
    return (Search.aNames != null) ? Search.aNames.length : 0;
}
Search.busyReq = false;
Search.aNames = null;
Search.aTitles = null;
Search.helpLinks = "";
Search.activeSearches = 0;
/***** End Search Object *****/

/*******************************/
/***** Community Search Object *****/
/*******************************/
function CommSearch() {}
CommSearch.getResults = function(p_q, p_qt) {
    CommSearch.clearCache();
    var url = Svc.getHelpUrl("","cmtysearch",p_q,"");
    var pass = p_q + ',' + p_qt;
    ++Search.activeSearches;
    Req.makeRequest(url,CommSearch.busyReq,"tlcommlinks",CommSearch.successCallback,CommSearch.errorCallback,pass);
}
CommSearch.successCallback = function(p_req,p_pass) {
    --Search.activeSearches;
    var params = p_pass.split(",");
    var q = params[0];
    var qt = params[1];;
    var aResults = Svc.getResultsArray(p_req.responseText);
    var len = aResults.length;
    CommSearch.count = 0;
    if (len == 1) {
        //there was a search error; return the error text
        CommSearch.displayResults("<p>" + aResults[0] + "</p>",qt);
    } else { //TODO verify len >=3 and mod(len,3) == 0
        //there are search results
        //"tid","ttl","tid","ttl",...
        //"bid,"tid","ttl","bid,"tid","ttl",...
        var count = len/3;
        CommSearch.count = count;
        CommSearch.aBoardIds = new Array(count);
        CommSearch.aThreadIds = new Array(count);
        CommSearch.aTitles = new Array(count);
        var idx = 0;
        for (i = 0; i < len; i += 3) {
            CommSearch.aBoardIds[idx] = aResults[i];
            CommSearch.aThreadIds[idx] = aResults[i+1];
            CommSearch.aTitles[idx] = aResults[i+2];
            idx++;
        }
        CommSearch.displayResults(CommSearch.createLinks(0,qt),qt);
    }
//TODO: else to handle error
    // log all community searches
    CommSearch.qt = qt;
    CommSearch.q = q;
    window.setTimeout("MapLog.SearchExecuted(CommSearch.qt,CommSearch.q,CommSearch.count,MapLog.commSearch)",CommSearch.CommSearchLogTimeout);//Omniture
}
CommSearch.errorCallback = function(p_req,p_pass) {
    --Search.activeSearches;
    var params = p_pass.split(",");
    var q = params[0];
    var qt = params[1];
    MapLog.SearchExecuted(qt,q,"",MapLog.commSearch);//Omniture
    CommSearch.displayResults(Req.getErrorHtml(p_req),qt);
}
CommSearch.createLinks = function(p_start,p_qt) {
    var html = "<ul>";
    var max;
    var resultsCount = CommSearch.getResultsCount()
    max = (p_start == 0) ? _srchDispInc : resultsCount;
    max = (max > resultsCount) ? resultsCount : max;
    for (var i = 0; i < max; i++) {
        html += CommTL.createThreadLink(CommSearch.aBoardIds[i],CommSearch.aThreadIds[i],CommSearch.aTitles[i]);
    }
    html += "</ul>";
    CommSearch.Links = html;//cache the topic links
    if (resultsCount > max) html += CommSearch.createMoreLink(max,p_qt);//user can chose to view more
    return html;
}
CommSearch.createMoreLink = function(p_start,p_qt) {
    return "<div id='viewmorecomm'><a id='vmt' href='#cml' onclick='CommSearch.viewMore(" + p_start + ",\"" + encodeURIComponent(p_qt) + "\")'>" + _viewMoreText + "</a><div>";
}
CommSearch.displayResults = function(p_html, p_qt) {
    var num = CommSearch.getResultsCount();
    var head = _tlCommHead + " (" + num + ")";
    CommTL.clickLocation  = '0'; // ominture set the click location set initial value
    if (p_qt == 'keyword') {
        // dont display zero results when its a targeted keyword search
        if (num > 0) {
            CommTL.clickLocation  = MapLog.clickLocCommunityKeyword; // ominture set the click location
            CommTL.display(p_html,head);
        }
    } else {
        // display the community results for user initiated searches
        CommTL.display(p_html,head);
    }

    if (p_qt != 'dtree') {
        //Don't overwrite the DT
        Search.handlePossibleSingleResult();
    } else {
        TL.hideDiv();
        FAQ.showNavLink();
        TOC.showNavLink();
    }
}
CommSearch.viewMore = function(p_start,p_qt) {
    CommSearch.displayResults(CommSearch.createLinks(p_start,p_qt),p_qt);
}
CommSearch.clearCache = function() {
    CommSearch.aBoardIds = null;
    CommSearch.aThreadIds = null;
    CommSearch.aTitles = null;
    CommSearch.Links = "";
}
CommSearch.getResultsCount = function() {
    return (CommSearch.aThreadIds != null) ? CommSearch.aThreadIds.length : 0;
}
CommSearch.CommSearchLogTimeout=5000;
CommSearch.qt = "";
CommSearch.q = "";
CommSearch.count = "";
CommSearch.busyReq = false;
CommSearch.aBoardIds = null;
CommSearch.aThreadIds = null;
CommSearch.aTitles = null;
CommSearch.Links = "";
/***** End Community Search Object *****/

/*******************************/
/***** Service (Svc) Object *****/
/*******************************/
function Svc() {}
Svc.getHelpUrl = function(p_prj,p_qt,p_q,p_f) {
    var prj = (p_prj.length > 0) ? p_prj : Proj.getCurrentProject();
    var url = _appPath + "/" + _thinSvc + "?project=" + prj + "&mkt=" + _mkt;
    if (p_qt.length > 0 && p_q.length > 0) {
        url += "&querytype=" + p_qt + "&query=" + p_q;
        if (p_f.length > 0) url += "&filter=" + p_f;
    }
    return url;
}
Svc.getResultsArray = function(p_str) {
    //parse search results (comma-delimited, double-quoted strings)
    var str = p_str.substring(1,p_str.length-1);
    return str.split('","');
}
/***** End Service (Svc) Object *****/

/*******************************/
/***** TOC Object *****/
/*******************************/
function TOC() {}
TOC.showTOC = function() {
    if (TOC.cache == null) {
        TOC.getTOC();
    } else {
        MapLog.TocListPresented(TOC.fileName,Proj.getCurrentProject(),"");//Omniture
        TOC.display(TOC.cache);
    }
    return false;
}
TOC.getTOC = function() {
    var url = Svc.getHelpUrl("","topic","toc.htm","");
    Req.makeRequest(url,TOC.busyReq,"tlhelplinks",TOC.successCallback,TOC.errorCallback,"");
}
TOC.successCallback = function(p_req,p_pass) {
    var contents = p_req.responseText;
    var idx = contents.indexOf("]");
    TOC.fileName = contents.substring(1,idx);//cache TOC file name
    contents = contents.substring(idx+1,contents.length);
    MapLog.TocListPresented(TOC.fileName,Proj.getCurrentProject(),"");//Omniture
    TOC.cache = contents;//cache TOC
    TOC.display(contents);
}
TOC.errorCallback = function(p_req,p_pass) {
    TOC.display(Req.getErrorHtml(p_req));
    MapLog.TocListPresented("",Proj.getCurrentProject(),"errorPage");//Omniture
}
TOC.display = function(p_toc) {
    CommTL.hide();//hide any community search results
    TL.display(p_toc,_tlTocHead);
    TOC.reopenBooks();
    TOC.hideNavLink();
    FAQ.showNavLink();
    SizeContents();
}
TOC.hideNavLink = function() {
    document.getElementById('tocnav').style.display = 'none';
}
TOC.showNavLink = function() {
    document.getElementById('tocnav').style.display = '';
}
TOC.reopenBooks = function() {
    if (TOC.openBooks != "") {
        var str = TOC.openBooks.substring(1,TOC.openBooks.length);
        var arr = str.split(",");
        for (var i = 0; i < arr.length; i++) {
            TOC.toggleBook(arr[i]);
        }
    }
}
TOC.toggleBook = function(p_bkid) {
    toggleElementDisplay(p_bkid,'block');//in wltopic.js
    TOC.toggleImg('I'+p_bkid,'c');
}
TOC.bookClick = function(p_bkid) {
    TOC.toggleBook(p_bkid);
    if (TOC.openBooks.indexOf(p_bkid) == -1) {//add book to cache
        TOC.openBooks += "," + p_bkid;
    } else {//remove book from cache
        var bkstr = "," + p_bkid;
        var idx = TOC.openBooks.indexOf(bkstr);
        var str1 = TOC.openBooks.substring(0,idx);
        var str2 = TOC.openBooks.substring(idx+bkstr.length,TOC.openBooks.length);
        TOC.openBooks = str1 + str2;
    }
}
TOC.toggleImg = function(p_id,p_ev) {
    var elem = document.getElementById(p_id);
    if (elem != null) {
        var src = elem.src;
        var srcRoot = "";
        var imgName = src;
        var imgNewName;
        var idx = src.lastIndexOf("/");
        if (idx > -1) {
            srcRoot = src.substring(0,idx+1);
            imgName = src.substring(idx+1,src.length);
        }
        imgName = imgName.substring(0,imgName.length - 4);
        switch (imgName) {
            case "glyph_expand_rest":
                if (p_ev == 'r') imgNewName = 'glyph_expand_hover';
                else if (p_ev == 't') imgNewName = 'glyph_expand_rest';
                else imgNewName = 'glyph_collapse_rest';
                break;
            case "glyph_expand_hover":
                if (p_ev == 't') imgNewName = 'glyph_expand_rest';
                else imgNewName = 'glyph_collapse_rest';
                break;
            case "glyph_collapse_rest":
                if (p_ev == 'r') imgNewName = 'glyph_collapse_hover';
                else if (p_ev == 't') imgNewName = 'glyph_collapse_rest';
                else imgNewName = 'glyph_expand_rest';
                break;
            case "glyph_collapse_hover":
                if (p_ev == 't') imgNewName = 'glyph_collapse_rest';
                else imgNewName = 'glyph_expand_rest';
                break;
        }
        elem.src = srcRoot + imgNewName + '.gif';
    }
}
TOC.clearCache = function() {
    TOC.fileName = "";
    TOC.cache = null;
    TOC.openBooks = "";
}
TOC.fileName = "";
TOC.busyReq = false;
TOC.cache = null;
TOC.openBooks = "";
/***** End TOC Object *****/

/*******************************/
/***** TopicFooter (TF) Object *****/
/*******************************/
function TF() {}
TF.show = function() {
    FB.setButtonStyle();
    document.getElementById('topicfooter').style.display = '';
}
TF.hide = function() {
    document.getElementById('topicfooter').style.display = 'none';
}
/***** End TopicFooter (TF) Object *****/

/*******************************/
/***** TopicHistory (TH) Object *****/
/*******************************/
//TODO: refactor to make differentiation of topic and thread clearer
function TH() {}
TH.next = function() {
    //Increment the TopicHistory array index by 1
    //and return the topic at the new array index
    var newIdx = (HT.current != _welcomePage) ? TH.idx + 1 : TH.idx;
    if (newIdx < TH.count()) {
        TH.idx = newIdx;
        TH.showControl(1); //show "previous" control
    }
    if (newIdx >= TH.count() - 1) {
        TH.hideControl(0); //hide "next" control
    }
    TH.showItem(1);
    return false;
}
TH.previous = function() {
    //Decrement the TopicHistory array index by 1
    //and display the topic at the new array index
    var newIdx = (HT.current != _welcomePage) ? TH.idx - 1 : TH.idx;
    if (newIdx >= 0) {
        TH.idx = newIdx;
        TH.showControl(0); //show "next" control
    }
    if (newIdx <= 0) {
        TH.hideControl(1); //hide "previous" control
    }
    TH.showItem(0);
    return false;
}
TH.showItem = function(p_link) {
    if (TH.isTopic()) {
        var topic = TH.getCurrentTopic();
        var project = TH.getCurrentProject();
        var bShowFoot = (topic.toLowerCase() == _welcomePage) ? false : true;
        HT.load(topic,project,false,bShowFoot,'');
    } else if (TH.isThread()){
        CT.load(TH.getCurrentThreadProject(),TH.getCurrentThreadId(),TH.getCurrentThreadForum(),TH.getCurrentThreadBoard(),false,CommTL.clickLocation);
    } else if (TH.isDT()) {
        DecisionTree.show(false,(p_link) ? MapLog.clickLocForward : MapLog.clickLocBack);
    } //no else case
}
TH.showControl = function(prev) {
    if (prev) { //show "previous" control
        document.getElementById('histprev').style.visibility = 'visible';
    } else { //show "next" control
        document.getElementById('histnext').style.visibility = 'visible';
    }
}
TH.hideControl = function(prev) {
    if (prev) { //hide "previous" control
        document.getElementById('histprev').style.visibility = 'hidden';
    } else { //hide "next" control
        document.getElementById('histnext').style.visibility = 'hidden';
    }
}
TH.addTopic = function(p_topic) {
    TH.add(1,p_topic,Proj.getCurrentProject());
    UH.add("topic", p_topic);
}
TH.addThread = function(p_tid,p_fid,p_bid,p_prj) {
    //TH.add(0,p_tid,p_fid + ":" + p_bid + ":" + p_prj);
    TH.add(0,p_tid,new TH.ThreadInfo(p_fid,p_bid,p_prj));
    UH.add("thread", p_tid);
}

TH.addDecisionTree = function() {
    TH.add(2,"dt",Proj.getCurrentProject());
    UH.add("dt", "");
}
TH.add = function(p_type,p_name,p_other) {
        p_name = p_name.toLowerCase();
    //If this topic is already in the history, then remove it so that it can be re-added at current index position.
    TH.removeDup(p_name);
    
    //Add the current topic info to the history arrays and point the index at this entry.
    if (TH.idx == TH.count() - 1) {//idx at end of array, so add to end
        TH.aType = TH.aType.concat(p_type);
        TH.aNames = TH.aNames.concat(p_name);
        TH.aOther = TH.aOther.concat(p_other);
        TH.idx = TH.count() - 1;//point idx at new entry
    } else {//idx in interior of array; remove items after idx
        //must create new, shorter arrays first with length idx + 1
        TH.idx = TH.idx + 1;
        TH.aType = TH.aType.slice(0,TH.idx);
        TH.aNames = TH.aNames.slice(0,TH.idx);
        TH.aOther = TH.aOther.slice(0,TH.idx);
        //add the new values to the last array idx
        TH.aType[TH.idx] = p_type;
        TH.aNames[TH.idx] = p_name;
        TH.aOther[TH.idx] = p_other;			
    }
    if (TH.idx > 0) TH.showControl(1); //show "previous" control
    TH.hideControl(0);//hide "next" control
}
TH.removeDup = function(p_name) {
    var end = TH.aNames.length - 1;
    for (var i = 0; i <= end; i++) {
        if (TH.aNames[i] == p_name) {//dup found
            for (var j = i; j <= end; j++) {
                if (j < end) {//move all entries back one index
                    TH.aNames[j] = TH.aNames[j+1];
                    TH.aType[j] = TH.aType[j+1];
                    TH.aOther[j] = TH.aOther[j+1];
                }
                else {//remove array entry at last index
                    TH.aNames = TH.aNames.slice(0,j);
                    TH.aType = TH.aType.slice(0,j);
                    TH.aOther = TH.aOther.slice(0,j);
                    TH.idx = j - 1;
                }
            }
            break;
        }
    }
}
TH.count = function() {
    return TH.aNames.length;
}
TH.getCurrentTopic = function() {
    return (TH.idx >= 0) ? TH.aNames[TH.idx] : ""; //the current topic name
}
TH.getCurrentProject = function() {
    return (TH.idx >= 0) ? TH.aOther[TH.idx] : ""; //the current project name
}
TH.getCurrentThreadId = function() {
    return (TH.idx >= 0) ? TH.aNames[TH.idx] : ""; //the current thread id
}
TH.getCurrentThreadProject = function() {
    if (TH.idx >= 0) { //get project from ThreadInfo object
        var ti = TH.aOther[TH.idx];
        return ti.prj;
    } else return "";
}
TH.getCurrentThreadForum = function() {
    if (TH.idx >= 0) { //get forumid from ThreadInfo object
        var ti = TH.aOther[TH.idx];
        return ti.fid;
    } else return "";
}
TH.getCurrentThreadBoard = function() {
    if (TH.idx >= 0) { //get boardid from ThreadInfo object
        var ti = TH.aOther[TH.idx];
        return ti.bid;
    } else return "";
}
TH.initialize = function() { 
    TH.aType = new Array();//1=topic; 0=community thread
    TH.aNames = new Array();//topic name or thread id
    TH.aOther = new Array();//topic project or ThreadInfo
    TH.idx = -1;
    TH.hideControl(0);
    TH.hideControl(1);
}
TH.isThread = function() {return (TH.idx >= 0 && TH.aType[TH.idx] == 0);}
TH.isTopic = function() {return (TH.idx >= 0 && TH.aType[TH.idx] == 1);}
TH.isDT = function() {return (TH.idx >= 0 && TH.aType[TH.idx] == 2);}
TH.aType;//1=topic; 0=community thread
TH.aNames;//topic name or thread id
TH.aOther;//topic project or ThreadInfo
TH.idx;
TH.ThreadInfo = function(p_fid,p_bid,p_prj) {
    this.fid = p_fid;
    this.bid = p_bid;
    this.prj = p_prj;
}
/***** End TopicHistory (TH) Object *****/


/**************************************/
/***** Help TopicList (TL) Object *****/
/**************************************/
function TL() {}
TL.display = function(p_html,p_head) {
    TL.showDiv();
    document.getElementById('tlhelphead').innerHTML = p_head;
    document.getElementById('tlhelplinks').innerHTML = p_html;
}
TL.createHelpLink = function(p_topic,p_title,p_href) {
    return "<li><a class='tlhelplink' href='#" + p_href + "' onclick=" + '"' + "return TL.clickLink('" + p_topic + "')" + '">' + p_title + "</a></li>";
}
TL.clickLink = function(p_topic) {
    HT.show(p_topic); //get the topic content and display it
    return false;
}
TL.hideDiv = function() {
    document.getElementById('tlhelp').style.display = 'none';
}
TL.showDiv = function() {
    document.getElementById('tlhelp').style.display = '';
}
/***** End Help TopicList (TL) Object *****/

/*******************************************/
/***** Community TopicList (TL) Object *****/
/*******************************************/
function CommTL() {}
CommTL.display = function(p_html,p_head) {
    document.getElementById('tlcomm').style.display = "";
    document.getElementById('tlcommhead').innerHTML = p_head;
    document.getElementById('tlcommlinks').innerHTML = p_html;
}
CommTL.createThreadLink = function(p_boardId,p_threadId,p_name) {
    return "<li><a class='tlcommlink' href='" 
            + Comm.getUrl(null,p_boardId,p_threadId,null) 
            + "' onclick=" + '"' 
            + "return CommTL.clickLink('" 
            + p_boardId 
            + "','" 
            + p_threadId 
            + "')" 
            + '">' 
            + CommTL.scrubTitle(p_name) 
            + "</a></li>";
}
CommTL.scrubTitle = function(p_s) {
    var reg = /\S{15}/g;//non-blank chars in long sequence
    p_s = p_s.replace(reg,"$& ");//insert space after long char sequences
    return p_s;
}
CommTL.clickLink = function(p_boardId,p_threadId) {
    CT.load(Proj.getCurrentProject(),p_threadId,_forumId,p_boardId,true,CommTL.clickLocation);//show the thread
    return false;
}
CommTL.hide = function() {
    document.getElementById('tlcomm').style.display = "none";
}

CommTL.clickLocation='0'; // omniture logging
/***** End TopicList (TL) Object *****/

//***********************************************************************************************
// CLASS:  Util.CookieHelper 
// Stolen from LiveControls and rebranded into our namespace to avoid collisions.
//***********************************************************************************************
function Util() {}

Util.CookieHelper = 
{
    getCookie:function(name) 
    {  
    
        function valueAt(offset) 
        {
            var endstr = document.cookie.indexOf (";", offset);
            if (endstr == -1)
            {
                endstr = document.cookie.length;
            }
            return unescape(document.cookie.substring(offset, endstr));
        }
        
        var arg = name + "=";  
        var alen = arg.length;  
        var clen = document.cookie.length;  
        var i = 0;  
        while (i < clen) 
        {
            var j = i + alen;    
            if (document.cookie.substring(i, j) == arg)
            {
                return valueAt(j);
            }
            i = document.cookie.indexOf(" ", i) + 1;    
            if (i == 0) 
            {
                break;
            }
        }  
        return null;
    },
    setCookie:function(name, value) 
    {  
        var expDays = 30;
        var exp = new Date(); 
        exp.setTime(exp.getTime() + (expDays*24*60*60*1000));

        var argv = Util.CookieHelper.setCookie.arguments;  
        var argc = Util.CookieHelper.setCookie.arguments.length;  
        var expires = (argc > 2) ? argv[2] : exp;  
        var path = (argc > 3) ? argv[3] : null;  
        var domain = (argc > 4) ? argv[4] : null;  
        var secure = (argc > 5) ? argv[5] : false;  
        document.cookie = name + "=" + escape (value) + 
            ((expires == null) ? "" : ("; expires=" + expires.toGMTString())) + 
            ((path == null) ? "" : ("; path=" + path)) +  
            ((domain == null) ? "" : ("; domain=" + domain)) +    
            ((secure == true) ? "; secure" : "");
    },
    deleteCookie:function(name)
    {
        var exp = new Date(); 
        exp.setTime(exp.getTime() - (30*24*60*60*1000));
        Util.CookieHelper.setCookie(name,"",exp);
    }
};

/*******************************/
/***** Utility *****/
/*******************************/
function EncodeQuery(p_q)
{
        try {p_q = encodeURIComponent(p_q);} catch(ex) {p_q = escape(p_q);}
        return p_q;
}

function DecodeQuery(p_q)
{
        try {p_q = decodeURIComponent(p_q);} catch(ex) {p_q = unescape(p_q);}
        return p_q;
}

function GetFirstNonBlankString() {
    // Iterate through the variable arguments list to find the first non-null, non-empty string value
    for (var i = 0; i != arguments.length; ++i)	{
        var x = arguments[i];
        if (!IsStringNullOrEmpty(x)) return x;
    }
    return null;
}
function IsStringNullOrEmpty(p_s) {
    //undefined, null, or empty
    return (!p_s || p_s.length == 0);
}
function ScrubInput(p_s) {
    //tab return newline ? ( ) < > ' " & #
    return p_s.replace(/[ \t\r\n?()<>'"&#]+/g, ' ');
}
function NormalizeWhitespace(p_s) {
    // Process the input string an convert any whitespace sequences into single spaces
    return p_s.replace(/\s+/g, ' ');
}
function ScrubQuery(p_q) {
    p_q = ScrubInput(p_q);
    var tmp = p_q.replace( / /g, "" ); // remove spaces to check query length
    if ( tmp.length > 0 ) {//the query is not empty, so return it
        p_q = EncodeQuery(p_q);
        return p_q;
    } else {
        return "";
    }
}
function SizeContents() {
    //size the topiclist and topiccontents divs to enable correct vertical scrolling
    var leftColIds = ['projects','search','faqnav','tocnav','dtnavlink','dtnavsubtext'];
    var oTList = document.getElementById("topiclist");
    var rightColIds = ['topicheader','topicfooter','topicfdbck'];
    var oTopic = document.getElementById("topiccontents");
    var availHeight; var usedHeight = 0; var hFactor = 62;
    //get the height of the area that contains the document
    var currWinHeight;
    if (window.innerHeight) {//FireFox with correction for status bar at bottom of window
        currWinHeight = (!IsHC()) ? window.innerHeight - 22 : window.innerHeight - 10;
    } else if (document.documentElement.clientHeight) {//IE 7 with correction for address bar
        currWinHeight = (!IsHC()) ? document.documentElement.clientHeight - 24 : document.documentElement.clientHeight - 10;
    } else if (document.body.offsetHeight) {//IE 4+
        currWinHeight = (!IsHC()) ? document.body.offsetHeight - 5 : document.body.offsetHeight + 10;
    }
    // Size the topiclist div in the left column
    // 1st calculate the used height of the objects whose height does not change
    for (var i = 0; i < leftColIds.length; i++) {
        var oElem = document.getElementById(leftColIds[i]);
        if (oElem != null && typeof oElem == "object") {
            usedHeight += oElem.offsetHeight;
        }
        //alert("id:" + leftColIds[i] + "\n" + "elemHeight:" + oElem.offsetHeight);//DEBUG
    }
    // 2nd set the height of the topiclist div to the available height
    availHeight = currWinHeight - usedHeight - hFactor;
    if (availHeight >= 0) oTList.style.height = availHeight + "px";
    //alert("currWinHeight:" + currWinHeight + "\n" + "usedHeight:" + usedHeight + "\n" + "height:" + (currWinHeight - usedHeight - hFactor));//DEBUG
    // Size the topic div in the right column
    // 1st calculate the used height of the objects whose height does not change
    usedHeight = 0;
    for (var i = 0; i < rightColIds.length; i++) {
        var oElem = document.getElementById(rightColIds[i]);
        if (oElem != null && typeof oElem == "object") {
            usedHeight += oElem.offsetHeight;
        }
        //alert("id:" + rightColIds[i] + "\n" + "elemHeight:" + oElem.offsetHeight);//DEBUG
    }
    // 2nd set the height of the topic div to the available height
    availHeight = currWinHeight - usedHeight - hFactor + 22;
    if (IsIE7()) availHeight += 14;
    else if (IsFireFox()) availHeight += 17;
    if (availHeight >= 0) try{oTopic.style.height = availHeight + "px";} catch(e){}
    //alert("currWinHeight:" + currWinHeight + "\n" + "usedHeight:" + usedHeight + "\n" + "height:" + (currWinHeight - usedHeight));//DEBUG
}
var _agent = navigator.userAgent;
function IsIE() {
    return 	(_agent.indexOf("MSIE ") > -1);
}
function IEVersion() {
    var idx = _agent.indexOf("MSIE ");
    return parseFloat(_agent.substring(idx + 5,_agent.indexOf(";",idx)))
}
function IsIE6Plus() {
    return 	(IsIE() && IEVersion() >= 6.0);
}
function IsIE7() {
    return 	(IsIE() && IEVersion() >= 7.0);
}
function IsFireFox() {
    return (_agent.indexOf("Firefox") > -1);
}
function GetElemHeight(p_el) {
    if (p_el.innerHeight) return p_el.innerHeight;
    else if (p_el.clientHeight) return p_el.clientHeight;
    else return p_el.offsetHeight;
}
function GetWinHeight() {
    if (window.innerHeight) return window.innerHeight;
    else if (document.documentElement.clientHeight) return document.documentElement.clientHeight;
    else if (document.body.offsetHeight) return document.body.offsetHeight;
    else return _winHeight;
}
function GetWinWidth() {
    if (window.innerWidth) return window.innerWidth;
    else if (document.documentElement.clientWidth) return document.documentElement.clientWidth;
    else if (document.body.offsetWidth) return document.body.offsetWidth;
    else return _winWidth;
}
function rt(p_name) {//related topic link click
    MapLog.RelatedLinkClick(p_name);//Omniture
    HT.show(p_name);
    return false;
}
function st(p_name) {//TOC link click
    return TL.clickLink(p_name)
}
function ttb(p_bkid) {//TOC book click
    TOC.bookClick(p_bkid);
    return false;
}
function tti(p_id,p_ev) {//TOC image event
    TOC.toggleImg(p_id,p_ev)
}
function ShowMovie(p_file,p_features){
    if (IsStringNullOrEmpty(p_features)) p_features = "width=640,height=480";
    OpenNewWin(GetContentUrlPath(p_file)+".htm","moviewin",p_features);
    MapLog.VideoLinkClick(p_file);//Omniture
}
function GetContentUrlPath(p_file) {
    return _targetedPath + _mkt + "/" + HT.getCurrentTopicProject() + "/content/" + p_file;
}
function GoToSupport(p_url) {
    if (p_url.indexOf("support.live") > -1 || p_url.indexOf("support.msn") > -1) { 
        p_url += (p_url.indexOf("?") == -1) ? "?" : "&";
        p_url += "sid=" + _sid;
        
        // pass the query type along to support
        p_url += "&mapquerytype=" + _querytype;
        
        // pass the query along to support 
        p_url += "&mapquery=" + _queryOriginal;;

    }
    MapLog.UserSentToSupport();//omniture
    if (IsHC()) {
        try {top.location.href = p_url;}//open within the Tango frame
        catch(e){OpenNewWin(p_url,"supwin","");}//error so open in new window
    }
    else {
        p_url += (p_url.indexOf("?") == -1) ? "?" : "&";
        p_url += "sid=" + _sid + "&project=" + Proj.getCurrentProject() + "&market=" + _mkt;

        if (_cuWriteCookie == "true") {
            ContactUs.Utils.processKeywords();
            ContactUs.Utils.setContactUsCookie();
        }
        if (_cuWinMode == "SameWindow") {
            OpenThisWin(p_url); // open in MAP window
        } else {
            OpenNewWin(p_url,"supwin","");//open in new window
        }
    }
    return false;
}
function OpenNewWin(p_url,p_name,p_features) {
    //if no other instructions then assure new window is full featured
    if (IsStringNullOrEmpty(p_features)) p_features = "resizable=yes,location=yes,menubar=yes,scrollbars=yes,status=yes,titlebar=yes,toolbar=yes";
    var win = null;
    try{win = window.open(p_url,p_name,p_features);}
    catch(e){win = window.open(p_url,"_blank",p_features);}//handles ie6 bug
    if (win != null && typeof win == 'object') win.focus();
}
function OpenThisWin(p_url) {
    document.location.href = p_url;
    
}
function IsHC() {//Help Central?
    return (_fmt == 'b2');
}
function IsRTL() {//RTL language?
    return (document.body.dir == 'rtl');
}
function HandleOnLoad() {
    // resolve _sid variable 
    SID.resolveGlobalSessionId();
    // set session guid on interactionobject
    MapLog.SetSessionId(_sid);
    InitIframeFunctionality();
    TH.initialize();
    var qt = _querytype.toLowerCase();
    var q = DecodeQuery(_query);
    if (qt == 'topic') {
        document.title = _appTitle; // change the title back to the approved string
        HT.topicDisplayedOnLoad(q);
        FAQ.getFAQ();
    } else if (qt == 'keyword' || qt == 'search') {
        if (q.toLowerCase() == _faqKey){
            FAQ.showFAQ();
            if (DecisionTree.isEnabled()){
                DecisionTree.show(true,null);
            } else {
                HT.showWelcome();
            }
        }
        else {
            q = ScrubQuery(q);
            if (q.length > 0) {
                Search.getResults(qt,q);
                if (qt == 'search'){
                    if (Comm.exists()) CommSearch.getResults(q);
                }
            }
        }
    }
    CM.setMinLeft();
    Comm.displayHelpCommLink();
    Survey.InitSurvey();
    if (qt == 'keyword') {
        ContactUs.keywords = _queryOriginal.substring(0,255);
    }
}
function InitIframeFunctionality() {
    if (DecisionTree.isEnabled()) 
    { 
        DecisionTree.initialize(); 
    }
    DecisionTree.showLink();
}
function HandleWinResize() {
    SizeContents();
}
function HandleOnBeforeUnload() {
    try
    {
        Survey.ShowSurvey();
        MapLog.UserClosesHelp();//Omniture
    }
    catch (e) {}
}

//
// Get number of minutes since Jan 1st 1970
//
function GetCurrentMin() {
        var date = new Date();
        var mins = date.getTime()/60000;
        var currentTime = parseInt(mins);
        
        return currentTime;
}

var cacheWinHeight = null;


function FormatString(format) {
    var result = "";    
    for (var i=0;;) {
        // Find the next brace
        var next = format.indexOf("{", i);
        if (next < 0) {
            // Not found: copy the end of the string and break
            result += format.slice(i);
            break;
        }
        
        // Copy the string before the brace
        result += format.slice(i, next);
        i = next+1;
        
        // Check for double braces (which display as one and are not arguments)
        if (format.charAt(i) == '{') {
            result += '{';
            i++;
            continue;
        }
        
        // Find the closing brace
        var next = format.indexOf("}", i);
//        ##DEBUG debug.assert(next > 0, "Missing closing brace");
        
        // Get the string between the braces, and split it around the ':' (if any)
        var brace = format.slice(i, next).split(':');
//        ##DEBUG debug.assert(brace.length <= 2, "Incorrect format syntax: " + brace);
        
        var argNumber = ParseNumber(brace[0])+1;
//        ##DEBUG debug.assert(!isNaN(argNumber), brace[0] + " is not a number");
        var arg = arguments[argNumber];
        if (arg == null) {
            arg = '';
        }

        // If it has a toFormattedString method, call it.  Otherwise, call toString()
        if (arg.toFormattedString)
            result += arg.toFormattedString(brace[1] ? brace[1] : '');
        else
            result += arg.toString();
        
        i = next+1;
    }
    
    return result;
}

function ParseNumber(value) {
    if (!value || (value.length == 0)) {
        return 0;
    }
    return parseFloat(value);
}

function ReverseChars(text)
{
    var reverseText = "";
    for (var i = text.length-1; i >= 0; i -= 1) {
        reverseText += text.charAt(i);
    }
    return reverseText;
}

function TrimString(text)
{
    // \xA0 is hex character code for a  non-breaking space.
    return text.replace(/^[\s\xA0]+/, '').replace(/[\s\xA0]+$/, '');
}
/***** End Utility *****/

/***** Attach events *****/
window.onload = HandleOnLoad;
window.onresize = HandleWinResize;
window.onbeforeunload = HandleOnBeforeUnload;

/***** Survey Object *********/
function Survey() {}
Survey.InitSurvey = function() {
    if (_showSurvey)
    {
        Survey.project = Proj.getCurrentProject();
        Survey.market = (_mkt != null) ? _mkt.toLowerCase() : "";
        if (_querytype.toLowerCase() == "keyword") {
            Survey.keyword = _query;
        } else {
            Survey.keyword = "";
        }
        Survey.randNumMax = .01;
        Survey.markets = new Array("en-us", "en-ca");
        Survey.projects = new Array("wl_spaces", "onecarev2");
    }
}
Survey.ShowSurvey = function() {
    if (_showSurvey
        && Survey.IsSurveyProject()
        && Survey.UserWasRandomlySelected()
        && Survey.UserHasNotSeenSurvey()
        && Survey.IsSurveyMarket())
    {
        Survey.LaunchSurveyWindow();
        Survey.SetCookie();	
    }
}

Survey.LaunchSurveyWindow = function() {
    //Launch the page
    var url = "https://www.msnfeedback.com/perseus/surveys/961278308/70c6c6ca.htm"
               + "?keyword=" + Survey.keyword 
               + "&product_ID=" + Survey.project 
               + "&article_ID=" + Survey.GetTopic()
               + "&session_ID=" + _sid;
    //alert("DEBUG TEST: URL: " + url);
    window.open(url, "", "height=285,width=300,scrollbars=yes");
}

Survey.GetTopic = function() {
    var topic = TH.getCurrentTopic() ;
    switch (topic)
    {
        case "":
            topic = "Welcome.htm";
            break;
        case "wlgmh.htm":
            topic = "GetMoreHelp";
            break;
    }
    return topic;
}

Survey.SetCookie = function() {
    //Set a cookie that won't expire for a year, so that the user won't see it again
    var exp = new Date(); 
    exp.setTime(exp.getTime() + (365*24*60*60*1000));
    Util.CookieHelper.setCookie("seenSurvey", "1", exp, "/");
}

Survey.UserWasRandomlySelected = function() {
    var n = Math.random();
    //alert("DEBUG TEST: Rand num: " + n);
    return (n < Survey.randNumMax);
}

Survey.UserHasNotSeenSurvey = function() {
    var seenSurvey = Util.CookieHelper.getCookie("seenSurvey");
    //alert("DEBUG TEST: Seen survey: " + seenSurvey);
    return ( seenSurvey == null) ? true : false;
}

Survey.IsSurveyProject = function() {
    if (Survey.project != null)
    {
        Survey.project = Survey.project.toLowerCase();
        for (var i=0; i < Survey.projects.length; i++) {
            if (Survey.project == Survey.projects[i].toLowerCase()) {
                return true;
            }
        }
    }
    //alert(Survey.project);
    return false;
}

Survey.IsSurveyMarket = function() {
    if (Survey.market != null)
    {
        for (var i=0; i < Survey.markets.length; i++) {
            if (Survey.market == Survey.markets[i].toLowerCase()) {
                return true;
            }
        }
    }
    //alert("DEBUG TEST: Survey.IsSurveyMarket returning false");
    return false;
}

Survey.market;
Survey.project;
Survey.keyword; 
Survey.randNumMax;
Survey.markets;
Survey.projects;
/***** End Survey Object *****/

/***** DHTML Code for Topics *****/
//	Note: Many functions are designed for templates that have subtopic_choice (STC) radio buttons.
var _STCCntxt = "";
var _CurrCntxt = "";
var	_aCntxtElems;
var	_aCntxtRelElems;
/* Functions called from content */
function ccTest(p_val) {
    //Conditional content test
    return (V4Has(p_val) || AgentHas(p_val));
}
function topicOnLoad() {
    if (ExistsForm("SubtopicChoiceForm")) {
        // set the classNames of the elements that have context
        // or are related ancestors of the context elements
        _aCntxtElems = new Array('INSTRUCTIONS','MORE_INFO','LINK');
        _aCntxtRelElems = new Array('LINKS');
        HideCntxtCntnt(); //hide elements with context
        ResetSTCForm(); //assure subtopic choice buttons are unchecked and context is nothing
    } else {
        //ShowCntxtCntnt()
    }
}
function clickedSubtopicChoice(strContext) {
    SetSTCCntxt( strContext );//remember context
    HideCntxtCntnt();//1st hide context content
    ShowCntxtCntnt();//2nd show context content dependent on new context
}
function clickedSubtopicChoiceText(p_cntxt,p_id) {
    oSubtopicChoice = getElementById(p_id);
    oSubtopicChoice.checked = true;
    clickedSubtopicChoice(p_cntxt);
}
function toggleDefinition(p_id) {
    //Legacy for bCentral
    if ( getStylePropertyById(p_id,'display')=='none') setStylePropertyById(p_id,'display','inline');
    else setStylePropertyById(p_id,'display','none');
}
function toggleTips(p_elid,p_imgid) {
    var oTipsImageElement = getElementById(p_imgid);
    if ( getStylePropertyById(p_elid,'display')=='none') {
        setStylePropertyById(p_elid,'display','block');
        if (oTipsImageElement != null) oTipsImageElement.src = "../resources/neutral/arrowbluedown.gif";
    } else {
        setStylePropertyById(p_elid,'display','none' );
        if (oTipsImageElement != null) oTipsImageElement.src = "../resources/neutral/arrowblueright.gif";
    }
}
function TakeMeThereMSN(p_url) {
    //assure that the protocol is correct (http: or https:)
    p_url = location.protocol + p_url.substring(p_url.indexOf(":") + 1);
    var sWName = (typeof(_openername) != "undefined" && _openername != '') ? _openername : "_helpext";
    window.open(p_url,sWName);
}
/*Internal Functions*/
function V4Has(p_val) {
    if (typeof p_val == 'string' && p_val != "" && typeof v4 == 'string' && v4 != "") {
        var aV4 = v4.split(',');
        var aValues = p_val.split(',');
        for(i = 0; i < aV4.length; i++) {
            for(j = 0; j < aValues.length; j++) {
                if (aV4[i] == aValues[j]) return true;
            }
        }
    }	
    return false;
}
function AgentHas(p_val) {
    if (typeof p_val == 'string') {
        if (p_val != "") {
            var aValues = p_val.split(',');
            for(j = 0; j < aValues.length; j++) {
                if (navigator.userAgent.indexOf(aValues[j]) != -1) return true;
            }
        }
    }	
    return false;
}
function ResetSTCForm() {
    if ( ExistsForm("SubtopicChoiceForm") ) {
        //uncheck all SubtopicChoice radio elements
        var oRadioGroup = document.forms["SubtopicChoiceForm"].SubtopicChoice;
        for (var i = 0; i < oRadioGroup.length; i++) {
            oRadioGroup[i].checked = false;
        }
        SetSTCCntxt("");//set subtopic_choice context to nothing
    }
}
function SetCurrCntxt() {_CurrCntxt = GetSTCCntxt();}//Set current context
function SetSTCCntxt(p_cntxt) {_STCCntxt = p_cntxt;}//Set subtopic_choice context
function GetSTCCntxt() {return _STCCntxt;}//Get subtopic_choice context
function GetElemCntxt(p_el) {
    //The context is contained in the id attribute
    return (p_el.id) ? p_el.id : "";
}
function IsCntxtElem(p_el) {
    // Is p_el an element that uses the id attribute to indicate the context?
    for (var i=0; i < _aCntxtElems.length; i++)	{
        if (p_el.className == _aCntxtElems[i]) return true;
    }
    return false;
}
function IsCntxtRelElem(p_el) {
    // Is p_el an element whose display depends on a child elements context?
    for (var i=0; i < _aCntxtRelElems.length; i++) {
        if (p_el.className == _aCntxtRelElems[i]) return true;
    }
    return false;
}
function ShowCntxtCntnt() {
    // Display all elements appropriate for the context
    var e;
    var eLinks;
    //First, assure that current context is up-to-date
    SetCurrCntxt();
    if (document.all) {
        for (var i = 0; i != document.all.length; i++) {
            e = document.all[i];
            if (e.className == 'LINKS') eLinks = e;
            ShowCntntForCntxtElem(e,eLinks);
        }
    } else if (document.getElementsByTagName) {
        //elements with INSTRUCTIONS, MORE_INFO, LINKS className are <div> tags
        var elems = document.getElementsByTagName("div");
        for (var i = 0; i != elems.length; i++) {
            e = elems[i];
            if (e.className == 'LINKS') eLinks = e;
            ShowCntntForCntxtElem(e,eLinks);
        }
        //elements with LINK className are <a> tags
        elems = document.getElementsByTagName("a");
        for (var i = 0; i != elems.length; i++) {
            e = elems[i];
            ShowCntntForCntxtElem(e,eLinks);
        }
    }
}
function HasTheCntxt(strElementContext,strCurrentContext) {
    // Does element have current context?
    var aElemCntxt = strElementContext.split(",");
    for (var i = 0; i < aElemCntxt.length; i++) {
        if (aElemCntxt[i] == _CurrCntxt) return true;
    }
    return false;
}
function ShowCntntForCntxtElem(p_el,p_links) {
    if (IsCntxtElem(p_el))	{
        if (HasTheCntxt(GetElemCntxt(p_el),_CurrCntxt))	{
            if (p_el.className == 'LINK') setStylePropertyByElement( p_links, 'display', '' ); // display the related LINKS container
            if (p_el.className == 'SUBTOPIC_CHOICE') {
                var oSubtopicChoicesElement = getElementById('SUBTOPIC_CHOICES');
                if (oSubtopicChoicesElement != null) setStylePropertyByElement( oSubtopicChoicesElement, 'display', '' ); // display the related LINKS container
            }
            setStylePropertyByElement(p_el,'display','');
        } else {
            setStylePropertyByElement(p_el,'display','none');
        }
    }
}
function HideCntntForCntxtElem(p_el) {
    if ( (IsCntxtElem(p_el)) || (IsCntxtRelElem(p_el)) ) {
        setStylePropertyByElement( p_el, 'display', 'none' );
    }
}
function HideCntxtCntnt() {
    // Hide all elements that have context
    if (document.all) {
        for (var i = 0; i != document.all.length; i++) {
            HideCntntForCntxtElem(document.all[i]);
        }
    } else if (document.getElementsByTagName) {
        //elements with INSTRUCTIONS, MORE_INFO, LINKS className are <div> tags
        var elems = document.getElementsByTagName("div");
        for (var i = 0; i != elems.length; i++) {
            HideCntntForCntxtElem(elems[i]);
        }
        //elements with LINK className are <a> tags
        elems = document.getElementsByTagName("a");
        for (var i = 0; i != elems.length; i++) {
            HideCntntForCntxtElem(elems[i]);
        }
    }
}
/***** End Original Dynamic Help Code (Pane Help and HTML Help) *****/
/***** Generic Cross Browser Code *****/
function blur(p_el) {p_el.blur();}
function ExistsForm(p_name) {
    var form = document.forms[p_name];
    return (form != null && typeof form == "object");
}
function getElementById(p_id) {
    if (document.getElementById) return document.getElementById( p_id );
    else if (document.all) return document.all[p_id];
    else return null;
}
function getElementObject(p_el) {
    if (typeof p_el == "object") return p_el;
    else if (typeof p_el == "string") return getElementById( p_el );
}
function getStyleBySelector(p_sel) {
    if (!document.getElementById) return null;
    var sheets = document.styleSheets;
    var rules; var i; var j;
    //look through stylesheets in reverse order that they appear in the document
    for (i=sheets.length-1; i >= 0; i--) {
        rules = sheets[i].cssRules;
        for (j=0; j<rules.length; j++) {
            if (rules[j].type == CSSRule.STYLE_RULE && rules[j].selectorText == p_sel) {
                return rules[j].style;
            }   
        }
    }
    return null;
}
function getStylePropertyById(p_id,p_prop) {
    if (document.getElementById) {
        var oS = document.getElementById( p_id );
        if (oS != null) {
            oS = oS.style;
            if (oS[p_prop]) return oS[ p_prop ];
        }
        oS = getStyleBySelector( "#" + p_id );
        return (oS != null) ? oS[p_prop] : null;
    } else if (document.all) {
        return document.all[p_id].style[p_prop];
    } else {
        return "";
    }
}
function setStylePropertyById(p_id,p_prop,p_val) {
    if (document.getElementById) {
        var oS = document.getElementById(p_id);
        if (oS != null) {
            oS = oS.style;
            oS[p_prop] = p_val;
        }
    } else if (document.all) {
        if (document.all[p_id] != null)	document.all[p_id].style[p_prop] = p_val;
    } else {} //so Nav4 won't return error
}
function setStylePropertyByElement(p_el,p_prop,p_val ) {
    if (document.getElementById) {
        var oS = p_el;
        if (oS != null) {
            oS = oS.style;
            oS[p_prop] = p_val;
        }
    } else if (document.all) {
        if (p_el != null) p_el.style[p_prop] = p_val;
    } else {} //so Nav4 won't return error
}
function toggleElementDisplay(p_el,p_style) {
    // p_style = (none,block,inline)
    var id;
    if (typeof p_el == "object") id = p_el.id;
    else if (typeof p_el == "string") id = p_el;
    if ((id != "") && (id != null)) {
        if (getStylePropertyById(id,'display')=='none') {
            setStylePropertyById(id,'display',p_style);
            //Omniture logging
            if (id.indexOf(_megaInstIdKey) > -1) {
                MapLog.MegaInstructionClick(id);
            }
        } else {
            setStylePropertyById(id,'display','none');
        }
    }
}
function toggleImg(p_el,p_img1,p_img2) {
    var e = getElementObject(p_el);
    if (e != null) {
        // p_img1 may be like ../resources/neutral/arrowblueright.gif
        // so need to get only the image name and compare to image current displayed
        var indx = p_img1.lastIndexOf("/");
        var imgName = (indx != -1) ? p_img1.substring(indx + 1,p_img1.length) : p_img1;
        var strSrc = e.src;
        e.src = (strSrc.indexOf(imgName) > -1) ? e.src = p_img2 : e.src = p_img1;
    }
}
function changeImg(p_el,p_img) {
    var e = getElementObject(p_el);
    if (e != null) e.src = p_img;
}
/***** End Generic Cross-Browser Code *****/

