var IE = navigator.userAgent.indexOf('MSIE') != -1;

var initialized = false;
var oldOnload = window.onload;
window.onload = function () {
    if (!initialized) {
        initialized = true;
        initialize();
        if (oldOnload != null) oldOnload();
    }

}

function initialize() {
    if (IE) {
        initializeFontSize();

        if (window.location.hash.length > 1) highlightBookmark(window.location.hash);
        window.attachEvent('onhashchange', function () { highlightBookmark(window.location.hash); });
    }

    initializeExternalMethods();

}

/********************************
* Feedback
********************************/
function sendFeedback() {
    //var baseFeedbackUrl = "https://prdpre.home.agilent.com/agilent/editorial.jspx?ckey=2319489&id=2319489&lc=eng&cc=US"
    var baseFeedbackUrl = "https://www.home.agilent.com/agilent/editorial.jspx?cc=US&lc=eng&ckey=2319489&id=2319489"
    var queryString = "&tfa_Version=" + encodeURIComponent(getVersion()) + "&tfa_URL=" + encodeURIComponent(getTopicSubUrl());
    var feedbackUrl = baseFeedbackUrl + queryString;
    window.open(feedbackUrl);
}

function getTopicSubUrl() {
    var subUrl = "";
    var parts = document.location.href.split('/');
    // start from the end of the url and include each file/folder until reaching the webhelp folder or getting 3 levels of folders
    for (i = parts.length - 1; i >= parts.length - 4 && i >= 0; i--) {
        subUrl = parts[i] + "/" + subUrl;
        if (parts[i].toLowerCase().indexOf('webhelp') == 0) break;
    }

    return subUrl.substr(0, subUrl.length - 1);
}

function getVersion() {
    // in the Default.flmsp file, there should be a hidden div that contains a reference to the Glacier.VsaVersion variable
    if (versionDiv) return versionDiv.innerText.replace(/^\s+|\s+$/img, "");
    else return "";
}

/********************************
* Web vs. webbrowser control
* note: these methods depend on each help system folder starting with "WebHelp" (WebHelp-apiref, WebHelp-scpi, etc.)
********************************/
var isOnWeb = true;
top.specialMethods = new Object();
top.specialMethods.basePaths = new Object();
function initializeExternalMethods() {
    // if there are any members on the window.external object, we are running in the VsaHelpViewer or the DynamicHelpPanel.
    try {
        if (typeof (window.external) != 'undefined' && typeof (window.external.isDynamicHelp) != 'undefined') isOnWeb = false;
    } catch (e) { }

    // the mapping between help directory name and the corresponding help system name.
    top.specialMethods.helpDirNameToHelpSysName = {
        'webhelp': 'vsahelp',
        'wehelp-apiref': 'apiref',
        'webhelp-scpi': 'scpiref'
    }

    // determine base paths by finding a folder in the path that starts with "webhelp"
    var parts = top.location.href.split('/');
    basePath = "";
    for (i = 0; i < parts.length; i++) {
        if (parts[i].toLowerCase().indexOf('webhelp') == 0) {
            // set top.name appropriately if this is the first webhelp system that is opened
            var windowName = top.specialMethods.helpDirNameToHelpSysName[parts[i].toLowerCase()];
            if (typeof (windowName) != 'undefined' && top.name != windowName) top.name = windowName;
            break;
        }
        basePath += parts[i] + "/";
    }
    basePath = basePath.substr(0, basePath.length - 1); // chop off last slash

    top.specialMethods.basePaths = {
        'base': basePath,
        'apiref': basePath + "/WebHelp-apiref/webframe.html",
        'vsahelp': basePath + "/WebHelp/89600_CSH.htm",
        'scpiref': basePath + "/WebHelp-scpi/scpiref_CSH.htm"
    }
    top.specialMethods.cshCall = {
        'apiref': "?",
        'vsahelp': "#",
        'scpiref': "#"
    }
    // set up javascript methods for opening other help systems

    // opens a topic in the specified help system window.
    // path: path to topic relative to base directory of helpSystem (WebHelp-apiref folder if helpSystem='apiref', for example).
    // helpSystem: indicates the help system
    top.specialMethods.ShowTopic = top.specialMethods.showTopic = function (path, helpSystem) {
        if (isOnWeb) {
            try {
                var fullPath = top.specialMethods.basePaths[helpSystem];
                if (path != null) fullPath += top.specialMethods.cshCall[helpSystem] + path;

                window.open(fullPath, helpSystem);
            } catch (e) { }
        }
        else {
            window.external.showTopic(path, helpSystem);
        }
    }

    // opens a PDF in a separate window.  
    // path: absolute path (file:// or http:// etc) or relative path from base help directory
    top.specialMethods.OpenPDF = top.specialMethods.openPDF = function (path) {
        if (isOnWeb) {
            try {
                if (path.indexOf("://") != -1) window.open(path); // absolute path to PDF
                else {
                    window.open(top.specialMethods.basePaths.base + "/" + path);
                }
            } catch (e) { }
        }
        else {
            window.external.openPDF(path);
        }
    }

    top.specialMethods.OpenCHM = top.specialMethods.openCHM = function (path) {
        if (isOnWeb) {
            alert("This type of link is only supported when help is opened from the 89600B VSA software: \n\n" + path);
        }
        else {
            window.external.openCHM(path);
        }
    }
}


