﻿// namespace
if(!window.com) com = new Object();
if(!com.TI) com.TI = new Object();
if(!com.TI.IMSDS) com.TI.IMSDS = new Object();
if(!com.TI.IMSDS.ProductLinking) com.TI.IMSDS.ProductLinking = new Object();
if(!com.TI.IMSDS.ProductLinking.Config) com.TI.IMSDS.ProductLinking.Config = new Object();
if(!com.TI.IMSDS.ProductLinking.Global) com.TI.IMSDS.ProductLinking.Global = new Object();

// config
com.TI.IMSDS.ProductLinking.Config.startnode = document.body;
com.TI.IMSDS.ProductLinking.Config.skipTagNames = [
        "a",
        "embed",
        "applet",
        "button",
        "frameset",
        "h1",
        "h2",
        "h3",
        "h4",
        "h5",
        "h6",
        "head",
        "iframe",
        "img",
        "input",
        "label",
        "map",
        "meta",
        "noscript",
        "object",
        "script",
        "select",
        "sub",
        "sup",
        "textarea"
    ];
com.TI.IMSDS.ProductLinking.Config.lookupUrlJS = "/Utility/js/ProductLinking/com.TI.IMSDS.ProductLinking.LookupJS.aspx?p={0}";
com.TI.IMSDS.ProductLinking.Config.lookupUrlXML = "/Utility/js/ProductLinking/com.TI.IMSDS.ProductLinking.LookupCSV.aspx?p={0}";
//com.TI.IMSDS.ProductLinking.Config.productfolderURL = "http://focus.ti.com/docs/prod/folders/print/{0}.html";
com.TI.IMSDS.ProductLinking.Config.productfolderURL = "http://focus-webapps.ti.com/general/docs/sitesearch/searchdevice.tsp?partNumber={0}";
com.TI.IMSDS.ProductLinking.Config.xmlHttpRequestMethod = "POST";  // "GET" or "POST"
com.TI.IMSDS.ProductLinking.Config.matchPatterns = [/\b[a-z|0-9]*([0-9]{1,}[a-z]{1,}|[a-z]{1,}[0-9]{1,})(-([a-z|0-9|\.]{1,}))*\b/ig, /\bR[FI]-[a-z0-9]{3}-[a-z0-9]{4}(-[a-z0-9]{1,})*\b/ig];
com.TI.IMSDS.ProductLinking.Config.OnDemandScriptID = "com.TI.IMSDS.ProductLinking.OnDemandJSLookup";
com.TI.IMSDS.ProductLinking.Config.toolTip = "Link to Product Folder";
com.TI.IMSDS.ProductLinking.Config.DEBUG_ENABLED = false;

// global variables
com.TI.IMSDS.ProductLinking.Global.potentialHash = new Array();
com.TI.IMSDS.ProductLinking.Global.lookupResults = undefined;
com.TI.IMSDS.ProductLinking.Global.serverLookupJSPoller = undefined;
com.TI.IMSDS.ProductLinking.Global.xmlRequest = undefined;

// debug
com.TI.IMSDS.ProductLinking.DEBUG = function(text) { if(com.TI.IMSDS.ProductLinking.Config.DEBUG_ENABLED == true) alert(text); }