/**************************
Text size functions
**************************/
// text size ranges from -M to +M where 0 leaves the text the same size and M is the maximum text size
// text sizes are specified in number of increments, so M = -5 means text size = (1 + (-5 * increment)) * original text size
var textSizeIncrement = 0.15;
var textSizeCookieName = "textSizeCookie";
var textSizeMin = -4; // ~ 0.5x font size
var textSizeMax = 14; // ~ 3x font size
//var originalTextSize, originalTextSizeUnit;
function increaseTextSize() {
    setTextSize(Math.min(getTextSize() + 1, textSizeMax));
}

function decreaseTextSize() {
    setTextSize(Math.max(getTextSize() - 1, textSizeMin));
}

function setTextSize(size) {
    SetCookie(textSizeCookieName, size);

    factor = (1 + (size * textSizeIncrement));
    setStyle(document.body, "font-size", (factor * top._originalTextSize) + top._originalTextSizeUnit);
}

function getTextSize() {
    var currentSize = parseInt(GetCookie(textSizeCookieName));

    if (isNaN(currentSize) || currentSize > textSizeMax || currentSize < textSizeMin) return 0;
    else return currentSize;
}

function initializeFontSize() {
    if (window.external != null && window.external.isDynamicHelp) textSizeCookieName += "-dynamicHelp";
    var currentTextSize = getStyle(document.body, "font-size");
    var matchDigits = /(\d+)([^\d]*)/i;
    var match = matchDigits.exec(currentTextSize);
    top._originalTextSize = parseFloat(match[1]);
    top._originalTextSizeUnit = match[2];
    setTextSize(getTextSize());
}

function resetTextSize() {
    document.body.style.fontSize = "";
    DelCookie(textSizeCookieName);
}




/**************************** 
* Bookmark highlighting
***************************/
function onLinkClick(e) {
    if (e == null) e = event; // IE
    var srcElement = e.srcElement;
    if (srcElement == null) srcElement = e.currentTarget; // firefox

    var link = srcElement;
    if (link.hash != null && link.hash.length > 1) {
        return highlightBookmark(link.hash);
    }
    return true;
}
function highlightBookmark(hash) {
    if (blinking) cancelBlinkingNodes();
    var anchors = document.getElementsByTagName("a");
    for (var i = 0; i < anchors.length; i++) {
        if ("#" + anchors[i].name == hash) {

            // don't blink if this is an h1 node
            if (anchors[i].parentNode.tagName.toLowerCase() == "h1") return;

            // scroll to item but leave some room at the top of the page.  
            window.setTimeout(function () {
                var y = Math.max(0, getY(anchors[i]) - 100);
                window.scrollTo(0, y);
            }, 150);

            startBlinking(anchors[i].parentNode);
            return false;
        }
    }

    return true;
}

function getX(node) {
    var pos = 0;
    while (node != null) {
        pos += node.offsetLeft;
        node = node.offsetParent;
    }
    return pos;
}
function getY(node) {
    var pos = 0;
    while (node != null) {
        pos += node.offsetTop;
        node = node.offsetParent;
    }
    return pos;
}

var blinkState;
var blinkColor = "lightgreen";
var blinking, blinkTimeout, blinkingNode;
function startBlinking(node) {
    blinkingNode = node;
    blinkTimeout = window.setTimeout(function () { blinkNode(1, 300); }, 400);
}

function blinkNode(blinks, interval) {
    blinking = true;
    if (blinkState == "on") {
        blinkOff();
        if (blinks <= 0) {
            cancelBlinkingNodes();
            return;
        }
    }
    else {
        blinkOn();
        blinks--;
    }
    blinkTimeout = window.setTimeout(function () { blinkNode(blinks, interval); }, interval);
}

function blinkOff() {
    blinkState = "off";
    blinkingNode.style.backgroundColor = "";
}
function blinkOn() {
    blinkState = "on";
    blinkingNode.style.backgroundColor = blinkColor;
}
function cancelBlinkingNodes() {
    window.clearTimeout(blinkTimeout); // reset existing timeouts
    blinking = false;
    blinkOff();
}
/****************************
*  Cookie functions
****************************/
// adapted from http://msdn.microsoft.com/en-us/library/ms533693(VS.85).aspx
// Create a cookie with the specified name and value.
function SetCookie(name, value) {
    var cookie = name + "=" + escape(value);
    // Expires the cookie in one month
    var date = new Date();
    date.setYear(date.getYear() + 10);
    cookie += ("; expires=" + date.toUTCString());
    cookie += "; path=/";
    document.cookie = cookie;
}

// Retrieve the value of the cookie with the specified name.
function GetCookie(name) {
    // cookies are separated by semicolons
    var aCookie = document.cookie.split("; ");
    for (var i = 0; i < aCookie.length; i++) {
        // a name/value pair (a crumb) is separated by an equal sign
        var aCrumb = aCookie[i].split("=");
        if (name == aCrumb[0])
            return unescape(aCrumb[1]);
    }
    // a cookie with the requested name does not exist
    return null;
}

// Delete the cookie with the specified name.
function DelCookie(name) {
    document.cookie = name + "=nothing; expires=Fri, 31 Dec 1999 23:59:59 GMT; path=/";
}

/*************************
* Utility functions
*************************/
function fixFilenameCase(href) {
    /* NOTE: this function is not needed.
    set all all directories and filenames in path after "Subsystems" to lowercase to match
    the casing on the hard drive (lower case has been forced in the 89600 webhelp target 
    configuration file).
    */

    var segments = href.toString().split("/");
    var newUrl = segments[0];
    var i = 1; var subsystemsFound = false;
    while (i < segments.length) {
        if (subsystemsFound || segments[i - 1].toLowerCase() == "subsystems") {
            subsystemsFound = true;
            newUrl += "/" + segments[i].toLowerCase();
        }
        else {
            newUrl += "/" + segments[i];
        }
        i++;
    }

    return newUrl;
}

function setStyle(element, styleName, value) {
    var regexp = /-(\w)/ig;
    var match = regexp.exec(styleName);
    styleName = styleName.replace(regexp, match[1].toUpperCase());
    element.style[styleName] = value;
}
function getStyle(element, styleName) {
    if (document.defaultView != null) return document.defaultView.getComputedStyle(element, null).getPropertyValue(styleName);
    else {
        var regexp = /-(\w)/ig;
        var match = regexp.exec(styleName);
        if (match) styleName = styleName.replace(regexp, match[1].toUpperCase());
        return element.currentStyle[styleName];
    }
}