// common
com.TI.IMSDS.ProductLinking.CrawlDOM = function(fn) {
    com.TI.IMSDS.ProductLinking.RecurseNode(com.TI.IMSDS.ProductLinking.Config.startnode, fn);
}
com.TI.IMSDS.ProductLinking.RecurseNode = function(node, fn) {
    if(node.tagName) {
        for(var i in com.TI.IMSDS.ProductLinking.Config.skipTagNames) {
            if(node.tagName.toLowerCase() == com.TI.IMSDS.ProductLinking.Config.skipTagNames[i]) return;
        }
    }
    if(node.nodeType == 3) fn(node);    // textnode only
    if(node.hasChildNodes()) {
        for(var i = 0; i < node.childNodes.length; i++) {
            com.TI.IMSDS.ProductLinking.RecurseNode(node.childNodes[i], fn);
        }
    }
}
com.TI.IMSDS.ProductLinking.SearchNode = function(node) {
    for(var i = 0; i < com.TI.IMSDS.ProductLinking.Config.matchPatterns.length; i++) {
        var matches = node.nodeValue.match(com.TI.IMSDS.ProductLinking.Config.matchPatterns[i]);
        if(matches && (matches.length > 0)) {
            for(var i = 0; i < matches.length; i++) {
                matches[i] = matches[i].toUpperCase();
                com.TI.IMSDS.ProductLinking.Global.potentialHash[matches[i]] = matches[i];
            }
        }
    }
}
com.TI.IMSDS.ProductLinking.ReplacePartNumbers = function(node) {
    var validPattern = "\\b" + com.TI.IMSDS.ProductLinking.Global.lookupResults.join().replace(/,/g, "\\b|\\b") + "\\b";
    var rxp = new RegExp(validPattern, "ig");
    var matches = node.nodeValue.match(rxp);
    if(matches && (matches.length > 0)) {
        var subs = node.nodeValue.split(rxp);
        var fragment = document.createDocumentFragment();
        for(var i = 0; i < matches.length; i++) {
            if((node.nodeValue.indexOf(matches[i]) == 0) && (subs[0] != "")) subs.unshift("");  // IE "split" bug
            if(subs[i]) fragment.appendChild(document.createTextNode(subs[i]));
            var url = com.TI.IMSDS.ProductLinking.Config.productfolderURL.replace("{0}", matches[i].toLowerCase());
            var link = document.createElement("a");
            link.setAttribute("href", url);
            link.setAttribute("title", com.TI.IMSDS.ProductLinking.Config.toolTip);
            link.innerHTML = matches[i];
            fragment.appendChild(link);
        }
        if(subs[i]) fragment.appendChild(document.createTextNode(subs[i]));
        node.parentNode.replaceChild(fragment, node);
    }
}

// XMLHTTPRequest
com.TI.IMSDS.ProductLinking.LoadXMLDoc = function(url, fn) {
    req = false;
    if(window.XMLHttpRequest && !(window.ActiveXObject)) {
        try {
            com.TI.IMSDS.ProductLinking.Global.xmlRequest = new XMLHttpRequest();
        }
        catch(e) {
            com.TI.IMSDS.ProductLinking.Global.xmlRequest = false;
        }
    }
    else if(window.ActiveXObject) {
        try {
            com.TI.IMSDS.ProductLinking.Global.xmlRequest = new ActiveXObject("Msxml2.XMLHTTP");
        }
        catch(e) {
            try {
                com.TI.IMSDS.ProductLinking.Global.xmlRequest = new ActiveXObject("Microsoft.XMLHTTP");
            }
            catch(e) {
                com.TI.IMSDS.ProductLinking.Global.xmlRequest = false;
            }
        }
    }
    if(com.TI.IMSDS.ProductLinking.Global.xmlRequest) {
        com.TI.IMSDS.ProductLinking.Global.xmlRequest.onreadystatechange = fn;
        if(com.TI.IMSDS.ProductLinking.Config.xmlHttpRequestMethod == "GET") {    // GET
            com.TI.IMSDS.ProductLinking.Global.xmlRequest.open("GET", url, true);
            com.TI.IMSDS.ProductLinking.Global.xmlRequest.send(null);
        }
        else {  // POST
            var urlParts = url.split("?");
            var baseURL = urlParts[0];
            var params = urlParts[1];
            com.TI.IMSDS.ProductLinking.Global.xmlRequest.open("POST", baseURL, true);
            com.TI.IMSDS.ProductLinking.Global.xmlRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            com.TI.IMSDS.ProductLinking.Global.xmlRequest.setRequestHeader("Content-length", params.length);
            com.TI.IMSDS.ProductLinking.Global.xmlRequest.setRequestHeader("Connection", "close");
            com.TI.IMSDS.ProductLinking.Global.xmlRequest.send(params);
        }
    }
}
com.TI.IMSDS.ProductLinking.DoServerLookupXML = function() {
    var potentialArray = new Array();
    for(var i in com.TI.IMSDS.ProductLinking.Global.potentialHash) {
        potentialArray.push(com.TI.IMSDS.ProductLinking.Global.potentialHash[i]);
    }
    com.TI.IMSDS.ProductLinking.DEBUG("PotentialArray:" + potentialArray);
    if(potentialArray.length > 0) {
        var src = com.TI.IMSDS.ProductLinking.Config.lookupUrlXML.replace("{0}", escape(potentialArray));
        com.TI.IMSDS.ProductLinking.LoadXMLDoc(src, com.TI.IMSDS.ProductLinking.DoReplaceXML);
    }
}
com.TI.IMSDS.ProductLinking.DoReplaceXML = function() {
    if(com.TI.IMSDS.ProductLinking.Global.xmlRequest.readyState == 4) {
        if(com.TI.IMSDS.ProductLinking.Global.xmlRequest.status == 200) {
            com.TI.IMSDS.ProductLinking.DEBUG("com.TI.IMSDS.ProductLinking.Global.xmlRequest.responseText:" + com.TI.IMSDS.ProductLinking.Global.xmlRequest.responseText);
            if(com.TI.IMSDS.ProductLinking.Global.xmlRequest.responseText.length == 0) return;
            com.TI.IMSDS.ProductLinking.Global.lookupResults = com.TI.IMSDS.ProductLinking.Global.xmlRequest.responseText.split(",");
            com.TI.IMSDS.ProductLinking.DEBUG("com.TI.IMSDS.ProductLinking.Global.lookupResults:" + com.TI.IMSDS.ProductLinking.Global.lookupResults);
            if(com.TI.IMSDS.ProductLinking.Global.lookupResults.length > 0) {
                com.TI.IMSDS.ProductLinking.CrawlDOM(com.TI.IMSDS.ProductLinking.ReplacePartNumbers);
            }
        }
        else {
            com.TI.IMSDS.ProductLinking.DEBUG("There was a problem retrieving the XML data:\n" + com.TI.IMSDS.ProductLinking.Global.xmlRequest.statusText);
        }
    }
}

// on-demand javascript
com.TI.IMSDS.ProductLinking.DoServerLookupJS = function() {
    var potentialArray = new Array();
    for(var i in com.TI.IMSDS.ProductLinking.Global.potentialHash) {
        potentialArray.push(com.TI.IMSDS.ProductLinking.Global.potentialHash[i]);
    }
    com.TI.IMSDS.ProductLinking.DEBUG("PotentialArray:" + potentialArray);
    if(potentialArray.length > 0) {
        var src = com.TI.IMSDS.ProductLinking.Config.lookupUrlJS.replace("{0}", escape(potentialArray));
        var head = document.getElementsByTagName("head")[0];
        var script = document.getElementById(com.TI.IMSDS.ProductLinking.Config.OnDemandScriptID);
        if(script) head.removeChild(script);
        script = document.createElement("script");
        script.setAttribute("id", com.TI.IMSDS.ProductLinking.Config.OnDemandScriptID);
        script.setAttribute("type", "text/javascript");
        script.setAttribute("src", src);
        head.appendChild(script);
        com.TI.IMSDS.ProductLinking.Global.serverLookupJSPoller = setInterval("com.TI.IMSDS.ProductLinking.DoReplaceJS()", 100);
    }
}
com.TI.IMSDS.ProductLinking.DoReplaceJS = function() {
    var script = document.getElementById(com.TI.IMSDS.ProductLinking.Config.OnDemandScriptID);
    if(script === undefined) {
        return;
    }
    if(com.TI.IMSDS.ProductLinking.Global.lookupResults === undefined) {
        return;
    }
    clearInterval(com.TI.IMSDS.ProductLinking.Global.serverLookupJSPoller);
    com.TI.IMSDS.ProductLinking.DEBUG("com.TI.IMSDS.ProductLinking.Global.lookupResults:" + com.TI.IMSDS.ProductLinking.Global.lookupResults);
    if(com.TI.IMSDS.ProductLinking.Global.lookupResults.length > 0) {
        com.TI.IMSDS.ProductLinking.CrawlDOM(com.TI.IMSDS.ProductLinking.ReplacePartNumbers);
    }
}

// main
com.TI.IMSDS.ProductLinking.AddLoadEvent = function(fn) {
    var oldonload = window.onload;
    if(typeof window.onload != 'function') {
        window.onload = fn;
    } else {
        window.onload = function() {
            if(oldonload) {
                oldonload();
            }
            fn();
        }
    }
}
com.TI.IMSDS.ProductLinking.MainJS = function() {
    com.TI.IMSDS.ProductLinking.CrawlDOM(com.TI.IMSDS.ProductLinking.SearchNode);
    com.TI.IMSDS.ProductLinking.DoServerLookupJS();
}
com.TI.IMSDS.ProductLinking.MainXML = function() {
    com.TI.IMSDS.ProductLinking.CrawlDOM(com.TI.IMSDS.ProductLinking.SearchNode);
    com.TI.IMSDS.ProductLinking.DoServerLookupXML();
}

// in-line
//com.TI.IMSDS.ProductLinking.AddLoadEvent(com.TI.IMSDS.ProductLinking.MainJS);
com.TI.IMSDS.ProductLinking.AddLoadEvent(com.TI.IMSDS.ProductLinking.MainXML);
